jsPsych/docs/demos/js/webgazer/webgazer.js

99913 lines
3.8 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*!
*
* WebGazer.js: Scalable Webcam EyeTracking Using User Interactions
* Copyright (c) 2016-2020, Brown HCI Group
* Licensed under GPLv3. Companies with a valuation of less than $1M can use WebGazer.js under LGPLv3.
*
*/
var webgazer = /******/ (function (modules) {
// webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if (installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/
}
/******/ // Create a new module (and put it into the cache)
/******/ var module = (installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {},
/******/
});
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/
}
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function (exports, name, getter) {
/******/ if (!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/
}
/******/
};
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function (exports) {
/******/ if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
/******/
}
/******/ Object.defineProperty(exports, "__esModule", { value: true });
/******/
};
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function (value, mode) {
/******/ if (mode & 1) value = __webpack_require__(value);
/******/ if (mode & 8) return value;
/******/ if (mode & 4 && typeof value === "object" && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, "default", { enumerable: true, value: value });
/******/ if (mode & 2 && typeof value != "string")
for (var key in value)
__webpack_require__.d(
ns,
key,
function (key) {
return value[key];
}.bind(null, key)
);
/******/ return ns;
/******/
};
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function (module) {
/******/ var getter =
module && module.__esModule
? /******/ function getDefault() {
return module["default"];
}
: /******/ function getModuleExports() {
return module;
};
/******/ __webpack_require__.d(getter, "a", getter);
/******/ return getter;
/******/
};
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function (object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
};
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__((__webpack_require__.s = 90));
/******/
})(
/************************************************************************/
/******/ [
/* 0 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "AdadeltaOptimizer", function () {
return /* reexport */ adadelta_optimizer_AdadeltaOptimizer;
});
__webpack_require__.d(__webpack_exports__, "AdagradOptimizer", function () {
return /* reexport */ adagrad_optimizer_AdagradOptimizer;
});
__webpack_require__.d(__webpack_exports__, "AdamOptimizer", function () {
return /* reexport */ adam_optimizer_AdamOptimizer;
});
__webpack_require__.d(__webpack_exports__, "AdamaxOptimizer", function () {
return /* reexport */ adamax_optimizer_AdamaxOptimizer;
});
__webpack_require__.d(__webpack_exports__, "MomentumOptimizer", function () {
return /* reexport */ momentum_optimizer_MomentumOptimizer;
});
__webpack_require__.d(__webpack_exports__, "Optimizer", function () {
return /* reexport */ optimizer_Optimizer;
});
__webpack_require__.d(__webpack_exports__, "RMSPropOptimizer", function () {
return /* reexport */ rmsprop_optimizer_RMSPropOptimizer;
});
__webpack_require__.d(__webpack_exports__, "SGDOptimizer", function () {
return /* reexport */ sgd_optimizer_SGDOptimizer;
});
__webpack_require__.d(__webpack_exports__, "Tensor", function () {
return /* reexport */ dist_tensor["a" /* Tensor */];
});
__webpack_require__.d(__webpack_exports__, "TensorBuffer", function () {
return /* reexport */ dist_tensor["b" /* TensorBuffer */];
});
__webpack_require__.d(__webpack_exports__, "Variable", function () {
return /* reexport */ dist_tensor["c" /* Variable */];
});
__webpack_require__.d(__webpack_exports__, "Rank", function () {
return /* reexport */ dist_types["a" /* Rank */];
});
__webpack_require__.d(__webpack_exports__, "sumOutType", function () {
return /* reexport */ dist_types["b" /* sumOutType */];
});
__webpack_require__.d(__webpack_exports__, "upcastType", function () {
return /* reexport */ dist_types["c" /* upcastType */];
});
__webpack_require__.d(__webpack_exports__, "add", function () {
return /* reexport */ add;
});
__webpack_require__.d(__webpack_exports__, "addN", function () {
return /* reexport */ addN;
});
__webpack_require__.d(__webpack_exports__, "atan2", function () {
return /* reexport */ atan2;
});
__webpack_require__.d(__webpack_exports__, "avgPool", function () {
return /* reexport */ avgPool;
});
__webpack_require__.d(__webpack_exports__, "avgPool3d", function () {
return /* reexport */ avgPool3d;
});
__webpack_require__.d(__webpack_exports__, "batchToSpaceND", function () {
return /* reexport */ batchToSpaceND;
});
__webpack_require__.d(__webpack_exports__, "batchNorm", function () {
return /* reexport */ batchNorm;
});
__webpack_require__.d(__webpack_exports__, "batchNorm2d", function () {
return /* reexport */ batchNorm2d;
});
__webpack_require__.d(__webpack_exports__, "batchNorm3d", function () {
return /* reexport */ batchNorm3d;
});
__webpack_require__.d(__webpack_exports__, "batchNorm4d", function () {
return /* reexport */ batchNorm4d;
});
__webpack_require__.d(__webpack_exports__, "broadcastTo", function () {
return /* reexport */ broadcastTo;
});
__webpack_require__.d(__webpack_exports__, "clone", function () {
return /* reexport */ clone;
});
__webpack_require__.d(__webpack_exports__, "complex", function () {
return /* reexport */ complex["a" /* complex */];
});
__webpack_require__.d(__webpack_exports__, "concat", function () {
return /* reexport */ concat;
});
__webpack_require__.d(__webpack_exports__, "concat1d", function () {
return /* reexport */ concat1d;
});
__webpack_require__.d(__webpack_exports__, "concat2d", function () {
return /* reexport */ concat2d;
});
__webpack_require__.d(__webpack_exports__, "concat3d", function () {
return /* reexport */ concat3d;
});
__webpack_require__.d(__webpack_exports__, "concat4d", function () {
return /* reexport */ concat4d;
});
__webpack_require__.d(__webpack_exports__, "conv1d", function () {
return /* reexport */ conv1d;
});
__webpack_require__.d(__webpack_exports__, "conv2d", function () {
return /* reexport */ conv2d;
});
__webpack_require__.d(__webpack_exports__, "conv2dTranspose", function () {
return /* reexport */ conv2dTranspose;
});
__webpack_require__.d(__webpack_exports__, "conv3d", function () {
return /* reexport */ conv3d;
});
__webpack_require__.d(__webpack_exports__, "conv3dTranspose", function () {
return /* reexport */ conv3dTranspose;
});
__webpack_require__.d(__webpack_exports__, "cumsum", function () {
return /* reexport */ cumsum;
});
__webpack_require__.d(__webpack_exports__, "depthToSpace", function () {
return /* reexport */ depthToSpace;
});
__webpack_require__.d(__webpack_exports__, "depthwiseConv2d", function () {
return /* reexport */ depthwiseConv2d;
});
__webpack_require__.d(__webpack_exports__, "diag", function () {
return /* reexport */ diag;
});
__webpack_require__.d(__webpack_exports__, "div", function () {
return /* reexport */ div;
});
__webpack_require__.d(__webpack_exports__, "divNoNan", function () {
return /* reexport */ divNoNan;
});
__webpack_require__.d(__webpack_exports__, "dot", function () {
return /* reexport */ dot;
});
__webpack_require__.d(__webpack_exports__, "elu", function () {
return /* reexport */ elu;
});
__webpack_require__.d(__webpack_exports__, "equal", function () {
return /* reexport */ equal;
});
__webpack_require__.d(__webpack_exports__, "eye", function () {
return /* reexport */ eye;
});
__webpack_require__.d(__webpack_exports__, "fill", function () {
return /* reexport */ fill;
});
__webpack_require__.d(__webpack_exports__, "floorDiv", function () {
return /* reexport */ floorDiv;
});
__webpack_require__.d(__webpack_exports__, "greater", function () {
return /* reexport */ greater;
});
__webpack_require__.d(__webpack_exports__, "greaterEqual", function () {
return /* reexport */ greaterEqual;
});
__webpack_require__.d(__webpack_exports__, "imag", function () {
return /* reexport */ imag["a" /* imag */];
});
__webpack_require__.d(__webpack_exports__, "leakyRelu", function () {
return /* reexport */ leakyRelu;
});
__webpack_require__.d(__webpack_exports__, "less", function () {
return /* reexport */ less;
});
__webpack_require__.d(__webpack_exports__, "lessEqual", function () {
return /* reexport */ lessEqual;
});
__webpack_require__.d(__webpack_exports__, "localResponseNormalization", function () {
return /* reexport */ localResponseNormalization;
});
__webpack_require__.d(__webpack_exports__, "matMul", function () {
return /* reexport */ matMul;
});
__webpack_require__.d(__webpack_exports__, "max", function () {
return /* reexport */ max_max;
});
__webpack_require__.d(__webpack_exports__, "maxPool", function () {
return /* reexport */ maxPool;
});
__webpack_require__.d(__webpack_exports__, "maxPool3d", function () {
return /* reexport */ maxPool3d;
});
__webpack_require__.d(__webpack_exports__, "maxPoolWithArgmax", function () {
return /* reexport */ maxPoolWithArgmax;
});
__webpack_require__.d(__webpack_exports__, "maximum", function () {
return /* reexport */ maximum;
});
__webpack_require__.d(__webpack_exports__, "minimum", function () {
return /* reexport */ minimum;
});
__webpack_require__.d(__webpack_exports__, "mod", function () {
return /* reexport */ mod;
});
__webpack_require__.d(__webpack_exports__, "mul", function () {
return /* reexport */ mul;
});
__webpack_require__.d(__webpack_exports__, "multinomial", function () {
return /* reexport */ multinomial;
});
__webpack_require__.d(__webpack_exports__, "notEqual", function () {
return /* reexport */ notEqual;
});
__webpack_require__.d(__webpack_exports__, "oneHot", function () {
return /* reexport */ oneHot;
});
__webpack_require__.d(__webpack_exports__, "outerProduct", function () {
return /* reexport */ outerProduct;
});
__webpack_require__.d(__webpack_exports__, "pad", function () {
return /* reexport */ pad_pad;
});
__webpack_require__.d(__webpack_exports__, "pad1d", function () {
return /* reexport */ pad1d;
});
__webpack_require__.d(__webpack_exports__, "pad2d", function () {
return /* reexport */ pad2d;
});
__webpack_require__.d(__webpack_exports__, "pad3d", function () {
return /* reexport */ pad3d;
});
__webpack_require__.d(__webpack_exports__, "pad4d", function () {
return /* reexport */ pad4d;
});
__webpack_require__.d(__webpack_exports__, "pool", function () {
return /* reexport */ pool;
});
__webpack_require__.d(__webpack_exports__, "pow", function () {
return /* reexport */ pow;
});
__webpack_require__.d(__webpack_exports__, "prelu", function () {
return /* reexport */ prelu;
});
__webpack_require__.d(__webpack_exports__, "rand", function () {
return /* reexport */ rand;
});
__webpack_require__.d(__webpack_exports__, "randomGamma", function () {
return /* reexport */ randomGamma;
});
__webpack_require__.d(__webpack_exports__, "randomNormal", function () {
return /* reexport */ randomNormal;
});
__webpack_require__.d(__webpack_exports__, "randomUniform", function () {
return /* reexport */ randomUniform;
});
__webpack_require__.d(__webpack_exports__, "real", function () {
return /* reexport */ real["a" /* real */];
});
__webpack_require__.d(__webpack_exports__, "relu", function () {
return /* reexport */ relu;
});
__webpack_require__.d(__webpack_exports__, "relu6", function () {
return /* reexport */ relu6;
});
__webpack_require__.d(__webpack_exports__, "selu", function () {
return /* reexport */ selu;
});
__webpack_require__.d(__webpack_exports__, "separableConv2d", function () {
return /* reexport */ separableConv2d;
});
__webpack_require__.d(__webpack_exports__, "spaceToBatchND", function () {
return /* reexport */ spaceToBatchND;
});
__webpack_require__.d(__webpack_exports__, "split", function () {
return /* reexport */ split;
});
__webpack_require__.d(__webpack_exports__, "square", function () {
return /* reexport */ square;
});
__webpack_require__.d(__webpack_exports__, "squaredDifference", function () {
return /* reexport */ squaredDifference;
});
__webpack_require__.d(__webpack_exports__, "sub", function () {
return /* reexport */ sub;
});
__webpack_require__.d(__webpack_exports__, "tile", function () {
return /* reexport */ tile;
});
__webpack_require__.d(__webpack_exports__, "truncatedNormal", function () {
return /* reexport */ truncatedNormal;
});
__webpack_require__.d(__webpack_exports__, "booleanMaskAsync", function () {
return /* reexport */ booleanMaskAsync;
});
__webpack_require__.d(__webpack_exports__, "reverse", function () {
return /* reexport */ reverse_reverse;
});
__webpack_require__.d(__webpack_exports__, "reverse1d", function () {
return /* reexport */ reverse1d;
});
__webpack_require__.d(__webpack_exports__, "reverse2d", function () {
return /* reexport */ reverse2d;
});
__webpack_require__.d(__webpack_exports__, "reverse3d", function () {
return /* reexport */ reverse3d;
});
__webpack_require__.d(__webpack_exports__, "reverse4d", function () {
return /* reexport */ reverse4d;
});
__webpack_require__.d(__webpack_exports__, "slice", function () {
return /* reexport */ slice;
});
__webpack_require__.d(__webpack_exports__, "slice1d", function () {
return /* reexport */ slice1d;
});
__webpack_require__.d(__webpack_exports__, "slice2d", function () {
return /* reexport */ slice2d;
});
__webpack_require__.d(__webpack_exports__, "slice3d", function () {
return /* reexport */ slice3d;
});
__webpack_require__.d(__webpack_exports__, "slice4d", function () {
return /* reexport */ slice4d;
});
__webpack_require__.d(__webpack_exports__, "abs", function () {
return /* reexport */ abs;
});
__webpack_require__.d(__webpack_exports__, "acos", function () {
return /* reexport */ acos;
});
__webpack_require__.d(__webpack_exports__, "acosh", function () {
return /* reexport */ acosh;
});
__webpack_require__.d(__webpack_exports__, "asin", function () {
return /* reexport */ asin;
});
__webpack_require__.d(__webpack_exports__, "asinh", function () {
return /* reexport */ asinh;
});
__webpack_require__.d(__webpack_exports__, "atan", function () {
return /* reexport */ atan;
});
__webpack_require__.d(__webpack_exports__, "atanh", function () {
return /* reexport */ atanh;
});
__webpack_require__.d(__webpack_exports__, "ceil", function () {
return /* reexport */ ceil;
});
__webpack_require__.d(__webpack_exports__, "clipByValue", function () {
return /* reexport */ clipByValue;
});
__webpack_require__.d(__webpack_exports__, "cos", function () {
return /* reexport */ cos;
});
__webpack_require__.d(__webpack_exports__, "cosh", function () {
return /* reexport */ cosh;
});
__webpack_require__.d(__webpack_exports__, "erf", function () {
return /* reexport */ erf;
});
__webpack_require__.d(__webpack_exports__, "exp", function () {
return /* reexport */ unary_ops_exp;
});
__webpack_require__.d(__webpack_exports__, "expm1", function () {
return /* reexport */ expm1;
});
__webpack_require__.d(__webpack_exports__, "floor", function () {
return /* reexport */ floor;
});
__webpack_require__.d(__webpack_exports__, "log", function () {
return /* reexport */ log;
});
__webpack_require__.d(__webpack_exports__, "log1p", function () {
return /* reexport */ log1p;
});
__webpack_require__.d(__webpack_exports__, "logSigmoid", function () {
return /* reexport */ logSigmoid;
});
__webpack_require__.d(__webpack_exports__, "neg", function () {
return /* reexport */ neg;
});
__webpack_require__.d(__webpack_exports__, "reciprocal", function () {
return /* reexport */ reciprocal;
});
__webpack_require__.d(__webpack_exports__, "round", function () {
return /* reexport */ round;
});
__webpack_require__.d(__webpack_exports__, "rsqrt", function () {
return /* reexport */ rsqrt;
});
__webpack_require__.d(__webpack_exports__, "sigmoid", function () {
return /* reexport */ sigmoid;
});
__webpack_require__.d(__webpack_exports__, "sign", function () {
return /* reexport */ sign;
});
__webpack_require__.d(__webpack_exports__, "isNaN", function () {
return /* reexport */ unary_ops_isNaN;
});
__webpack_require__.d(__webpack_exports__, "isInf", function () {
return /* reexport */ isInf;
});
__webpack_require__.d(__webpack_exports__, "isFinite", function () {
return /* reexport */ unary_ops_isFinite;
});
__webpack_require__.d(__webpack_exports__, "sin", function () {
return /* reexport */ sin;
});
__webpack_require__.d(__webpack_exports__, "sinh", function () {
return /* reexport */ sinh;
});
__webpack_require__.d(__webpack_exports__, "softplus", function () {
return /* reexport */ softplus;
});
__webpack_require__.d(__webpack_exports__, "sqrt", function () {
return /* reexport */ sqrt;
});
__webpack_require__.d(__webpack_exports__, "step", function () {
return /* reexport */ unary_ops_step;
});
__webpack_require__.d(__webpack_exports__, "tan", function () {
return /* reexport */ tan;
});
__webpack_require__.d(__webpack_exports__, "tanh", function () {
return /* reexport */ tanh;
});
__webpack_require__.d(__webpack_exports__, "all", function () {
return /* reexport */ reduction_ops_all;
});
__webpack_require__.d(__webpack_exports__, "any", function () {
return /* reexport */ any;
});
__webpack_require__.d(__webpack_exports__, "argMax", function () {
return /* reexport */ argMax;
});
__webpack_require__.d(__webpack_exports__, "argMin", function () {
return /* reexport */ argMin;
});
__webpack_require__.d(__webpack_exports__, "logSumExp", function () {
return /* reexport */ logSumExp;
});
__webpack_require__.d(__webpack_exports__, "mean", function () {
return /* reexport */ reduction_ops_mean;
});
__webpack_require__.d(__webpack_exports__, "min", function () {
return /* reexport */ reduction_ops_min;
});
__webpack_require__.d(__webpack_exports__, "moments", function () {
return /* reexport */ moments;
});
__webpack_require__.d(__webpack_exports__, "sum", function () {
return /* reexport */ sum;
});
__webpack_require__.d(__webpack_exports__, "prod", function () {
return /* reexport */ reduction_ops_prod;
});
__webpack_require__.d(__webpack_exports__, "equalStrict", function () {
return /* reexport */ equalStrict;
});
__webpack_require__.d(__webpack_exports__, "greaterEqualStrict", function () {
return /* reexport */ greaterEqualStrict;
});
__webpack_require__.d(__webpack_exports__, "greaterStrict", function () {
return /* reexport */ greaterStrict;
});
__webpack_require__.d(__webpack_exports__, "lessEqualStrict", function () {
return /* reexport */ lessEqualStrict;
});
__webpack_require__.d(__webpack_exports__, "lessStrict", function () {
return /* reexport */ lessStrict;
});
__webpack_require__.d(__webpack_exports__, "notEqualStrict", function () {
return /* reexport */ notEqualStrict;
});
__webpack_require__.d(__webpack_exports__, "addStrict", function () {
return /* reexport */ addStrict;
});
__webpack_require__.d(__webpack_exports__, "divStrict", function () {
return /* reexport */ divStrict;
});
__webpack_require__.d(__webpack_exports__, "maximumStrict", function () {
return /* reexport */ maximumStrict;
});
__webpack_require__.d(__webpack_exports__, "minimumStrict", function () {
return /* reexport */ minimumStrict;
});
__webpack_require__.d(__webpack_exports__, "modStrict", function () {
return /* reexport */ modStrict;
});
__webpack_require__.d(__webpack_exports__, "mulStrict", function () {
return /* reexport */ mulStrict;
});
__webpack_require__.d(__webpack_exports__, "powStrict", function () {
return /* reexport */ powStrict;
});
__webpack_require__.d(__webpack_exports__, "squaredDifferenceStrict", function () {
return /* reexport */ squaredDifferenceStrict;
});
__webpack_require__.d(__webpack_exports__, "subStrict", function () {
return /* reexport */ subStrict;
});
__webpack_require__.d(__webpack_exports__, "logicalAnd", function () {
return /* reexport */ logicalAnd;
});
__webpack_require__.d(__webpack_exports__, "logicalNot", function () {
return /* reexport */ logicalNot;
});
__webpack_require__.d(__webpack_exports__, "logicalOr", function () {
return /* reexport */ logicalOr;
});
__webpack_require__.d(__webpack_exports__, "logicalXor", function () {
return /* reexport */ logicalXor;
});
__webpack_require__.d(__webpack_exports__, "where", function () {
return /* reexport */ where;
});
__webpack_require__.d(__webpack_exports__, "whereAsync", function () {
return /* reexport */ whereAsync;
});
__webpack_require__.d(__webpack_exports__, "buffer", function () {
return /* reexport */ array_ops_buffer;
});
__webpack_require__.d(__webpack_exports__, "print", function () {
return /* reexport */ print;
});
__webpack_require__.d(__webpack_exports__, "cast", function () {
return /* reexport */ cast;
});
__webpack_require__.d(__webpack_exports__, "expandDims", function () {
return /* reexport */ expandDims;
});
__webpack_require__.d(__webpack_exports__, "reshape", function () {
return /* reexport */ reshape;
});
__webpack_require__.d(__webpack_exports__, "squeeze", function () {
return /* reexport */ squeeze;
});
__webpack_require__.d(__webpack_exports__, "stack", function () {
return /* reexport */ stack;
});
__webpack_require__.d(__webpack_exports__, "unstack", function () {
return /* reexport */ unstack;
});
__webpack_require__.d(__webpack_exports__, "setdiff1dAsync", function () {
return /* reexport */ setdiff1dAsync;
});
__webpack_require__.d(__webpack_exports__, "linspace", function () {
return /* reexport */ tensor_ops["a" /* linspace */];
});
__webpack_require__.d(__webpack_exports__, "ones", function () {
return /* reexport */ tensor_ops["b" /* ones */];
});
__webpack_require__.d(__webpack_exports__, "range", function () {
return /* reexport */ tensor_ops["d" /* range */];
});
__webpack_require__.d(__webpack_exports__, "scalar", function () {
return /* reexport */ tensor_ops["e" /* scalar */];
});
__webpack_require__.d(__webpack_exports__, "tensor", function () {
return /* reexport */ tensor_ops["f" /* tensor */];
});
__webpack_require__.d(__webpack_exports__, "tensor1d", function () {
return /* reexport */ tensor_ops["g" /* tensor1d */];
});
__webpack_require__.d(__webpack_exports__, "tensor2d", function () {
return /* reexport */ tensor_ops["h" /* tensor2d */];
});
__webpack_require__.d(__webpack_exports__, "tensor3d", function () {
return /* reexport */ tensor_ops["i" /* tensor3d */];
});
__webpack_require__.d(__webpack_exports__, "tensor4d", function () {
return /* reexport */ tensor_ops["j" /* tensor4d */];
});
__webpack_require__.d(__webpack_exports__, "tensor5d", function () {
return /* reexport */ tensor_ops["k" /* tensor5d */];
});
__webpack_require__.d(__webpack_exports__, "tensor6d", function () {
return /* reexport */ tensor_ops["l" /* tensor6d */];
});
__webpack_require__.d(__webpack_exports__, "variable", function () {
return /* reexport */ tensor_ops["m" /* variable */];
});
__webpack_require__.d(__webpack_exports__, "zeros", function () {
return /* reexport */ tensor_ops["n" /* zeros */];
});
__webpack_require__.d(__webpack_exports__, "onesLike", function () {
return /* reexport */ tensor_ops["c" /* onesLike */];
});
__webpack_require__.d(__webpack_exports__, "zerosLike", function () {
return /* reexport */ tensor_ops["o" /* zerosLike */];
});
__webpack_require__.d(__webpack_exports__, "transpose", function () {
return /* reexport */ transpose;
});
__webpack_require__.d(__webpack_exports__, "softmax", function () {
return /* reexport */ softmax;
});
__webpack_require__.d(__webpack_exports__, "logSoftmax", function () {
return /* reexport */ logSoftmax;
});
__webpack_require__.d(__webpack_exports__, "norm", function () {
return /* reexport */ norm_norm;
});
__webpack_require__.d(__webpack_exports__, "gather", function () {
return /* reexport */ gather;
});
__webpack_require__.d(__webpack_exports__, "unsortedSegmentSum", function () {
return /* reexport */ unsortedSegmentSum;
});
__webpack_require__.d(__webpack_exports__, "basicLSTMCell", function () {
return /* reexport */ basicLSTMCell;
});
__webpack_require__.d(__webpack_exports__, "multiRNNCell", function () {
return /* reexport */ multiRNNCell;
});
__webpack_require__.d(__webpack_exports__, "movingAverage", function () {
return /* reexport */ movingAverage;
});
__webpack_require__.d(__webpack_exports__, "stridedSlice", function () {
return /* reexport */ stridedSlice;
});
__webpack_require__.d(__webpack_exports__, "topk", function () {
return /* reexport */ topk;
});
__webpack_require__.d(__webpack_exports__, "scatterND", function () {
return /* reexport */ scatterND;
});
__webpack_require__.d(__webpack_exports__, "fft", function () {
return /* reexport */ fft;
});
__webpack_require__.d(__webpack_exports__, "ifft", function () {
return /* reexport */ ifft;
});
__webpack_require__.d(__webpack_exports__, "rfft", function () {
return /* reexport */ rfft;
});
__webpack_require__.d(__webpack_exports__, "irfft", function () {
return /* reexport */ irfft;
});
__webpack_require__.d(__webpack_exports__, "sparseToDense", function () {
return /* reexport */ sparseToDense;
});
__webpack_require__.d(__webpack_exports__, "gatherND", function () {
return /* reexport */ gatherND;
});
__webpack_require__.d(__webpack_exports__, "dropout", function () {
return /* reexport */ dropout;
});
__webpack_require__.d(__webpack_exports__, "hannWindow", function () {
return /* reexport */ hannWindow;
});
__webpack_require__.d(__webpack_exports__, "hammingWindow", function () {
return /* reexport */ hammingWindow;
});
__webpack_require__.d(__webpack_exports__, "frame", function () {
return /* reexport */ signal_ops_frame;
});
__webpack_require__.d(__webpack_exports__, "stft", function () {
return /* reexport */ stft;
});
__webpack_require__.d(__webpack_exports__, "inTopKAsync", function () {
return /* reexport */ inTopKAsync;
});
__webpack_require__.d(__webpack_exports__, "op", function () {
return /* reexport */ operation["a" /* op */];
});
__webpack_require__.d(__webpack_exports__, "image", function () {
return /* reexport */ image_ops_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "linalg", function () {
return /* reexport */ linalg_ops_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "losses", function () {
return /* reexport */ loss_ops_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "spectral", function () {
return /* reexport */ spectral_ops_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "fused", function () {
return /* reexport */ fused_ops_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "signal", function () {
return /* reexport */ signal_ops_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "Reduction", function () {
return /* reexport */ Reduction;
});
__webpack_require__.d(__webpack_exports__, "train", function () {
return /* reexport */ train;
});
__webpack_require__.d(__webpack_exports__, "enableProdMode", function () {
return /* reexport */ enableProdMode;
});
__webpack_require__.d(__webpack_exports__, "enableDebugMode", function () {
return /* reexport */ enableDebugMode;
});
__webpack_require__.d(__webpack_exports__, "disableDeprecationWarnings", function () {
return /* reexport */ disableDeprecationWarnings;
});
__webpack_require__.d(__webpack_exports__, "deprecationWarn", function () {
return /* reexport */ deprecationWarn;
});
__webpack_require__.d(__webpack_exports__, "disposeVariables", function () {
return /* reexport */ disposeVariables;
});
__webpack_require__.d(__webpack_exports__, "engine", function () {
return /* reexport */ globals_engine;
});
__webpack_require__.d(__webpack_exports__, "memory", function () {
return /* reexport */ memory;
});
__webpack_require__.d(__webpack_exports__, "profile", function () {
return /* reexport */ profile;
});
__webpack_require__.d(__webpack_exports__, "tidy", function () {
return /* reexport */ tidy;
});
__webpack_require__.d(__webpack_exports__, "dispose", function () {
return /* reexport */ dispose;
});
__webpack_require__.d(__webpack_exports__, "keep", function () {
return /* reexport */ keep;
});
__webpack_require__.d(__webpack_exports__, "time", function () {
return /* reexport */ time;
});
__webpack_require__.d(__webpack_exports__, "setBackend", function () {
return /* reexport */ setBackend;
});
__webpack_require__.d(__webpack_exports__, "ready", function () {
return /* reexport */ ready;
});
__webpack_require__.d(__webpack_exports__, "getBackend", function () {
return /* reexport */ getBackend;
});
__webpack_require__.d(__webpack_exports__, "removeBackend", function () {
return /* reexport */ removeBackend;
});
__webpack_require__.d(__webpack_exports__, "findBackend", function () {
return /* reexport */ findBackend;
});
__webpack_require__.d(__webpack_exports__, "findBackendFactory", function () {
return /* reexport */ findBackendFactory;
});
__webpack_require__.d(__webpack_exports__, "registerBackend", function () {
return /* reexport */ registerBackend;
});
__webpack_require__.d(__webpack_exports__, "backend", function () {
return /* reexport */ globals_backend;
});
__webpack_require__.d(__webpack_exports__, "setPlatform", function () {
return /* reexport */ setPlatform;
});
__webpack_require__.d(__webpack_exports__, "getKernel", function () {
return /* reexport */ kernel_registry["b" /* getKernel */];
});
__webpack_require__.d(__webpack_exports__, "getGradient", function () {
return /* reexport */ kernel_registry["a" /* getGradient */];
});
__webpack_require__.d(__webpack_exports__, "getKernelsForBackend", function () {
return /* reexport */ kernel_registry["c" /* getKernelsForBackend */];
});
__webpack_require__.d(__webpack_exports__, "registerKernel", function () {
return /* reexport */ kernel_registry["e" /* registerKernel */];
});
__webpack_require__.d(__webpack_exports__, "registerGradient", function () {
return /* reexport */ kernel_registry["d" /* registerGradient */];
});
__webpack_require__.d(__webpack_exports__, "unregisterKernel", function () {
return /* reexport */ kernel_registry["g" /* unregisterKernel */];
});
__webpack_require__.d(__webpack_exports__, "unregisterGradient", function () {
return /* reexport */ kernel_registry["f" /* unregisterGradient */];
});
__webpack_require__.d(__webpack_exports__, "customGrad", function () {
return /* reexport */ customGrad;
});
__webpack_require__.d(__webpack_exports__, "grad", function () {
return /* reexport */ gradients_grad;
});
__webpack_require__.d(__webpack_exports__, "grads", function () {
return /* reexport */ gradients_grads;
});
__webpack_require__.d(__webpack_exports__, "valueAndGrad", function () {
return /* reexport */ valueAndGrad;
});
__webpack_require__.d(__webpack_exports__, "valueAndGrads", function () {
return /* reexport */ valueAndGrads;
});
__webpack_require__.d(__webpack_exports__, "variableGrads", function () {
return /* reexport */ variableGrads;
});
__webpack_require__.d(__webpack_exports__, "Environment", function () {
return /* reexport */ environment["b" /* Environment */];
});
__webpack_require__.d(__webpack_exports__, "env", function () {
return /* reexport */ environment["c" /* env */];
});
__webpack_require__.d(__webpack_exports__, "ENV", function () {
return /* reexport */ environment["a" /* ENV */];
});
__webpack_require__.d(__webpack_exports__, "version_core", function () {
return /* reexport */ version;
});
__webpack_require__.d(__webpack_exports__, "nextFrame", function () {
return /* reexport */ browser_util["a" /* nextFrame */];
});
__webpack_require__.d(__webpack_exports__, "browser", function () {
return /* reexport */ browser_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "io", function () {
return /* reexport */ io_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "math", function () {
return /* reexport */ math_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "serialization", function () {
return /* reexport */ serialization_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "test_util", function () {
return /* reexport */ test_util_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "util", function () {
return /* reexport */ util;
});
__webpack_require__.d(__webpack_exports__, "backend_util", function () {
return /* reexport */ backend_util_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "tensor_util", function () {
return /* reexport */ tensor_util;
});
__webpack_require__.d(__webpack_exports__, "slice_util", function () {
return /* reexport */ slice_util_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "gather_util", function () {
return /* reexport */ gather_nd_util_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "scatter_util", function () {
return /* reexport */ scatter_nd_util_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "device_util", function () {
return /* reexport */ device_util;
});
__webpack_require__.d(__webpack_exports__, "kernel_impls", function () {
return /* reexport */ kernel_impls_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "KernelBackend", function () {
return /* reexport */ KernelBackend;
});
__webpack_require__.d(__webpack_exports__, "DataStorage", function () {
return /* reexport */ DataStorage;
});
__webpack_require__.d(__webpack_exports__, "Add", function () {
return /* reexport */ kernel_names["a" /* Add */];
});
__webpack_require__.d(__webpack_exports__, "AddN", function () {
return /* reexport */ kernel_names["b" /* AddN */];
});
__webpack_require__.d(__webpack_exports__, "Atan2", function () {
return /* reexport */ kernel_names["c" /* Atan2 */];
});
__webpack_require__.d(__webpack_exports__, "AvgPool", function () {
return /* reexport */ kernel_names["d" /* AvgPool */];
});
__webpack_require__.d(__webpack_exports__, "AvgPoolBackprop", function () {
return /* reexport */ kernel_names["g" /* AvgPoolBackprop */];
});
__webpack_require__.d(__webpack_exports__, "AvgPool3D", function () {
return /* reexport */ kernel_names["e" /* AvgPool3D */];
});
__webpack_require__.d(__webpack_exports__, "AvgPool3DBackprop", function () {
return /* reexport */ kernel_names["f" /* AvgPool3DBackprop */];
});
__webpack_require__.d(__webpack_exports__, "BatchMatMul", function () {
return /* reexport */ kernel_names["h" /* BatchMatMul */];
});
__webpack_require__.d(__webpack_exports__, "BatchToSpaceND", function () {
return /* reexport */ kernel_names["i" /* BatchToSpaceND */];
});
__webpack_require__.d(__webpack_exports__, "BroadcastTo", function () {
return /* reexport */ kernel_names["j" /* BroadcastTo */];
});
__webpack_require__.d(__webpack_exports__, "Complex", function () {
return /* reexport */ kernel_names["k" /* Complex */];
});
__webpack_require__.d(__webpack_exports__, "Concat", function () {
return /* reexport */ kernel_names["l" /* Concat */];
});
__webpack_require__.d(__webpack_exports__, "Conv2D", function () {
return /* reexport */ kernel_names["m" /* Conv2D */];
});
__webpack_require__.d(__webpack_exports__, "Conv2DBackpropFilter", function () {
return /* reexport */ kernel_names["n" /* Conv2DBackpropFilter */];
});
__webpack_require__.d(__webpack_exports__, "Conv2DBackpropInput", function () {
return /* reexport */ kernel_names["o" /* Conv2DBackpropInput */];
});
__webpack_require__.d(__webpack_exports__, "Conv3D", function () {
return /* reexport */ kernel_names["p" /* Conv3D */];
});
__webpack_require__.d(__webpack_exports__, "Conv3DBackpropFilterV2", function () {
return /* reexport */ kernel_names["q" /* Conv3DBackpropFilterV2 */];
});
__webpack_require__.d(__webpack_exports__, "Conv3DBackpropInputV2", function () {
return /* reexport */ kernel_names["r" /* Conv3DBackpropInputV2 */];
});
__webpack_require__.d(__webpack_exports__, "Cumsum", function () {
return /* reexport */ kernel_names["s" /* Cumsum */];
});
__webpack_require__.d(__webpack_exports__, "DepthToSpace", function () {
return /* reexport */ kernel_names["t" /* DepthToSpace */];
});
__webpack_require__.d(__webpack_exports__, "DepthwiseConv2dNative", function () {
return /* reexport */ kernel_names["u" /* DepthwiseConv2dNative */];
});
__webpack_require__.d(
__webpack_exports__,
"DepthwiseConv2dNativeBackpropFilter",
function () {
return /* reexport */ kernel_names["v" /* DepthwiseConv2dNativeBackpropFilter */];
}
);
__webpack_require__.d(__webpack_exports__, "DepthwiseConv2dNativeBackpropInput", function () {
return /* reexport */ kernel_names["w" /* DepthwiseConv2dNativeBackpropInput */];
});
__webpack_require__.d(__webpack_exports__, "Diag", function () {
return /* reexport */ kernel_names["x" /* Diag */];
});
__webpack_require__.d(__webpack_exports__, "Div", function () {
return /* reexport */ kernel_names["y" /* Div */];
});
__webpack_require__.d(__webpack_exports__, "Elu", function () {
return /* reexport */ kernel_names["z" /* Elu */];
});
__webpack_require__.d(__webpack_exports__, "EluGrad", function () {
return /* reexport */ kernel_names["A" /* EluGrad */];
});
__webpack_require__.d(__webpack_exports__, "Equal", function () {
return /* reexport */ kernel_names["B" /* Equal */];
});
__webpack_require__.d(__webpack_exports__, "FloorDiv", function () {
return /* reexport */ kernel_names["D" /* FloorDiv */];
});
__webpack_require__.d(__webpack_exports__, "Fill", function () {
return /* reexport */ kernel_names["C" /* Fill */];
});
__webpack_require__.d(__webpack_exports__, "FusedBatchNorm", function () {
return /* reexport */ kernel_names["F" /* FusedBatchNorm */];
});
__webpack_require__.d(__webpack_exports__, "GatherNd", function () {
return /* reexport */ kernel_names["G" /* GatherNd */];
});
__webpack_require__.d(__webpack_exports__, "Greater", function () {
return /* reexport */ kernel_names["H" /* Greater */];
});
__webpack_require__.d(__webpack_exports__, "GreaterEqual", function () {
return /* reexport */ kernel_names["I" /* GreaterEqual */];
});
__webpack_require__.d(__webpack_exports__, "Identity", function () {
return /* reexport */ kernel_names["J" /* Identity */];
});
__webpack_require__.d(__webpack_exports__, "Imag", function () {
return /* reexport */ kernel_names["K" /* Imag */];
});
__webpack_require__.d(__webpack_exports__, "Less", function () {
return /* reexport */ kernel_names["N" /* Less */];
});
__webpack_require__.d(__webpack_exports__, "LessEqual", function () {
return /* reexport */ kernel_names["O" /* LessEqual */];
});
__webpack_require__.d(__webpack_exports__, "LRN", function () {
return /* reexport */ kernel_names["L" /* LRN */];
});
__webpack_require__.d(__webpack_exports__, "LRNBackprop", function () {
return /* reexport */ kernel_names["M" /* LRNBackprop */];
});
__webpack_require__.d(__webpack_exports__, "Max", function () {
return /* reexport */ kernel_names["P" /* Max */];
});
__webpack_require__.d(__webpack_exports__, "Maximum", function () {
return /* reexport */ kernel_names["V" /* Maximum */];
});
__webpack_require__.d(__webpack_exports__, "MaxPool", function () {
return /* reexport */ kernel_names["Q" /* MaxPool */];
});
__webpack_require__.d(__webpack_exports__, "MaxPoolBackprop", function () {
return /* reexport */ kernel_names["T" /* MaxPoolBackprop */];
});
__webpack_require__.d(__webpack_exports__, "MaxPool3D", function () {
return /* reexport */ kernel_names["R" /* MaxPool3D */];
});
__webpack_require__.d(__webpack_exports__, "MaxPool3DBackprop", function () {
return /* reexport */ kernel_names["S" /* MaxPool3DBackprop */];
});
__webpack_require__.d(__webpack_exports__, "MaxPoolWithArgmax", function () {
return /* reexport */ kernel_names["U" /* MaxPoolWithArgmax */];
});
__webpack_require__.d(__webpack_exports__, "Minimum", function () {
return /* reexport */ kernel_names["W" /* Minimum */];
});
__webpack_require__.d(__webpack_exports__, "Mod", function () {
return /* reexport */ kernel_names["X" /* Mod */];
});
__webpack_require__.d(__webpack_exports__, "Multiply", function () {
return /* reexport */ kernel_names["Y" /* Multiply */];
});
__webpack_require__.d(__webpack_exports__, "NotEqual", function () {
return /* reexport */ kernel_names["bb" /* NotEqual */];
});
__webpack_require__.d(__webpack_exports__, "NonMaxSuppressionV3", function () {
return /* reexport */ kernel_names["Z" /* NonMaxSuppressionV3 */];
});
__webpack_require__.d(__webpack_exports__, "NonMaxSuppressionV5", function () {
return /* reexport */ kernel_names["ab" /* NonMaxSuppressionV5 */];
});
__webpack_require__.d(__webpack_exports__, "OneHot", function () {
return /* reexport */ kernel_names["cb" /* OneHot */];
});
__webpack_require__.d(__webpack_exports__, "PadV2", function () {
return /* reexport */ kernel_names["db" /* PadV2 */];
});
__webpack_require__.d(__webpack_exports__, "Pool", function () {
return /* reexport */ kernel_names["eb" /* Pool */];
});
__webpack_require__.d(__webpack_exports__, "Pow", function () {
return /* reexport */ kernel_names["fb" /* Pow */];
});
__webpack_require__.d(__webpack_exports__, "Prelu", function () {
return /* reexport */ kernel_names["gb" /* Prelu */];
});
__webpack_require__.d(__webpack_exports__, "Real", function () {
return /* reexport */ kernel_names["hb" /* Real */];
});
__webpack_require__.d(__webpack_exports__, "Relu", function () {
return /* reexport */ kernel_names["ib" /* Relu */];
});
__webpack_require__.d(__webpack_exports__, "Relu6", function () {
return /* reexport */ kernel_names["jb" /* Relu6 */];
});
__webpack_require__.d(__webpack_exports__, "SelectV2", function () {
return /* reexport */ kernel_names["kb" /* SelectV2 */];
});
__webpack_require__.d(__webpack_exports__, "Selu", function () {
return /* reexport */ kernel_names["lb" /* Selu */];
});
__webpack_require__.d(__webpack_exports__, "SpaceToBatchND", function () {
return /* reexport */ kernel_names["mb" /* SpaceToBatchND */];
});
__webpack_require__.d(__webpack_exports__, "SplitV", function () {
return /* reexport */ kernel_names["nb" /* SplitV */];
});
__webpack_require__.d(__webpack_exports__, "SquaredDifference", function () {
return /* reexport */ kernel_names["pb" /* SquaredDifference */];
});
__webpack_require__.d(__webpack_exports__, "Square", function () {
return /* reexport */ kernel_names["ob" /* Square */];
});
__webpack_require__.d(__webpack_exports__, "Sub", function () {
return /* reexport */ kernel_names["qb" /* Sub */];
});
__webpack_require__.d(__webpack_exports__, "Tile", function () {
return /* reexport */ kernel_names["rb" /* Tile */];
});
__webpack_require__.d(__webpack_exports__, "Transpose", function () {
return /* reexport */ kernel_names["sb" /* Transpose */];
});
__webpack_require__.d(__webpack_exports__, "FromPixels", function () {
return /* reexport */ kernel_names["E" /* FromPixels */];
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/slice_util.js
var slice_util_namespaceObject = {};
__webpack_require__.r(slice_util_namespaceObject);
__webpack_require__.d(slice_util_namespaceObject, "assertParamsValid", function () {
return assertParamsValid;
});
__webpack_require__.d(slice_util_namespaceObject, "maskToAxes", function () {
return maskToAxes;
});
__webpack_require__.d(slice_util_namespaceObject, "computeOutShape", function () {
return slice_util_computeOutShape;
});
__webpack_require__.d(slice_util_namespaceObject, "stridesWithElidedDims", function () {
return stridesWithElidedDims;
});
__webpack_require__.d(slice_util_namespaceObject, "startIndicesWithElidedDims", function () {
return startIndicesWithElidedDims;
});
__webpack_require__.d(slice_util_namespaceObject, "stopIndicesWithElidedDims", function () {
return stopIndicesWithElidedDims;
});
__webpack_require__.d(slice_util_namespaceObject, "stridesForAxis", function () {
return stridesForAxis;
});
__webpack_require__.d(slice_util_namespaceObject, "startForAxis", function () {
return startForAxis;
});
__webpack_require__.d(slice_util_namespaceObject, "stopForAxis", function () {
return stopForAxis;
});
__webpack_require__.d(slice_util_namespaceObject, "isSliceContinous", function () {
return isSliceContinous;
});
__webpack_require__.d(slice_util_namespaceObject, "computeFlatOffset", function () {
return computeFlatOffset;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/io/io.js
var io_namespaceObject = {};
__webpack_require__.r(io_namespaceObject);
__webpack_require__.d(io_namespaceObject, "copyModel", function () {
return copyModel;
});
__webpack_require__.d(io_namespaceObject, "listModels", function () {
return listModels;
});
__webpack_require__.d(io_namespaceObject, "moveModel", function () {
return moveModel;
});
__webpack_require__.d(io_namespaceObject, "removeModel", function () {
return removeModel;
});
__webpack_require__.d(io_namespaceObject, "browserFiles", function () {
return browserFiles;
});
__webpack_require__.d(io_namespaceObject, "browserHTTPRequest", function () {
return browserHTTPRequest;
});
__webpack_require__.d(io_namespaceObject, "concatenateArrayBuffers", function () {
return io_utils["d" /* concatenateArrayBuffers */];
});
__webpack_require__.d(io_namespaceObject, "decodeWeights", function () {
return io_utils["e" /* decodeWeights */];
});
__webpack_require__.d(io_namespaceObject, "encodeWeights", function () {
return io_utils["f" /* encodeWeights */];
});
__webpack_require__.d(io_namespaceObject, "fromMemory", function () {
return fromMemory;
});
__webpack_require__.d(io_namespaceObject, "getLoadHandlers", function () {
return getLoadHandlers;
});
__webpack_require__.d(io_namespaceObject, "getModelArtifactsInfoForJSON", function () {
return io_utils["g" /* getModelArtifactsInfoForJSON */];
});
__webpack_require__.d(io_namespaceObject, "getSaveHandlers", function () {
return getSaveHandlers;
});
__webpack_require__.d(io_namespaceObject, "http", function () {
return http;
});
__webpack_require__.d(io_namespaceObject, "isHTTPScheme", function () {
return isHTTPScheme;
});
__webpack_require__.d(io_namespaceObject, "loadWeights", function () {
return loadWeights;
});
__webpack_require__.d(io_namespaceObject, "registerLoadRouter", function () {
return registerLoadRouter;
});
__webpack_require__.d(io_namespaceObject, "registerSaveRouter", function () {
return registerSaveRouter;
});
__webpack_require__.d(io_namespaceObject, "weightsLoaderFactory", function () {
return weightsLoaderFactory;
});
__webpack_require__.d(io_namespaceObject, "withSaveHandler", function () {
return withSaveHandler;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/math.js
var math_namespaceObject = {};
__webpack_require__.r(math_namespaceObject);
__webpack_require__.d(math_namespaceObject, "confusionMatrix", function () {
return confusionMatrix;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/browser.js
var browser_namespaceObject = {};
__webpack_require__.r(browser_namespaceObject);
__webpack_require__.d(browser_namespaceObject, "toPixels", function () {
return toPixels;
});
__webpack_require__.d(browser_namespaceObject, "fromPixels", function () {
return fromPixels;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/gather_nd_util.js
var gather_nd_util_namespaceObject = {};
__webpack_require__.r(gather_nd_util_namespaceObject);
__webpack_require__.d(gather_nd_util_namespaceObject, "prepareAndValidate", function () {
return prepareAndValidate;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/scatter_nd_util.js
var scatter_nd_util_namespaceObject = {};
__webpack_require__.r(scatter_nd_util_namespaceObject);
__webpack_require__.d(scatter_nd_util_namespaceObject, "validateUpdateShape", function () {
return validateUpdateShape;
});
__webpack_require__.d(scatter_nd_util_namespaceObject, "validateInput", function () {
return validateInput;
});
__webpack_require__.d(scatter_nd_util_namespaceObject, "calculateShapes", function () {
return calculateShapes;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/serialization.js
var serialization_namespaceObject = {};
__webpack_require__.r(serialization_namespaceObject);
__webpack_require__.d(serialization_namespaceObject, "Serializable", function () {
return Serializable;
});
__webpack_require__.d(serialization_namespaceObject, "SerializationMap", function () {
return SerializationMap;
});
__webpack_require__.d(serialization_namespaceObject, "registerClass", function () {
return registerClass;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/test_util.js
var test_util_namespaceObject = {};
__webpack_require__.r(test_util_namespaceObject);
__webpack_require__.d(test_util_namespaceObject, "TEST_EPSILON_FLOAT16", function () {
return TEST_EPSILON_FLOAT16;
});
__webpack_require__.d(test_util_namespaceObject, "expectArraysClose", function () {
return expectArraysClose;
});
__webpack_require__.d(test_util_namespaceObject, "testEpsilon", function () {
return testEpsilon;
});
__webpack_require__.d(test_util_namespaceObject, "expectPromiseToFail", function () {
return expectPromiseToFail;
});
__webpack_require__.d(test_util_namespaceObject, "expectArraysEqual", function () {
return expectArraysEqual;
});
__webpack_require__.d(test_util_namespaceObject, "expectNumbersClose", function () {
return expectNumbersClose;
});
__webpack_require__.d(test_util_namespaceObject, "expectValuesInRange", function () {
return expectValuesInRange;
});
__webpack_require__.d(test_util_namespaceObject, "expectArrayBuffersEqual", function () {
return expectArrayBuffersEqual;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/segment_util.js
var segment_util_namespaceObject = {};
__webpack_require__.r(segment_util_namespaceObject);
__webpack_require__.d(
segment_util_namespaceObject,
"segOpComputeOptimalWindowSize",
function () {
return segOpComputeOptimalWindowSize;
}
);
__webpack_require__.d(segment_util_namespaceObject, "computeOutShape", function () {
return segment_util_computeOutShape;
});
__webpack_require__.d(segment_util_namespaceObject, "collectGatherOpShapeInfo", function () {
return collectGatherOpShapeInfo;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/spectral_ops.js
var spectral_ops_namespaceObject = {};
__webpack_require__.r(spectral_ops_namespaceObject);
__webpack_require__.d(spectral_ops_namespaceObject, "fft", function () {
return fft;
});
__webpack_require__.d(spectral_ops_namespaceObject, "ifft", function () {
return ifft;
});
__webpack_require__.d(spectral_ops_namespaceObject, "rfft", function () {
return rfft;
});
__webpack_require__.d(spectral_ops_namespaceObject, "irfft", function () {
return irfft;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/signal_ops.js
var signal_ops_namespaceObject = {};
__webpack_require__.r(signal_ops_namespaceObject);
__webpack_require__.d(signal_ops_namespaceObject, "hannWindow", function () {
return hannWindow;
});
__webpack_require__.d(signal_ops_namespaceObject, "hammingWindow", function () {
return hammingWindow;
});
__webpack_require__.d(signal_ops_namespaceObject, "frame", function () {
return signal_ops_frame;
});
__webpack_require__.d(signal_ops_namespaceObject, "stft", function () {
return stft;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/loss_ops.js
var loss_ops_namespaceObject = {};
__webpack_require__.r(loss_ops_namespaceObject);
__webpack_require__.d(loss_ops_namespaceObject, "Reduction", function () {
return Reduction;
});
__webpack_require__.d(loss_ops_namespaceObject, "absoluteDifference", function () {
return absoluteDifference;
});
__webpack_require__.d(loss_ops_namespaceObject, "computeWeightedLoss", function () {
return computeWeightedLoss;
});
__webpack_require__.d(loss_ops_namespaceObject, "cosineDistance", function () {
return cosineDistance;
});
__webpack_require__.d(loss_ops_namespaceObject, "hingeLoss", function () {
return hingeLoss;
});
__webpack_require__.d(loss_ops_namespaceObject, "huberLoss", function () {
return huberLoss;
});
__webpack_require__.d(loss_ops_namespaceObject, "logLoss", function () {
return logLoss;
});
__webpack_require__.d(loss_ops_namespaceObject, "meanSquaredError", function () {
return meanSquaredError;
});
__webpack_require__.d(loss_ops_namespaceObject, "sigmoidCrossEntropy", function () {
return sigmoidCrossEntropy;
});
__webpack_require__.d(loss_ops_namespaceObject, "softmaxCrossEntropy", function () {
return softmaxCrossEntropy;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/linalg_ops.js
var linalg_ops_namespaceObject = {};
__webpack_require__.r(linalg_ops_namespaceObject);
__webpack_require__.d(linalg_ops_namespaceObject, "bandPart", function () {
return bandPart;
});
__webpack_require__.d(linalg_ops_namespaceObject, "gramSchmidt", function () {
return gramSchmidt;
});
__webpack_require__.d(linalg_ops_namespaceObject, "qr", function () {
return qr;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/image_ops.js
var image_ops_namespaceObject = {};
__webpack_require__.r(image_ops_namespaceObject);
__webpack_require__.d(image_ops_namespaceObject, "nonMaxSuppression", function () {
return nonMaxSuppression;
});
__webpack_require__.d(image_ops_namespaceObject, "resizeBilinear", function () {
return resizeBilinear;
});
__webpack_require__.d(image_ops_namespaceObject, "resizeNearestNeighbor", function () {
return resizeNearestNeighbor;
});
__webpack_require__.d(image_ops_namespaceObject, "nonMaxSuppressionAsync", function () {
return nonMaxSuppressionAsync;
});
__webpack_require__.d(image_ops_namespaceObject, "nonMaxSuppressionWithScore", function () {
return nonMaxSuppressionWithScore;
});
__webpack_require__.d(
image_ops_namespaceObject,
"nonMaxSuppressionWithScoreAsync",
function () {
return nonMaxSuppressionWithScoreAsync;
}
);
__webpack_require__.d(image_ops_namespaceObject, "cropAndResize", function () {
return cropAndResize;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/fused_ops.js
var fused_ops_namespaceObject = {};
__webpack_require__.r(fused_ops_namespaceObject);
__webpack_require__.d(fused_ops_namespaceObject, "matMul", function () {
return fused_ops_matMul;
});
__webpack_require__.d(fused_ops_namespaceObject, "conv2d", function () {
return fused_ops_conv2d;
});
__webpack_require__.d(fused_ops_namespaceObject, "depthwiseConv2d", function () {
return fused_ops_depthwiseConv2d;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/ops/ops.js
var ops_namespaceObject = {};
__webpack_require__.r(ops_namespaceObject);
__webpack_require__.d(ops_namespaceObject, "add", function () {
return add;
});
__webpack_require__.d(ops_namespaceObject, "addN", function () {
return addN;
});
__webpack_require__.d(ops_namespaceObject, "atan2", function () {
return atan2;
});
__webpack_require__.d(ops_namespaceObject, "avgPool", function () {
return avgPool;
});
__webpack_require__.d(ops_namespaceObject, "avgPool3d", function () {
return avgPool3d;
});
__webpack_require__.d(ops_namespaceObject, "batchToSpaceND", function () {
return batchToSpaceND;
});
__webpack_require__.d(ops_namespaceObject, "batchNorm", function () {
return batchNorm;
});
__webpack_require__.d(ops_namespaceObject, "batchNorm2d", function () {
return batchNorm2d;
});
__webpack_require__.d(ops_namespaceObject, "batchNorm3d", function () {
return batchNorm3d;
});
__webpack_require__.d(ops_namespaceObject, "batchNorm4d", function () {
return batchNorm4d;
});
__webpack_require__.d(ops_namespaceObject, "broadcastTo", function () {
return broadcastTo;
});
__webpack_require__.d(ops_namespaceObject, "clone", function () {
return clone;
});
__webpack_require__.d(ops_namespaceObject, "complex", function () {
return complex["a" /* complex */];
});
__webpack_require__.d(ops_namespaceObject, "concat", function () {
return concat;
});
__webpack_require__.d(ops_namespaceObject, "concat1d", function () {
return concat1d;
});
__webpack_require__.d(ops_namespaceObject, "concat2d", function () {
return concat2d;
});
__webpack_require__.d(ops_namespaceObject, "concat3d", function () {
return concat3d;
});
__webpack_require__.d(ops_namespaceObject, "concat4d", function () {
return concat4d;
});
__webpack_require__.d(ops_namespaceObject, "conv1d", function () {
return conv1d;
});
__webpack_require__.d(ops_namespaceObject, "conv2d", function () {
return conv2d;
});
__webpack_require__.d(ops_namespaceObject, "conv2dTranspose", function () {
return conv2dTranspose;
});
__webpack_require__.d(ops_namespaceObject, "conv3d", function () {
return conv3d;
});
__webpack_require__.d(ops_namespaceObject, "conv3dTranspose", function () {
return conv3dTranspose;
});
__webpack_require__.d(ops_namespaceObject, "cumsum", function () {
return cumsum;
});
__webpack_require__.d(ops_namespaceObject, "depthToSpace", function () {
return depthToSpace;
});
__webpack_require__.d(ops_namespaceObject, "depthwiseConv2d", function () {
return depthwiseConv2d;
});
__webpack_require__.d(ops_namespaceObject, "diag", function () {
return diag;
});
__webpack_require__.d(ops_namespaceObject, "div", function () {
return div;
});
__webpack_require__.d(ops_namespaceObject, "divNoNan", function () {
return divNoNan;
});
__webpack_require__.d(ops_namespaceObject, "dot", function () {
return dot;
});
__webpack_require__.d(ops_namespaceObject, "elu", function () {
return elu;
});
__webpack_require__.d(ops_namespaceObject, "equal", function () {
return equal;
});
__webpack_require__.d(ops_namespaceObject, "eye", function () {
return eye;
});
__webpack_require__.d(ops_namespaceObject, "fill", function () {
return fill;
});
__webpack_require__.d(ops_namespaceObject, "floorDiv", function () {
return floorDiv;
});
__webpack_require__.d(ops_namespaceObject, "greater", function () {
return greater;
});
__webpack_require__.d(ops_namespaceObject, "greaterEqual", function () {
return greaterEqual;
});
__webpack_require__.d(ops_namespaceObject, "imag", function () {
return imag["a" /* imag */];
});
__webpack_require__.d(ops_namespaceObject, "leakyRelu", function () {
return leakyRelu;
});
__webpack_require__.d(ops_namespaceObject, "less", function () {
return less;
});
__webpack_require__.d(ops_namespaceObject, "lessEqual", function () {
return lessEqual;
});
__webpack_require__.d(ops_namespaceObject, "localResponseNormalization", function () {
return localResponseNormalization;
});
__webpack_require__.d(ops_namespaceObject, "matMul", function () {
return matMul;
});
__webpack_require__.d(ops_namespaceObject, "max", function () {
return max_max;
});
__webpack_require__.d(ops_namespaceObject, "maxPool", function () {
return maxPool;
});
__webpack_require__.d(ops_namespaceObject, "maxPool3d", function () {
return maxPool3d;
});
__webpack_require__.d(ops_namespaceObject, "maxPoolWithArgmax", function () {
return maxPoolWithArgmax;
});
__webpack_require__.d(ops_namespaceObject, "maximum", function () {
return maximum;
});
__webpack_require__.d(ops_namespaceObject, "minimum", function () {
return minimum;
});
__webpack_require__.d(ops_namespaceObject, "mod", function () {
return mod;
});
__webpack_require__.d(ops_namespaceObject, "mul", function () {
return mul;
});
__webpack_require__.d(ops_namespaceObject, "multinomial", function () {
return multinomial;
});
__webpack_require__.d(ops_namespaceObject, "notEqual", function () {
return notEqual;
});
__webpack_require__.d(ops_namespaceObject, "oneHot", function () {
return oneHot;
});
__webpack_require__.d(ops_namespaceObject, "outerProduct", function () {
return outerProduct;
});
__webpack_require__.d(ops_namespaceObject, "pad", function () {
return pad_pad;
});
__webpack_require__.d(ops_namespaceObject, "pad1d", function () {
return pad1d;
});
__webpack_require__.d(ops_namespaceObject, "pad2d", function () {
return pad2d;
});
__webpack_require__.d(ops_namespaceObject, "pad3d", function () {
return pad3d;
});
__webpack_require__.d(ops_namespaceObject, "pad4d", function () {
return pad4d;
});
__webpack_require__.d(ops_namespaceObject, "pool", function () {
return pool;
});
__webpack_require__.d(ops_namespaceObject, "pow", function () {
return pow;
});
__webpack_require__.d(ops_namespaceObject, "prelu", function () {
return prelu;
});
__webpack_require__.d(ops_namespaceObject, "rand", function () {
return rand;
});
__webpack_require__.d(ops_namespaceObject, "randomGamma", function () {
return randomGamma;
});
__webpack_require__.d(ops_namespaceObject, "randomNormal", function () {
return randomNormal;
});
__webpack_require__.d(ops_namespaceObject, "randomUniform", function () {
return randomUniform;
});
__webpack_require__.d(ops_namespaceObject, "real", function () {
return real["a" /* real */];
});
__webpack_require__.d(ops_namespaceObject, "relu", function () {
return relu;
});
__webpack_require__.d(ops_namespaceObject, "relu6", function () {
return relu6;
});
__webpack_require__.d(ops_namespaceObject, "selu", function () {
return selu;
});
__webpack_require__.d(ops_namespaceObject, "separableConv2d", function () {
return separableConv2d;
});
__webpack_require__.d(ops_namespaceObject, "spaceToBatchND", function () {
return spaceToBatchND;
});
__webpack_require__.d(ops_namespaceObject, "split", function () {
return split;
});
__webpack_require__.d(ops_namespaceObject, "square", function () {
return square;
});
__webpack_require__.d(ops_namespaceObject, "squaredDifference", function () {
return squaredDifference;
});
__webpack_require__.d(ops_namespaceObject, "sub", function () {
return sub;
});
__webpack_require__.d(ops_namespaceObject, "tile", function () {
return tile;
});
__webpack_require__.d(ops_namespaceObject, "truncatedNormal", function () {
return truncatedNormal;
});
__webpack_require__.d(ops_namespaceObject, "booleanMaskAsync", function () {
return booleanMaskAsync;
});
__webpack_require__.d(ops_namespaceObject, "reverse", function () {
return reverse_reverse;
});
__webpack_require__.d(ops_namespaceObject, "reverse1d", function () {
return reverse1d;
});
__webpack_require__.d(ops_namespaceObject, "reverse2d", function () {
return reverse2d;
});
__webpack_require__.d(ops_namespaceObject, "reverse3d", function () {
return reverse3d;
});
__webpack_require__.d(ops_namespaceObject, "reverse4d", function () {
return reverse4d;
});
__webpack_require__.d(ops_namespaceObject, "slice", function () {
return slice;
});
__webpack_require__.d(ops_namespaceObject, "slice1d", function () {
return slice1d;
});
__webpack_require__.d(ops_namespaceObject, "slice2d", function () {
return slice2d;
});
__webpack_require__.d(ops_namespaceObject, "slice3d", function () {
return slice3d;
});
__webpack_require__.d(ops_namespaceObject, "slice4d", function () {
return slice4d;
});
__webpack_require__.d(ops_namespaceObject, "abs", function () {
return abs;
});
__webpack_require__.d(ops_namespaceObject, "acos", function () {
return acos;
});
__webpack_require__.d(ops_namespaceObject, "acosh", function () {
return acosh;
});
__webpack_require__.d(ops_namespaceObject, "asin", function () {
return asin;
});
__webpack_require__.d(ops_namespaceObject, "asinh", function () {
return asinh;
});
__webpack_require__.d(ops_namespaceObject, "atan", function () {
return atan;
});
__webpack_require__.d(ops_namespaceObject, "atanh", function () {
return atanh;
});
__webpack_require__.d(ops_namespaceObject, "ceil", function () {
return ceil;
});
__webpack_require__.d(ops_namespaceObject, "clipByValue", function () {
return clipByValue;
});
__webpack_require__.d(ops_namespaceObject, "cos", function () {
return cos;
});
__webpack_require__.d(ops_namespaceObject, "cosh", function () {
return cosh;
});
__webpack_require__.d(ops_namespaceObject, "erf", function () {
return erf;
});
__webpack_require__.d(ops_namespaceObject, "exp", function () {
return unary_ops_exp;
});
__webpack_require__.d(ops_namespaceObject, "expm1", function () {
return expm1;
});
__webpack_require__.d(ops_namespaceObject, "floor", function () {
return floor;
});
__webpack_require__.d(ops_namespaceObject, "log", function () {
return log;
});
__webpack_require__.d(ops_namespaceObject, "log1p", function () {
return log1p;
});
__webpack_require__.d(ops_namespaceObject, "logSigmoid", function () {
return logSigmoid;
});
__webpack_require__.d(ops_namespaceObject, "neg", function () {
return neg;
});
__webpack_require__.d(ops_namespaceObject, "reciprocal", function () {
return reciprocal;
});
__webpack_require__.d(ops_namespaceObject, "round", function () {
return round;
});
__webpack_require__.d(ops_namespaceObject, "rsqrt", function () {
return rsqrt;
});
__webpack_require__.d(ops_namespaceObject, "sigmoid", function () {
return sigmoid;
});
__webpack_require__.d(ops_namespaceObject, "sign", function () {
return sign;
});
__webpack_require__.d(ops_namespaceObject, "isNaN", function () {
return unary_ops_isNaN;
});
__webpack_require__.d(ops_namespaceObject, "isInf", function () {
return isInf;
});
__webpack_require__.d(ops_namespaceObject, "isFinite", function () {
return unary_ops_isFinite;
});
__webpack_require__.d(ops_namespaceObject, "sin", function () {
return sin;
});
__webpack_require__.d(ops_namespaceObject, "sinh", function () {
return sinh;
});
__webpack_require__.d(ops_namespaceObject, "softplus", function () {
return softplus;
});
__webpack_require__.d(ops_namespaceObject, "sqrt", function () {
return sqrt;
});
__webpack_require__.d(ops_namespaceObject, "step", function () {
return unary_ops_step;
});
__webpack_require__.d(ops_namespaceObject, "tan", function () {
return tan;
});
__webpack_require__.d(ops_namespaceObject, "tanh", function () {
return tanh;
});
__webpack_require__.d(ops_namespaceObject, "all", function () {
return reduction_ops_all;
});
__webpack_require__.d(ops_namespaceObject, "any", function () {
return any;
});
__webpack_require__.d(ops_namespaceObject, "argMax", function () {
return argMax;
});
__webpack_require__.d(ops_namespaceObject, "argMin", function () {
return argMin;
});
__webpack_require__.d(ops_namespaceObject, "logSumExp", function () {
return logSumExp;
});
__webpack_require__.d(ops_namespaceObject, "mean", function () {
return reduction_ops_mean;
});
__webpack_require__.d(ops_namespaceObject, "min", function () {
return reduction_ops_min;
});
__webpack_require__.d(ops_namespaceObject, "moments", function () {
return moments;
});
__webpack_require__.d(ops_namespaceObject, "sum", function () {
return sum;
});
__webpack_require__.d(ops_namespaceObject, "prod", function () {
return reduction_ops_prod;
});
__webpack_require__.d(ops_namespaceObject, "equalStrict", function () {
return equalStrict;
});
__webpack_require__.d(ops_namespaceObject, "greaterEqualStrict", function () {
return greaterEqualStrict;
});
__webpack_require__.d(ops_namespaceObject, "greaterStrict", function () {
return greaterStrict;
});
__webpack_require__.d(ops_namespaceObject, "lessEqualStrict", function () {
return lessEqualStrict;
});
__webpack_require__.d(ops_namespaceObject, "lessStrict", function () {
return lessStrict;
});
__webpack_require__.d(ops_namespaceObject, "notEqualStrict", function () {
return notEqualStrict;
});
__webpack_require__.d(ops_namespaceObject, "addStrict", function () {
return addStrict;
});
__webpack_require__.d(ops_namespaceObject, "divStrict", function () {
return divStrict;
});
__webpack_require__.d(ops_namespaceObject, "maximumStrict", function () {
return maximumStrict;
});
__webpack_require__.d(ops_namespaceObject, "minimumStrict", function () {
return minimumStrict;
});
__webpack_require__.d(ops_namespaceObject, "modStrict", function () {
return modStrict;
});
__webpack_require__.d(ops_namespaceObject, "mulStrict", function () {
return mulStrict;
});
__webpack_require__.d(ops_namespaceObject, "powStrict", function () {
return powStrict;
});
__webpack_require__.d(ops_namespaceObject, "squaredDifferenceStrict", function () {
return squaredDifferenceStrict;
});
__webpack_require__.d(ops_namespaceObject, "subStrict", function () {
return subStrict;
});
__webpack_require__.d(ops_namespaceObject, "logicalAnd", function () {
return logicalAnd;
});
__webpack_require__.d(ops_namespaceObject, "logicalNot", function () {
return logicalNot;
});
__webpack_require__.d(ops_namespaceObject, "logicalOr", function () {
return logicalOr;
});
__webpack_require__.d(ops_namespaceObject, "logicalXor", function () {
return logicalXor;
});
__webpack_require__.d(ops_namespaceObject, "where", function () {
return where;
});
__webpack_require__.d(ops_namespaceObject, "whereAsync", function () {
return whereAsync;
});
__webpack_require__.d(ops_namespaceObject, "buffer", function () {
return array_ops_buffer;
});
__webpack_require__.d(ops_namespaceObject, "print", function () {
return print;
});
__webpack_require__.d(ops_namespaceObject, "cast", function () {
return cast;
});
__webpack_require__.d(ops_namespaceObject, "expandDims", function () {
return expandDims;
});
__webpack_require__.d(ops_namespaceObject, "reshape", function () {
return reshape;
});
__webpack_require__.d(ops_namespaceObject, "squeeze", function () {
return squeeze;
});
__webpack_require__.d(ops_namespaceObject, "stack", function () {
return stack;
});
__webpack_require__.d(ops_namespaceObject, "unstack", function () {
return unstack;
});
__webpack_require__.d(ops_namespaceObject, "setdiff1dAsync", function () {
return setdiff1dAsync;
});
__webpack_require__.d(ops_namespaceObject, "linspace", function () {
return tensor_ops["a" /* linspace */];
});
__webpack_require__.d(ops_namespaceObject, "ones", function () {
return tensor_ops["b" /* ones */];
});
__webpack_require__.d(ops_namespaceObject, "range", function () {
return tensor_ops["d" /* range */];
});
__webpack_require__.d(ops_namespaceObject, "scalar", function () {
return tensor_ops["e" /* scalar */];
});
__webpack_require__.d(ops_namespaceObject, "tensor", function () {
return tensor_ops["f" /* tensor */];
});
__webpack_require__.d(ops_namespaceObject, "tensor1d", function () {
return tensor_ops["g" /* tensor1d */];
});
__webpack_require__.d(ops_namespaceObject, "tensor2d", function () {
return tensor_ops["h" /* tensor2d */];
});
__webpack_require__.d(ops_namespaceObject, "tensor3d", function () {
return tensor_ops["i" /* tensor3d */];
});
__webpack_require__.d(ops_namespaceObject, "tensor4d", function () {
return tensor_ops["j" /* tensor4d */];
});
__webpack_require__.d(ops_namespaceObject, "tensor5d", function () {
return tensor_ops["k" /* tensor5d */];
});
__webpack_require__.d(ops_namespaceObject, "tensor6d", function () {
return tensor_ops["l" /* tensor6d */];
});
__webpack_require__.d(ops_namespaceObject, "variable", function () {
return tensor_ops["m" /* variable */];
});
__webpack_require__.d(ops_namespaceObject, "zeros", function () {
return tensor_ops["n" /* zeros */];
});
__webpack_require__.d(ops_namespaceObject, "onesLike", function () {
return tensor_ops["c" /* onesLike */];
});
__webpack_require__.d(ops_namespaceObject, "zerosLike", function () {
return tensor_ops["o" /* zerosLike */];
});
__webpack_require__.d(ops_namespaceObject, "transpose", function () {
return transpose;
});
__webpack_require__.d(ops_namespaceObject, "softmax", function () {
return softmax;
});
__webpack_require__.d(ops_namespaceObject, "logSoftmax", function () {
return logSoftmax;
});
__webpack_require__.d(ops_namespaceObject, "norm", function () {
return norm_norm;
});
__webpack_require__.d(ops_namespaceObject, "gather", function () {
return gather;
});
__webpack_require__.d(ops_namespaceObject, "unsortedSegmentSum", function () {
return unsortedSegmentSum;
});
__webpack_require__.d(ops_namespaceObject, "basicLSTMCell", function () {
return basicLSTMCell;
});
__webpack_require__.d(ops_namespaceObject, "multiRNNCell", function () {
return multiRNNCell;
});
__webpack_require__.d(ops_namespaceObject, "movingAverage", function () {
return movingAverage;
});
__webpack_require__.d(ops_namespaceObject, "stridedSlice", function () {
return stridedSlice;
});
__webpack_require__.d(ops_namespaceObject, "topk", function () {
return topk;
});
__webpack_require__.d(ops_namespaceObject, "scatterND", function () {
return scatterND;
});
__webpack_require__.d(ops_namespaceObject, "fft", function () {
return fft;
});
__webpack_require__.d(ops_namespaceObject, "ifft", function () {
return ifft;
});
__webpack_require__.d(ops_namespaceObject, "rfft", function () {
return rfft;
});
__webpack_require__.d(ops_namespaceObject, "irfft", function () {
return irfft;
});
__webpack_require__.d(ops_namespaceObject, "sparseToDense", function () {
return sparseToDense;
});
__webpack_require__.d(ops_namespaceObject, "gatherND", function () {
return gatherND;
});
__webpack_require__.d(ops_namespaceObject, "dropout", function () {
return dropout;
});
__webpack_require__.d(ops_namespaceObject, "hannWindow", function () {
return hannWindow;
});
__webpack_require__.d(ops_namespaceObject, "hammingWindow", function () {
return hammingWindow;
});
__webpack_require__.d(ops_namespaceObject, "frame", function () {
return signal_ops_frame;
});
__webpack_require__.d(ops_namespaceObject, "stft", function () {
return stft;
});
__webpack_require__.d(ops_namespaceObject, "inTopKAsync", function () {
return inTopKAsync;
});
__webpack_require__.d(ops_namespaceObject, "op", function () {
return operation["a" /* op */];
});
__webpack_require__.d(ops_namespaceObject, "image", function () {
return image_ops_namespaceObject;
});
__webpack_require__.d(ops_namespaceObject, "linalg", function () {
return linalg_ops_namespaceObject;
});
__webpack_require__.d(ops_namespaceObject, "losses", function () {
return loss_ops_namespaceObject;
});
__webpack_require__.d(ops_namespaceObject, "spectral", function () {
return spectral_ops_namespaceObject;
});
__webpack_require__.d(ops_namespaceObject, "fused", function () {
return fused_ops_namespaceObject;
});
__webpack_require__.d(ops_namespaceObject, "signal", function () {
return signal_ops_namespaceObject;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/backends/backend_util.js
var backend_util_namespaceObject = {};
__webpack_require__.r(backend_util_namespaceObject);
__webpack_require__.d(backend_util_namespaceObject, "axesAreInnerMostDims", function () {
return axesAreInnerMostDims;
});
__webpack_require__.d(backend_util_namespaceObject, "combineLocations", function () {
return combineLocations;
});
__webpack_require__.d(backend_util_namespaceObject, "computeOutAndReduceShapes", function () {
return computeOutAndReduceShapes;
});
__webpack_require__.d(backend_util_namespaceObject, "expandShapeToKeepDim", function () {
return expandShapeToKeepDim;
});
__webpack_require__.d(
backend_util_namespaceObject,
"assertAxesAreInnerMostDims",
function () {
return assertAxesAreInnerMostDims;
}
);
__webpack_require__.d(backend_util_namespaceObject, "getAxesPermutation", function () {
return getAxesPermutation;
});
__webpack_require__.d(backend_util_namespaceObject, "getUndoAxesPermutation", function () {
return getUndoAxesPermutation;
});
__webpack_require__.d(backend_util_namespaceObject, "getInnerMostAxes", function () {
return getInnerMostAxes;
});
__webpack_require__.d(backend_util_namespaceObject, "getBroadcastDims", function () {
return getBroadcastDims;
});
__webpack_require__.d(backend_util_namespaceObject, "getReductionAxes", function () {
return getReductionAxes;
});
__webpack_require__.d(
backend_util_namespaceObject,
"assertAndGetBroadcastShape",
function () {
return assertAndGetBroadcastShape;
}
);
__webpack_require__.d(backend_util_namespaceObject, "assertParamsConsistent", function () {
return assertParamsConsistent;
});
__webpack_require__.d(backend_util_namespaceObject, "computeOutShape", function () {
return computeOutShape;
});
__webpack_require__.d(backend_util_namespaceObject, "computePool2DInfo", function () {
return computePool2DInfo;
});
__webpack_require__.d(backend_util_namespaceObject, "computePool3DInfo", function () {
return computePool3DInfo;
});
__webpack_require__.d(backend_util_namespaceObject, "computeConv2DInfo", function () {
return computeConv2DInfo;
});
__webpack_require__.d(backend_util_namespaceObject, "computeConv3DInfo", function () {
return computeConv3DInfo;
});
__webpack_require__.d(backend_util_namespaceObject, "computeDefaultPad", function () {
return computeDefaultPad;
});
__webpack_require__.d(backend_util_namespaceObject, "tupleValuesAreOne", function () {
return tupleValuesAreOne;
});
__webpack_require__.d(
backend_util_namespaceObject,
"eitherStridesOrDilationsAreOne",
function () {
return eitherStridesOrDilationsAreOne;
}
);
__webpack_require__.d(backend_util_namespaceObject, "convertConv2DDataFormat", function () {
return convertConv2DDataFormat;
});
__webpack_require__.d(backend_util_namespaceObject, "PARALLELIZE_THRESHOLD", function () {
return PARALLELIZE_THRESHOLD;
});
__webpack_require__.d(backend_util_namespaceObject, "computeOptimalWindowSize", function () {
return computeOptimalWindowSize;
});
__webpack_require__.d(backend_util_namespaceObject, "nonMaxSuppressionV3", function () {
return nonMaxSuppressionV3;
});
__webpack_require__.d(backend_util_namespaceObject, "nonMaxSuppressionV5", function () {
return nonMaxSuppressionV5;
});
__webpack_require__.d(backend_util_namespaceObject, "upcastType", function () {
return dist_types["c" /* upcastType */];
});
__webpack_require__.d(backend_util_namespaceObject, "getReshaped", function () {
return getReshaped;
});
__webpack_require__.d(backend_util_namespaceObject, "getPermuted", function () {
return getPermuted;
});
__webpack_require__.d(backend_util_namespaceObject, "getReshapedPermuted", function () {
return getReshapedPermuted;
});
__webpack_require__.d(backend_util_namespaceObject, "getSliceBeginCoords", function () {
return getSliceBeginCoords;
});
__webpack_require__.d(backend_util_namespaceObject, "getSliceSize", function () {
return getSliceSize;
});
__webpack_require__.d(backend_util_namespaceObject, "prepareAndValidate", function () {
return prepareAndValidate;
});
__webpack_require__.d(backend_util_namespaceObject, "validateUpdateShape", function () {
return validateUpdateShape;
});
__webpack_require__.d(backend_util_namespaceObject, "validateInput", function () {
return validateInput;
});
__webpack_require__.d(backend_util_namespaceObject, "calculateShapes", function () {
return calculateShapes;
});
__webpack_require__.d(backend_util_namespaceObject, "SELU_SCALEALPHA", function () {
return SELU_SCALEALPHA;
});
__webpack_require__.d(backend_util_namespaceObject, "SELU_SCALE", function () {
return SELU_SCALE;
});
__webpack_require__.d(backend_util_namespaceObject, "shouldFuse", function () {
return shouldFuse;
});
__webpack_require__.d(backend_util_namespaceObject, "ERF_P", function () {
return ERF_P;
});
__webpack_require__.d(backend_util_namespaceObject, "ERF_A1", function () {
return ERF_A1;
});
__webpack_require__.d(backend_util_namespaceObject, "ERF_A2", function () {
return ERF_A2;
});
__webpack_require__.d(backend_util_namespaceObject, "ERF_A3", function () {
return ERF_A3;
});
__webpack_require__.d(backend_util_namespaceObject, "ERF_A4", function () {
return ERF_A4;
});
__webpack_require__.d(backend_util_namespaceObject, "ERF_A5", function () {
return ERF_A5;
});
__webpack_require__.d(backend_util_namespaceObject, "warn", function () {
return warn;
});
__webpack_require__.d(backend_util_namespaceObject, "log", function () {
return log_log;
});
__webpack_require__.d(backend_util_namespaceObject, "mergeRealAndImagArrays", function () {
return mergeRealAndImagArrays;
});
__webpack_require__.d(backend_util_namespaceObject, "splitRealAndImagArrays", function () {
return splitRealAndImagArrays;
});
__webpack_require__.d(backend_util_namespaceObject, "complexWithEvenIndex", function () {
return complexWithEvenIndex;
});
__webpack_require__.d(backend_util_namespaceObject, "complexWithOddIndex", function () {
return complexWithOddIndex;
});
__webpack_require__.d(backend_util_namespaceObject, "getComplexWithIndex", function () {
return getComplexWithIndex;
});
__webpack_require__.d(backend_util_namespaceObject, "assignToTypedArray", function () {
return assignToTypedArray;
});
__webpack_require__.d(backend_util_namespaceObject, "exponents", function () {
return exponents;
});
__webpack_require__.d(backend_util_namespaceObject, "exponent", function () {
return exponent;
});
__webpack_require__.d(backend_util_namespaceObject, "segment_util", function () {
return segment_util_namespaceObject;
});
__webpack_require__.d(backend_util_namespaceObject, "castTensor", function () {
return castTensor;
});
__webpack_require__.d(backend_util_namespaceObject, "reshapeTensor", function () {
return reshapeTensor;
});
__webpack_require__.d(backend_util_namespaceObject, "linspaceImpl", function () {
return linspaceImpl;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-core/dist/backends/kernel_impls.js
var kernel_impls_namespaceObject = {};
__webpack_require__.r(kernel_impls_namespaceObject);
__webpack_require__.d(kernel_impls_namespaceObject, "nonMaxSuppressionV3", function () {
return nonMaxSuppressionV3;
});
__webpack_require__.d(kernel_impls_namespaceObject, "nonMaxSuppressionV5", function () {
return nonMaxSuppressionV5;
});
__webpack_require__.d(kernel_impls_namespaceObject, "split", function () {
return split_shared_split;
});
__webpack_require__.d(kernel_impls_namespaceObject, "tile", function () {
return tile_impl_tile;
});
__webpack_require__.d(kernel_impls_namespaceObject, "topkImpl", function () {
return topkImpl;
});
__webpack_require__.d(kernel_impls_namespaceObject, "whereImpl", function () {
return whereImpl;
});
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/engine.js + 2 modules
var engine = __webpack_require__(5);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/flags.js
var flags = __webpack_require__(61);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/kernel_names.js
var kernel_names = __webpack_require__(6);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/broadcast_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the dimensions in the input shape that are broadcasted to
* produce the provided output shape.
*
* The returned dimensions are 0-indexed and sorted. An example:
* inShape = [4, 1, 3]
* outShape = [5, 4, 3, 3]
* result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.
*/
function getBroadcastDims(inShape, outShape) {
const inRank = inShape.length;
const dims = [];
for (let i = 0; i < inRank; i++) {
const dim = inRank - 1 - i;
const a = inShape[dim] || 1;
const b = outShape[outShape.length - 1 - i] || 1;
if (b > 1 && a === 1) {
dims.unshift(dim);
}
}
return dims;
}
/**
* Returns the axes in the output space that should be reduced to produce
* the input space.
*/
function getReductionAxes(inShape, outShape) {
const result = [];
for (let i = 0; i < outShape.length; i++) {
const inDim = inShape[inShape.length - i - 1];
const outAxis = outShape.length - i - 1;
const outDim = outShape[outAxis];
if (inDim == null || (inDim === 1 && outDim > 1)) {
result.unshift(outAxis);
}
}
return result;
}
function assertAndGetBroadcastShape(shapeA, shapeB) {
const result = [];
const l = Math.max(shapeA.length, shapeB.length);
for (let i = 0; i < l; i++) {
let a = shapeA[shapeA.length - i - 1];
if (a == null) {
a = 1;
}
let b = shapeB[shapeB.length - i - 1];
if (b == null) {
b = 1;
}
if (a === 1) {
result.unshift(b);
} else if (b === 1) {
result.unshift(a);
} else if (a !== b) {
const errMsg =
`Operands could not be broadcast together with shapes ` + `${shapeA} and ${shapeB}.`;
throw Error(errMsg);
} else {
result.unshift(a);
}
}
return result;
}
//# sourceMappingURL=broadcast_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Add_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const addGradConfig = {
kernelName: kernel_names["a" /* Add */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
let res = dy;
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = res.sum(reduceAxes);
}
return res.reshape(a.shape);
};
const derB = () => {
let res = dy;
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = res.sum(reduceAxes);
}
return res.reshape(b.shape);
};
return { a: derA, b: derB };
},
};
//# sourceMappingURL=Add_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/AddN_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const addNGradConfig = {
kernelName: kernel_names["b" /* AddN */],
saveAllInputs: true,
gradFunc: (dy, saved) => {
const ders = {};
saved.forEach((_, i) => {
ders[i] = () => dy.clone();
});
return ders;
},
};
//# sourceMappingURL=AddN_grad.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor_util.js
var tensor_util = __webpack_require__(11);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor_util_env.js
var tensor_util_env = __webpack_require__(3);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/operation.js
var operation = __webpack_require__(4);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/add.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.
*
*
* ```js
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.tensor1d([10, 20, 30, 40]);
*
* a.add(b).print(); // or tf.add(a, b)
* ```
*
* ```js
* // Broadcast add a with b.
* const a = tf.scalar(5);
* const b = tf.tensor1d([10, 20, 30, 40]);
*
* a.add(b).print(); // or tf.add(a, b)
* ```
* @param a The first `tf.Tensor` to add.
* @param b The second `tf.Tensor` to add. Must have the same type as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function add_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "add");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "add");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
const forward = (backend, save) => {
const res = backend.add($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["a" /* Add */]
);
}
const add = Object(operation["a" /* op */])({ add_ });
//# sourceMappingURL=add.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor.js + 1 modules
var dist_tensor = __webpack_require__(7);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/util.js
var util = __webpack_require__(1);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/concat_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function assertParamsConsistent(shapes, axis) {
const rank = shapes[0].length;
shapes.forEach((shape, i) => {
util["assert"](
shape.length === rank,
() =>
`Error in concat${rank}D: rank of tensors[${i}] must be the same ` +
`as the rank of the rest (${rank})`
);
});
util["assert"](
axis >= 0 && axis < rank,
() => `Error in concat${rank}D: axis must be between 0 and ${rank - 1}.`
);
const firstShape = shapes[0];
shapes.forEach((shape, i) => {
for (let r = 0; r < rank; r++) {
util["assert"](
r === axis || shape[r] === firstShape[r],
() =>
`Error in concat${rank}D: Shape of tensors[${i}] (${shape}) ` +
`does not match the shape of the rest (${firstShape}) ` +
`along the non-concatenated axis ${i}.`
);
}
});
}
function computeOutShape(shapes, axis) {
const outputShape = shapes[0].slice();
for (let i = 1; i < shapes.length; i++) {
outputShape[axis] += shapes[i][axis];
}
return outputShape;
}
//# sourceMappingURL=concat_util.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/tensor_ops.js
var tensor_ops = __webpack_require__(8);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/concat.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Concatenates a list of `tf.Tensor`s along a given axis.
*
* The tensors ranks and types must match, and their sizes must match in all
* dimensions except `axis`.
*
* Also available are stricter rank-specific methods that assert that
* `tensors` are of the given rank:
* - `tf.concat1d`
* - `tf.concat2d`
* - `tf.concat3d`
* - `tf.concat4d`
*
* Except `tf.concat1d` (which does not have axis param), all methods have
* same signature as this method.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* a.concat(b).print(); // or a.concat(b)
* ```
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
* tf.concat([a, b, c]).print();
* ```
*
* ```js
* const a = tf.tensor2d([[1, 2], [10, 20]]);
* const b = tf.tensor2d([[3, 4], [30, 40]]);
* const axis = 1;
* tf.concat([a, b], axis).print();
* ```
* @param tensors A list of tensors to concatenate.
* @param axis The axis to concate along. Defaults to 0 (the first dim).
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
function concat_(tensors, axis = 0) {
Object(util["assert"])(tensors.length >= 1, () => "Pass at least one tensor to concat");
let $tensors = Object(tensor_util_env["b" /* convertToTensorArray */])(
tensors,
"tensors",
"concat"
);
if ($tensors[0].dtype === "complex64") {
$tensors.forEach((tensor) => {
if (tensor.dtype !== "complex64") {
throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${tensor.dtype}. `);
}
});
}
const $axis = Object(util["parseAxisParam"])(axis, $tensors[0].shape)[0];
const outShape = computeOutShape(
$tensors.map((t) => t.shape),
$axis
);
if (Object(util["sizeFromShape"])(outShape) === 0) {
return Object(tensor_ops["f" /* tensor */])([], outShape);
}
// Keep only non-empty tensors (ignore tensors with 0 in their shape).
$tensors = $tensors.filter((t) => t.size > 0);
if ($tensors.length === 1) {
return $tensors[0];
}
const shapes = $tensors.map((t) => t.shape);
assertParamsConsistent(shapes, $axis);
const forward = (backend, save) => {
const res = backend.concat($tensors, $axis);
save($tensors);
return res;
};
const inputs = $tensors;
const attr = { axis };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["l" /* Concat */],
attr
);
}
const concat = Object(operation["a" /* op */])({ concat_ });
//# sourceMappingURL=concat.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/array_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reshapes a `tf.Tensor` to a given shape.
*
* Given an input tensor, returns a new tensor with the same values as the
* input tensor with shape `shape`.
*
* If one component of shape is the special value -1, the size of that
* dimension is computed so that the total size remains constant. In
* particular, a shape of [-1] flattens into 1-D. At most one component of
* shape can be -1.
*
* If shape is 1-D or higher, then the operation returns a tensor with shape
* shape filled with the values of tensor. In this case, the number of
* elements implied by shape must be the same as the number of elements in
* tensor.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* x.reshape([2, 2]).print();
* ```
*
* @param x The input tensor to be reshaped.
* @param shape An array of integers defining the output tensor shape.
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function reshape_(x, shape) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "reshape", null);
shape = util["inferFromImplicitShape"](shape, $x.size);
util["assert"](
$x.size === util["sizeFromShape"](shape),
() => "new shape and old shape must have the same number of elements."
);
const grad = (dy) => {
return { x: () => dy.reshape($x.shape) };
};
const attrs = { shape };
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.reshape($x, shape),
{ x: $x },
grad,
"Reshape",
attrs
);
}
/**
* Removes dimensions of size 1 from the shape of a `tf.Tensor`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);
* x.squeeze().print();
* ```
*
* @param x The input tensor to be squeezed.
* @param axis An optional list of numbers. If specified, only
* squeezes the dimensions listed. The dimension index starts at 0. It
* is an error to squeeze a dimension that is not 1.
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function squeeze_(x, axis) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "squeeze");
return reshape($x, util["squeezeShape"]($x.shape, axis).newShape);
}
/**
* Casts a `tf.Tensor` to a new dtype.
*
* ```js
* const x = tf.tensor1d([1.5, 2.5, 3]);
* tf.cast(x, 'int32').print();
* ```
* @param x The input tensor to be casted.
* @param dtype The dtype to cast the input tensor to.
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function cast_(x, dtype) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "cast");
// Sanity checks.
if (!util["isValidDtype"](dtype)) {
throw new Error(`Failed to cast to unknown dtype ${dtype}`);
}
if (
(dtype === "string" && $x.dtype !== "string") ||
(dtype !== "string" && $x.dtype === "string")
) {
throw new Error("Only strings can be casted to strings");
}
const grad = (dy) => {
return { x: () => dy.clone() };
};
const attrs = { dtype };
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.cast($x, dtype),
{ x: $x },
grad,
"Cast",
attrs
);
}
/**
* Stacks a list of rank-`R` `tf.Tensor`s into one rank-`(R+1)` `tf.Tensor`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
* tf.stack([a, b, c]).print();
* ```
*
* @param tensors A list of tensor objects with the same shape and dtype.
* @param axis The axis to stack along. Defaults to 0 (the first dim).
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
function stack_(tensors, axis = 0) {
const $tensors = Object(tensor_util_env["b" /* convertToTensorArray */])(
tensors,
"tensors",
"stack"
);
util["assert"]($tensors.length >= 1, () => "Pass at least one tensor to tf.stack");
if ($tensors.length === 1) {
return $tensors[0].expandDims(axis);
}
const rank = $tensors[0].rank;
const shape = $tensors[0].shape;
const dtype = $tensors[0].dtype;
util["assert"](axis <= rank, () => "Axis must be <= rank of the tensor");
$tensors.forEach((t) => {
util["assertShapesMatch"](
shape,
t.shape,
"All tensors passed to stack must have matching shapes"
);
});
$tensors.forEach((t) => {
util["assert"](
dtype === t.dtype,
() => "All tensors passed to stack must have matching dtypes"
);
});
const expandedTensors = $tensors.map((t) => t.expandDims(axis));
return concat(expandedTensors, axis);
}
/**
* Unstacks a `tf.Tensor` of rank-`R` into a list of rank-`(R-1)` `tf.Tensor`s.
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* tf.unstack(a).forEach(tensor => tensor.print());
* ```
*
* @param x A tensor object.
* @param axis The axis to unstack along. Defaults to 0 (the first dim).
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
function unstack_(x, axis = 0) {
axis = axis || 0;
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "unstack");
util["assert"](
axis >= -$x.shape.length && axis < $x.shape.length,
() => `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`
);
if (axis < 0) {
axis += $x.shape.length;
}
const grad = (dy) => {
return { x: () => stack(dy, axis) };
};
const attrs = { axis };
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.unstack($x, axis),
{ x: $x },
grad,
"Unpack",
attrs
);
}
/**
* Returns a `tf.Tensor` that has expanded rank, by inserting a dimension
* into the tensor's shape.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const axis = 1;
* x.expandDims(axis).print();
* ```
*
* @param x The input tensor whose dimensions to be expanded.
* @param axis The dimension index at which to insert shape of `1`. Defaults
* to 0 (the first dimension).
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function expandDims_(x, axis = 0) {
const parseAs = null;
const $x = Object(tensor_util_env["a" /* convertToTensor */])(
x,
"x",
"expandDims",
parseAs
);
util["assert"](axis <= $x.rank, () => "Axis must be <= rank of the tensor");
const newShape = $x.shape.slice();
if (axis < 0) {
// Negative value is counted from the tail of rank.
util["assert"](
-($x.rank + 1) <= axis,
() => `Axis must be in the interval [${-($x.rank + 1)}, ${$x.rank}]`
);
axis = $x.rank + axis + 1;
}
newShape.splice(axis, 0, 1);
return reshape($x, newShape);
}
/**
* Computes the difference between two lists of numbers.
*
* Given a Tensor `x` and a Tensor `y`, this operation returns a Tensor `out`
* that represents all values that are in `x` but not in `y`. The returned
* Tensor `out` is sorted in the same order that the numbers appear in `x`
* (duplicates are preserved). This operation also returns a Tensor indices that
* represents the position of each out element in `x`. In other words:
*
* `out[i] = x[idx[i]] for i in [0, 1, ..., out.length - 1]`
*
* ```js
* const x = [1, 2, 3, 4, 5, 6];
* const y = [1, 3, 5];
*
* const [out, indices] = await tf.setdiff1dAsync(x, y);
* out.print(); // [2, 4, 6]
* indices.print(); // [1, 3, 5]
* ```
*
* @param x 1-D Tensor. Values to keep.
* @param y 1-D Tensor. Must have the same type as x. Values to exclude in the
* output.
* @returns Promise of Tensor tuple [out, indices].
* out: Tensor with the same type as x.
* indices: A Tensor of type int32.
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
async function setdiff1dAsync_(x, y) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "setdiff1d");
const $y = Object(tensor_util_env["a" /* convertToTensor */])(y, "y", "setdiff1d");
util["assert"](
$x.dtype === $y.dtype,
() => `x and y should have the same dtype, but got x (${$x.dtype}) and y (${$y.dtype}).`
);
util["assert"]($x.rank === 1, () => `x should be 1D tensor, but got x (${$x.shape}).`);
util["assert"]($y.rank === 1, () => `y should be 1D tensor, but got y (${$y.shape}).`);
const xVals = await $x.data();
const yVals = await $y.data();
const ySet = new Set(yVals);
let outputSize = 0;
for (let i = 0; i < xVals.length; i++) {
if (!ySet.has(xVals[i])) {
outputSize++;
}
}
const buffer = new dist_tensor["b" /* TensorBuffer */]([outputSize], $x.dtype);
const indices = new dist_tensor["b" /* TensorBuffer */]([outputSize], "int32");
for (let i = 0, p = 0; i < xVals.length; i++) {
if (!ySet.has(xVals[i])) {
buffer.values[p] = xVals[i];
indices.values[p] = i;
p++;
}
}
return [buffer.toTensor(), indices.toTensor()];
}
/**
* Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.
*
* The values are stored in CPU as `TypedArray`. Fill the buffer using
* `buffer.set()`, or by modifying directly `buffer.values`.
*
* When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with
* those values.
*
* ```js
* // Create a buffer and set values at particular indices.
* const buffer = tf.buffer([2, 2]);
* buffer.set(3, 0, 0);
* buffer.set(5, 1, 0);
*
* // Convert the buffer back to a tensor.
* buffer.toTensor().print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The dtype of the buffer. Defaults to 'float32'.
* @param values The values of the buffer as `TypedArray`. Defaults to
* zeros.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function array_ops_buffer(shape, dtype = "float32", values) {
dtype = dtype || "float32";
util["assertNonNegativeIntegerDimensions"](shape);
return new dist_tensor["b" /* TensorBuffer */](shape, dtype, values);
}
/**
* Prints information about the `tf.Tensor` including its data.
*
* ```js
* const verbose = true;
* tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);
* ```
* @param x The tensor to be printed.
* @param verbose Whether to print verbose information about the ` Tensor`,
* including dtype and size.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function print(x, verbose = false) {
console.log(x.toString(verbose));
}
const cast = Object(operation["a" /* op */])({ cast_ });
const expandDims = Object(operation["a" /* op */])({ expandDims_ });
const reshape = Object(operation["a" /* op */])({ reshape_ });
const squeeze = Object(operation["a" /* op */])({ squeeze_ });
const stack = Object(operation["a" /* op */])({ stack_ });
const unstack = Object(operation["a" /* op */])({ unstack_ });
const setdiff1dAsync = setdiff1dAsync_;
//# sourceMappingURL=array_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/floorDiv.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.
* The result is rounded with floor function.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.floorDiv(b).print(); // or tf.div(a, b)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
*
* a.floorDiv(b).print(); // or tf.floorDiv(a, b)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function floorDiv_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "floorDiv");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "floorDiv");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
const forward = (backend, save) => {
const res = backend.floorDiv($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["D" /* FloorDiv */]
);
}
const floorDiv = Object(operation["a" /* op */])({ floorDiv_ });
//# sourceMappingURL=floorDiv.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/div.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.div(b).print(); // or tf.div(a, b)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
*
* a.div(b).print(); // or tf.div(a, b)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function div_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "div");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "div");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
if ($a.dtype === "int32" && $b.dtype === "int32") {
return floorDiv($a, $b);
}
const forward = (backend, save) => {
const res = backend.realDivide($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
const attrs = {};
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["y" /* Div */],
attrs
);
}
const div = Object(operation["a" /* op */])({ div_ });
//# sourceMappingURL=div.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/mul.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Multiplies two `tf.Tensor`s element-wise, A * B. Supports broadcasting.
*
* We also expose `tf.mulStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.tensor1d([2, 3, 4, 5]);
*
* a.mul(b).print(); // or tf.mul(a, b)
* ```
*
* ```js
* // Broadcast mul a with b.
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.scalar(5);
*
* a.mul(b).print(); // or tf.mul(a, b)
* ```
* @param a The first tensor to multiply.
* @param b The second tensor to multiply. Must have the same dtype as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function mul_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "mul");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "mul");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
const forward = (backend, save) => {
const res = backend.multiply($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["Y" /* Multiply */]
);
}
const mul = Object(operation["a" /* op */])({ mul_ });
//# sourceMappingURL=mul.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Provided `f(x)`, returns another function `g(x, dy?)`, which gives the
* gradient of `f(x)` with respect to `x`.
*
* If `dy` is provided, the gradient of `f(x).mul(dy).sum()` with respect to
* `x` is computed instead. `f(x)` must take a single tensor `x` and return a
* single tensor `y`. If `f()` takes multiple inputs, use `tf.grads` instead.
*
* ```js
* // f(x) = x ^ 2
* const f = x => x.square();
* // f'(x) = 2x
* const g = tf.grad(f);
*
* const x = tf.tensor1d([2, 3]);
* g(x).print();
* ```
*
* ```js
* // f(x) = x ^ 3
* const f = x => x.pow(tf.scalar(3, 'int32'));
* // f'(x) = 3x ^ 2
* const g = tf.grad(f);
* // f''(x) = 6x
* const gg = tf.grad(g);
*
* const x = tf.tensor1d([2, 3]);
* gg(x).print();
* ```
*
* @param f The function f(x), to compute gradient for.
*/
/** @doc {heading: 'Training', subheading: 'Gradients'} */
function gradients_grad(f) {
util["assert"](util["isFunction"](f), () => "The f passed in grad(f) must be a function");
return (x, dy) => {
// x can be of any dtype, thus null as the last argument.
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "tf.grad", null);
const $dy =
dy != null
? Object(tensor_util_env["a" /* convertToTensor */])(dy, "dy", "tf.grad")
: null;
return engine["a" /* ENGINE */].tidy(() => {
const { value, grads } = engine["a" /* ENGINE */].gradients(() => f($x), [$x], $dy);
if ($dy != null) {
util["assertShapesMatch"](
value.shape,
$dy.shape,
"The shape of dy passed in grad(f)(x, dy) must match the shape " +
"returned by f(x)"
);
}
checkGrads(grads);
return grads[0];
});
};
}
/**
* Provided `f(x1, x2,...)`, returns another function `g([x1, x2,...], dy?)`,
* which gives an array of gradients of `f()` with respect to each input
* [`x1`,`x2`,...].
*
* If `dy` is passed when calling `g()`, the gradient of
* `f(x1,...).mul(dy).sum()` with respect to each input is computed instead.
* The provided `f` must take one or more tensors and return a single tensor
* `y`. If `f()` takes a single input, we recommend using `tf.grad` instead.
*
* ```js
* // f(a, b) = a * b
* const f = (a, b) => a.mul(b);
* // df / da = b, df / db = a
* const g = tf.grads(f);
*
* const a = tf.tensor1d([2, 3]);
* const b = tf.tensor1d([-2, -3]);
* const [da, db] = g([a, b]);
* console.log('da');
* da.print();
* console.log('db');
* db.print();
* ```
*
* @param f The function `f(x1, x2,...)` to compute gradients for.
*/
/** @doc {heading: 'Training', subheading: 'Gradients'} */
function gradients_grads(f) {
util["assert"](util["isFunction"](f), () => "The f passed in grads(f) must be a function");
return (args, dy) => {
util["assert"](
Array.isArray(args),
() =>
"The args passed in grads(f)(args) must be an array " +
"of `Tensor`s or `TensorLike`s"
);
// args can be of any dtype, thus null as the last argument.
const $args = Object(tensor_util_env["b" /* convertToTensorArray */])(
args,
"args",
"tf.grads",
null
);
const $dy =
dy != null
? Object(tensor_util_env["a" /* convertToTensor */])(dy, "dy", "tf.grads")
: null;
return engine["a" /* ENGINE */].tidy(() => {
const { value, grads } = engine["a" /* ENGINE */].gradients(
() => f(...$args),
$args,
$dy
);
if ($dy != null) {
util["assertShapesMatch"](
value.shape,
$dy.shape,
"The shape of dy passed in grads(f)([x1,...], dy) must " +
"match the shape returned by f([x1,...])"
);
}
checkGrads(grads);
return grads;
});
};
}
/**
* Like `tf.grad`, but also returns the value of `f()`. Useful when `f()`
* returns a metric you want to show.
*
* The result is a rich object with the following properties:
* - grad: The gradient of `f(x)` w.r.t `x` (result of `tf.grad`).
* - value: The value returned by `f(x)`.
*
* ```js
* // f(x) = x ^ 2
* const f = x => x.square();
* // f'(x) = 2x
* const g = tf.valueAndGrad(f);
*
* const x = tf.tensor1d([2, 3]);
* const {value, grad} = g(x);
*
* console.log('value');
* value.print();
* console.log('grad');
* grad.print();
* ```
*/
/** @doc {heading: 'Training', subheading: 'Gradients'} */
function valueAndGrad(f) {
util["assert"](
util["isFunction"](f),
() => "The f passed in valueAndGrad(f) must be a function"
);
return (x, dy) => {
util["assert"](
x instanceof dist_tensor["a" /* Tensor */],
() => "The x passed in valueAndGrad(f)(x) must be a tensor"
);
util["assert"](
dy == null || dy instanceof dist_tensor["a" /* Tensor */],
() => "The dy passed in valueAndGrad(f)(x, dy) must be a tensor"
);
const { grads, value } = engine["a" /* ENGINE */].gradients(() => f(x), [x], dy);
checkGrads(grads);
return { grad: grads[0], value };
};
}
/**
* Like `tf.grads`, but returns also the value of `f()`. Useful when `f()`
* returns a metric you want to show.
*
* The result is a rich object with the following properties:
* - grads: The gradients of `f()` w.r.t each input (result of `tf.grads`).
* - value: The value returned by `f(x)`.
*
* ```js
* // f(a, b) = a * b
* const f = (a, b) => a.mul(b);
* // df/da = b, df/db = a
* const g = tf.valueAndGrads(f);
*
* const a = tf.tensor1d([2, 3]);
* const b = tf.tensor1d([-2, -3]);
* const {value, grads} = g([a, b]);
*
* const [da, db] = grads;
*
* console.log('value');
* value.print();
*
* console.log('da');
* da.print();
* console.log('db');
* db.print();
* ```
*/
/** @doc {heading: 'Training', subheading: 'Gradients'} */
function valueAndGrads(f) {
util["assert"](
util["isFunction"](f),
() => "The f passed in valueAndGrads(f) must be a function"
);
return (args, dy) => {
util["assert"](
Array.isArray(args) &&
args.every((arg) => arg instanceof dist_tensor["a" /* Tensor */]),
() => "The args passed in valueAndGrads(f)(args) must be array of " + "tensors"
);
util["assert"](
dy == null || dy instanceof dist_tensor["a" /* Tensor */],
() => "The dy passed in valueAndGrads(f)(args, dy) must be a tensor"
);
const res = engine["a" /* ENGINE */].gradients(() => f(...args), args, dy);
if (dy != null) {
util["assertShapesMatch"](
res.value.shape,
dy.shape,
"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must " +
"match the shape returned by f([x1,...])"
);
}
checkGrads(res.grads);
return res;
};
}
/**
* Computes and returns the gradient of f(x) with respect to the list of
* trainable variables provided by `varList`. If no list is provided, it
* defaults to all trainable variables.
*
* ```js
* const a = tf.variable(tf.tensor1d([3, 4]));
* const b = tf.variable(tf.tensor1d([5, 6]));
* const x = tf.tensor1d([1, 2]);
*
* // f(a, b) = a * x ^ 2 + b * x
* const f = () => a.mul(x.square()).add(b.mul(x)).sum();
* // df/da = x ^ 2, df/db = x
* const {value, grads} = tf.variableGrads(f);
*
* Object.keys(grads).forEach(varName => grads[varName].print());
* ```
*
* @param f The function to execute. f() should return a scalar.
* @param varList The list of variables to compute the gradients with respect
* to. Defaults to all trainable variables.
* @returns An object with the following keys and values:
* - `value`: The value of the function `f`.
* - `grads`: A map from the names of the variables to the gradients.
* If the `varList` argument is provided explicitly and contains a subset of
* non-trainable variables, this map in the return value will contain keys
* that map the names of the non-trainable variables to `null`.
*/
/** @doc {heading: 'Training', subheading: 'Gradients'} */
function variableGrads(f, varList) {
util["assert"](
util["isFunction"](f),
() => "The f passed in variableGrads(f) must be a function"
);
util["assert"](
varList == null ||
(Array.isArray(varList) &&
varList.every((v) => v instanceof dist_tensor["c" /* Variable */])),
() => "The varList passed in variableGrads(f, varList) must be an array " + "of variables"
);
const specifiedVarList = varList != null;
if (!specifiedVarList) {
// Get all of the trainable variables.
varList = [];
for (const varName in engine["a" /* ENGINE */].registeredVariables) {
varList.push(engine["a" /* ENGINE */].registeredVariables[varName]);
}
}
const specifiedNonTrainable = specifiedVarList
? varList.filter((variable) => !variable.trainable)
: null;
// Prune non-trainable variables.
const originalVarCount = varList.length;
varList = varList.filter((variable) => variable.trainable);
util["assert"](
varList.length > 0,
() =>
`variableGrads() expects at least one of the input variables to ` +
`be trainable, but none of the ${originalVarCount} variables is ` +
`trainable.`
);
const allowNoGradients = true;
const { value, grads } = engine["a" /* ENGINE */].gradients(
f,
varList,
null,
allowNoGradients
);
util["assert"](
grads.some((g) => g != null),
() =>
"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()."
);
util["assert"](
value.rank === 0,
() =>
`The f passed in variableGrads(f) must return a scalar, but it ` +
`returned a rank-${value.rank} tensor`
);
const namedGrads = {};
varList.forEach((v, i) => {
if (grads[i] != null) {
namedGrads[v.name] = grads[i];
}
});
if (specifiedNonTrainable != null) {
// If varList is explicitly provided and contains non-trainable values,
// add them to the returned gradients with `null` values.
specifiedNonTrainable.forEach((v) => (namedGrads[v.name] = null));
}
return { value, grads: namedGrads };
}
/**
* Overrides the gradient computation of a function `f`.
*
* Takes a function
* `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`
* and returns another function `g(...inputs)` which takes the same inputs as
* `f`. When called, `g` returns `f().value`. In backward mode, custom gradients
* with respect to each input of `f` are computed using `f().gradFunc`.
*
* The `save` function passsed to `f` should be used for saving tensors needed
* in the gradient. And the `saved` passed to the `gradFunc` is a
* `NamedTensorMap`, which contains those saved tensor.
*
* ```js
* const customOp = tf.customGrad((x, save) => {
* // Save x to make sure it's available later for the gradient.
* save([x]);
* // Override gradient of our custom x ^ 2 op to be dy * abs(x);
* return {
* value: x.square(),
* // Note `saved.x` which points to the `x` we saved earlier.
* gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]
* };
* });
*
* const x = tf.tensor1d([-1, -2, 3]);
* const dx = tf.grad(x => customOp(x));
*
* console.log(`f(x):`);
* customOp(x).print();
* console.log(`f'(x):`);
* dx(x).print();
* ```
*
* @param f The function to evaluate in forward mode, which should return
* `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`
* returns the custom gradients of `f` with respect to its inputs.
*/
/** @doc {heading: 'Training', subheading: 'Gradients'} */
function customGrad(f) {
return engine["a" /* ENGINE */].customGrad(f);
}
function checkGrads(grads) {
const numNullGradients = grads.filter((g) => g == null).length;
if (numNullGradients > 0) {
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.`);
}
}
//# sourceMappingURL=gradients.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/axis_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns true if the axis specifies the inner most dimensions of the
* array.
*/
function axesAreInnerMostDims(axes, rank) {
for (let i = 0; i < axes.length; ++i) {
if (axes[axes.length - i - 1] !== rank - 1 - i) {
return false;
}
}
return true;
}
function combineLocations(outputLoc, reduceLoc, axes) {
const rank = outputLoc.length + reduceLoc.length;
const loc = [];
let outIdx = 0;
let reduceIdx = 0;
for (let dim = 0; dim < rank; dim++) {
if (axes.indexOf(dim) === -1) {
loc.push(outputLoc[outIdx++]);
} else {
loc.push(reduceLoc[reduceIdx++]);
}
}
return loc;
}
function computeOutAndReduceShapes(aShape, axes) {
const outShape = [];
const rank = aShape.length;
for (let dim = 0; dim < rank; dim++) {
if (axes.indexOf(dim) === -1) {
outShape.push(aShape[dim]);
}
}
const reduceShape = axes.map((dim) => aShape[dim]);
return [outShape, reduceShape];
}
function expandShapeToKeepDim(shape, axes) {
const reduceSubShape = axes.map((x) => 1);
return combineLocations(shape, reduceSubShape, axes);
}
function assertAxesAreInnerMostDims(msg, axes, rank) {
util["assert"](
axesAreInnerMostDims(axes, rank),
() =>
`${msg} supports only inner-most axes for now. ` +
`Got axes ${axes} and rank-${rank} input.`
);
}
/**
* Returns the axes permutation to be used with `tf.transpose`, if such
* permutation is necessary. Otherwise it returns null. This method is used by
* operations that operate only on inner-most axes.
*/
function getAxesPermutation(axes, rank) {
if (axesAreInnerMostDims(axes, rank)) {
return null;
}
const result = [];
for (let i = 0; i < rank; ++i) {
if (axes.indexOf(i) === -1) {
result.push(i);
}
}
axes.forEach((axis) => result.push(axis));
return result;
}
/** Returns the axes permutation that undoes the original permutation. */
function getUndoAxesPermutation(axes) {
return axes
.map((axis, i) => [i, axis])
.sort((a, b) => a[1] - b[1])
.map((x) => x[0]);
}
function getInnerMostAxes(numAxes, rank) {
const res = [];
for (let i = rank - numAxes; i < rank; ++i) {
res.push(i);
}
return res;
}
//# sourceMappingURL=axis_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/reduction_ops_util.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gradient helper function for the min and max operations.
*/
function gradForMinAndMax(dy, y, xOrig, origAxes, permutedAxes) {
if (y.rank < xOrig.rank) {
y = y.reshape(expandShapeToKeepDim(y.shape, origAxes));
}
if (dy.rank < xOrig.rank) {
dy = dy.reshape(expandShapeToKeepDim(dy.shape, origAxes));
}
return {
x: () => {
const dx = dy.mul(xOrig.equal(y).cast(dy.dtype));
return permutedAxes == null ? dx : dx.transpose(permutedAxes);
},
};
}
//# sourceMappingURL=reduction_ops_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/reduction_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the log(sum(exp(elements across the reduction dimensions)).
*
* Reduces the input along the dimensions given in `axis`. Unless `keepDims`
* is true, the rank of the array is reduced by 1 for each entry in `axis`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axis` has no entries, all dimensions are reduced, and an array with a
* single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.logSumExp().print(); // or tf.logSumExp(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.logSumExp(axis).print(); // or tf.logSumExp(a, axis)
* ```
* @param x The input tensor.
* @param axis The dimension(s) to reduce. If null (the default),
* reduces all dimensions.
* @param keepDims If true, retains reduced dimensions with length
* of 1. Defaults to false.
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function logSumExp_(x, axis = null, keepDims = false) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "logSumExp");
const axes = util["parseAxisParam"](axis, $x.shape);
const xMax = $x.max(axes, true /* keepDims */);
const a = $x.sub(xMax);
const b = a.exp();
const c = b.sum(axes);
const d = c.log();
const res = xMax.reshape(d.shape).add(d);
if (keepDims) {
const newShape = expandShapeToKeepDim(res.shape, axes);
return res.reshape(newShape);
}
return res;
}
/**
* Computes the sum of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If axes has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.sum().print(); // or tf.sum(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.sum(axis).print(); // or tf.sum(x, axis)
* ```
*
* @param x The input tensor to compute the sum over. If the dtype is `bool`
* it will be converted to `int32` and the output dtype will be `int32`.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function sum_(x, axis = null, keepDims = false) {
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "sum");
if ($x.dtype === "bool") {
$x = $x.toInt();
}
const axes = util["parseAxisParam"](axis, $x.shape);
// Use a custom gradient to bypass 2 gradient backprops since sum is used
// extremely often.
const customOp = customGrad((x) => {
const permutation = getAxesPermutation(axes, x.rank);
let reductionAxes = axes;
let permutedX = x;
if (permutation != null) {
permutedX = x.transpose(permutation);
reductionAxes = getInnerMostAxes(reductionAxes.length, x.rank);
}
const gradFunc = (dy) => {
const expandedDyShape = x.shape.slice();
axes.forEach((axis) => {
expandedDyShape[axis] = 1;
});
const expandedDy = dy.reshape(expandedDyShape);
const derX = expandedDy.mul(Object(tensor_ops["b" /* ones */])(x.shape, "float32"));
return derX;
};
const gradInputs = (dy) => {
return { x: () => gradFunc(dy) };
};
const attrs = { axes: reductionAxes };
let value = engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.sum(permutedX, reductionAxes),
{ x: permutedX },
gradInputs,
"Sum",
attrs
);
if (keepDims) {
const newShape = expandShapeToKeepDim(value.shape, axes);
value = value.reshape(newShape);
}
return { value, gradFunc };
});
return customOp($x);
}
/**
* Computes the product of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.prod().print(); // or tf.prod(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.prod(axis).print(); // or tf.prod(x, axis)
* ```
*
* @param x The input tensor to compute the product over. If the dtype is `bool`
* it will be converted to `int32` and the output dtype will be `int32`.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function prod_(x, axis = null, keepDims = false) {
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "prod");
if ($x.dtype === "bool") {
$x = $x.toInt();
}
const axes = util["parseAxisParam"](axis, $x.shape);
const permutation = getAxesPermutation(axes, $x.rank);
let reductionAxes = axes;
let permutedX = $x;
if (permutation != null) {
permutedX = $x.transpose(permutation);
reductionAxes = getInnerMostAxes(reductionAxes.length, $x.rank);
}
let value = engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.prod(permutedX, reductionAxes),
{ permutedX }
);
if (keepDims) {
const newShape = expandShapeToKeepDim(value.shape, axes);
value = value.reshape(newShape);
}
return value;
}
/**
* Computes the mean of elements across dimensions of a `tf.Tensor`.
*
* Reduces `x` along the dimensions given in `axis`. Unless `keepDims` is
* true, the rank of the `tf.Tensor` is reduced by 1 for each entry in `axis`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axis` has no entries, all dimensions are reduced, and a `tf.Tensor` with
* a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.mean().print(); // or tf.mean(a)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.mean(axis).print(); // or tf.mean(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function mean_(x, axis = null, keepDims = false) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "mean");
const axes = util["parseAxisParam"](axis, $x.shape);
const shapes = computeOutAndReduceShapes($x.shape, axes);
const reduceShape = shapes[1];
const reduceSize = util["sizeFromShape"](reduceShape);
// Use a custom gradient to bypass 2 gradient backprops since mean is used
// extremely often.
const customOp = customGrad((x) => {
const reduceSizeScalar = Object(tensor_ops["e" /* scalar */])(reduceSize);
// Cast if needed.
const xReduce = reduceSizeScalar.dtype === x.dtype ? x : x.cast(reduceSizeScalar.dtype);
const res = xReduce.div(reduceSizeScalar);
const value = res.sum(axis, keepDims);
const gradFunc = (dy) => {
const expandedDyShape = x.shape.slice();
axes.forEach((axis) => {
expandedDyShape[axis] = 1;
});
const expandedDy = dy.reshape(expandedDyShape);
const derX = expandedDy
.mul(Object(tensor_ops["b" /* ones */])(x.shape, "float32"))
.div(reduceSize);
return derX;
};
return { value, gradFunc };
});
return customOp($x);
}
/**
* Computes the minimum value from the input.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the array is reduced by 1 for each entry in `axes`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axes` has no entries, all dimensions are reduced, and an array with a
* single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.min().print(); // or tf.min(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.min(axis).print(); // or tf.min(x, axis)
* ```
*
* @param x The input Tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function min_(x, axis = null, keepDims = false) {
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "min");
const xOrig = $x;
const origAxes = util["parseAxisParam"](axis, $x.shape);
let axes = origAxes;
const permutedAxes = getAxesPermutation(axes, $x.rank);
if (permutedAxes != null) {
$x = $x.transpose(permutedAxes);
axes = getInnerMostAxes(axes.length, $x.rank);
}
const grad = (dy, saved) =>
gradForMinAndMax(dy, saved[1], saved[0], origAxes, permutedAxes);
const inputsToSave = [$x];
const outputsToSave = [true];
let res = engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const y = backend.min($x, axes);
save([xOrig, y]);
return y;
},
{ x: $x },
grad,
"Min",
{ axes },
inputsToSave,
outputsToSave
);
if (keepDims) {
const newShape = expandShapeToKeepDim(res.shape, origAxes);
res = res.reshape(newShape);
}
return res;
}
/**
* Returns the indices of the minimum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMin().print(); // or tf.argMin(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMin(axis).print(); // or tf.argMin(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function argMin_(x, axis = 0) {
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "argMin");
if (axis == null) {
axis = 0;
}
let axes = util["parseAxisParam"](axis, $x.shape);
const permutedAxes = getAxesPermutation(axes, $x.rank);
if (permutedAxes != null) {
$x = $x.transpose(permutedAxes);
axes = getInnerMostAxes(axes.length, $x.rank);
}
const grad = (dy, saved) => {
const [$x] = saved;
return { $x: () => Object(tensor_ops["o" /* zerosLike */])($x) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.argMin($x, axes[0]);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Returns the indices of the maximum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMax().print(); // or tf.argMax(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMax(axis).print(); // or tf.argMax(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function argMax_(x, axis = 0) {
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "argMax");
if (axis == null) {
axis = 0;
}
let axes = util["parseAxisParam"](axis, $x.shape);
const permutedAxes = getAxesPermutation(axes, $x.rank);
if (permutedAxes != null) {
$x = $x.transpose(permutedAxes);
axes = getInnerMostAxes(axes.length, $x.rank);
}
const grad = (dy, saved) => {
const [$x] = saved;
return { x: () => Object(tensor_ops["o" /* zerosLike */])($x) };
};
const attrs = { axis: axes[0] };
const inputsToSave = [$x];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.argMax($x, axes[0]);
save([$x]);
return res;
},
{ x: $x },
grad,
"ArgMax",
attrs,
inputsToSave
);
}
/**
* Computes the logical and of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.all().print(); // or tf.all(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.all(axis).print(); // or tf.all(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function all_(x, axis = null, keepDims = false) {
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "all", "bool");
const origAxes = util["parseAxisParam"](axis, $x.shape);
let axes = origAxes;
const permutedAxes = getAxesPermutation(axes, $x.rank);
if (permutedAxes != null) {
$x = $x.transpose(permutedAxes);
axes = getInnerMostAxes(axes.length, $x.rank);
}
const res = engine["a" /* ENGINE */].runKernelFunc((backend) => backend.all($x, axes), {
$x,
});
if (keepDims) {
const newShape = expandShapeToKeepDim(res.shape, origAxes);
return res.reshape(newShape);
}
return res;
}
/**
* Computes the logical or of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.any().print(); // or tf.any(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.any(axis).print(); // or tf.any(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function any_(x, axis = null, keepDims = false) {
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "any", "bool");
const origAxes = util["parseAxisParam"](axis, $x.shape);
let axes = origAxes;
const permutedAxes = getAxesPermutation(axes, $x.rank);
if (permutedAxes != null) {
$x = $x.transpose(permutedAxes);
axes = getInnerMostAxes(axes.length, $x.rank);
}
const res = engine["a" /* ENGINE */].runKernelFunc((backend) => backend.any($x, axes), {
$x,
});
if (keepDims) {
const newShape = expandShapeToKeepDim(res.shape, origAxes);
return res.reshape(newShape);
}
return res;
}
/**
* Calculates the mean and variance of `x`. The mean and variance are
* calculated by aggregating the contents of `x` across `axes`. If `x` is
* 1-D and `axes = [0]` this is just the mean and variance of a vector.
*
* @param x The input tensor.
* @param axis The dimension(s) along with to compute mean and
* variance. By default it reduces all dimensions.
* @param keepDims If true, the moments have the same dimensionality as the
* input.
* @return An object with two keys: `mean` and `variance`.
*/
/** @doc {heading: 'Operations', subheading: 'Normalization'} */
function moments_(x, axis = null, keepDims = false) {
x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "moments");
const axes = util["parseAxisParam"](axis, x.shape);
const mean = x.mean(axes, keepDims);
let keepDimsShape = mean.shape;
if (!keepDims) {
keepDimsShape = expandShapeToKeepDim(mean.shape, axes);
}
const devSquared = x.toFloat().sub(mean.reshape(keepDimsShape)).square();
const variance = devSquared.mean(axes, keepDims);
return { mean, variance };
}
const reduction_ops_all = Object(operation["a" /* op */])({ all_ });
// tslint:disable-next-line:variable-name
const any = Object(operation["a" /* op */])({ any_ });
const argMax = Object(operation["a" /* op */])({ argMax_ });
const argMin = Object(operation["a" /* op */])({ argMin_ });
const logSumExp = Object(operation["a" /* op */])({ logSumExp_ });
const reduction_ops_mean = Object(operation["a" /* op */])({ mean_ });
const reduction_ops_min = Object(operation["a" /* op */])({ min_ });
const moments = Object(operation["a" /* op */])({ moments_ });
const sum = Object(operation["a" /* op */])({ sum_ });
const reduction_ops_prod = Object(operation["a" /* op */])({ prod_ });
//# sourceMappingURL=reduction_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/square.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes square of `x` element-wise: `x ^ 2`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);
*
* x.square().print(); // or tf.square(x)
* ```
* @param x The input Tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function square_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "square");
const attrs = {};
const inputsToSave = [$x];
const outputsToSave = [];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
save([$x]);
return backend.square($x);
},
{ x: $x },
null /* grad */,
"Square",
attrs,
inputsToSave,
outputsToSave
);
}
const square = Object(operation["a" /* op */])({ square_ });
//# sourceMappingURL=square.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/unary_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes `-1 * x` element-wise.
*
* ```js
* const x = tf.tensor2d([1, 2, -2, 0], [2, 2]);
*
* x.neg().print(); // or tf.neg(x)
* ```
*
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function neg_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "neg");
const grad = (dy) => {
return { x: () => dy.neg() };
};
const attrs = {};
const inputsToSave = [$x];
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.neg($x),
{ x: $x },
grad,
"Neg",
attrs,
inputsToSave
);
}
/**
* Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.ceil().print(); // or tf.ceil(x)
* ```
* @param x The input Tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function ceil_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "ceil");
// TODO(manrajgrover): Return null for gradients when backprop supports it.
const grad = (dy) => {
return { $x: () => Object(tensor_ops["o" /* zerosLike */])(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.ceil($x), { $x }, grad);
}
/**
* Computes floor of input `tf.Tensor` element-wise: `floor(x)`.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.floor().print(); // or tf.floor(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function floor_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "floor");
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
const grad = (dy) => {
return { $x: () => Object(tensor_ops["o" /* zerosLike */])(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.floor($x), { $x }, grad);
}
/**
* Returns an element-wise indication of the sign of a number.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3, NaN, 0]);
*
* x.sign().print(); // or tf.sign(x)
* ```
* @param x The input Tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function sign_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "sign");
const grad = (dy) => {
return { $x: () => Object(tensor_ops["o" /* zerosLike */])(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.sign($x), { $x }, grad);
}
/**
* RReturns which elements of x are NaN.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isNaN().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function isNaN_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "isNaN");
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
const grad = (dy) => {
return { $x: () => Object(tensor_ops["o" /* zerosLike */])(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.isNaN($x), { $x }, grad);
}
/**
* Returns which elements of x are Infinity or -Infinity.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isInf().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function isInf_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "isInf");
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
const grad = (dy) => {
return { $x: () => Object(tensor_ops["o" /* zerosLike */])(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.isInf($x), { $x }, grad);
}
/**
* Returns which elements of x are finite.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isFinite().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function isFinite_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "isFinite");
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
const grad = (dy) => {
return { $x: () => Object(tensor_ops["o" /* zerosLike */])(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.isFinite($x),
{ $x },
grad
);
}
/**
* Computes round of input `tf.Tensor` element-wise: `round(x)`.
* It implements banker's rounding.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.round().print(); // or tf.round(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function round_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "round");
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
const grad = (dy) => {
return { $x: () => Object(tensor_ops["o" /* zerosLike */])(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.round($x), { $x }, grad);
}
/**
* Computes exponential of the input `tf.Tensor` element-wise. `e ^ x`
*
* ```js
* const x = tf.tensor1d([1, 2, -3]);
*
* x.exp().print(); // or tf.exp(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function exp_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "exp");
const bck = (dy, saved) => {
// tslint:disable-next-line: no-unnecessary-type-assertion
return { x: () => dy.mul(saved[0]) };
};
const attrs = {};
const inputsToSave = [];
const outputsToSave = [true];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const y = backend.exp($x);
save([y]);
return y;
},
{ x: $x },
bck,
"Exp",
attrs,
inputsToSave,
outputsToSave
);
}
/**
* Computes exponential of the input `tf.Tensor` minus one element-wise.
* `e ^ x - 1`
*
* ```js
* const x = tf.tensor1d([1, 2, -3]);
*
* x.expm1().print(); // or tf.expm1(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function expm1_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "expm1");
const grad = (dy, saved) => {
const [$x] = saved;
return { $x: () => dy.mul($x.exp()) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.expm1($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes natural logarithm of the input `tf.Tensor` element-wise: `ln(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.E]);
*
* x.log().print(); // or tf.log(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function log_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "log");
const grad = (dy, saved) => {
const [$x] = saved;
return { x: () => dy.div($x.toFloat()) };
};
const attrs = {};
const inputsToSave = [$x];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.log($x);
save([$x]);
return res;
},
{ x: $x },
grad,
"Log",
attrs,
inputsToSave
);
}
/**
* Computes natural logarithm of the input `tf.Tensor` plus one
* element-wise: `ln(1 + x)`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.E - 1]);
*
* x.log1p().print(); // or tf.log1p(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function log1p_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "log1p");
const grad = (dy, saved) => {
const [$x] = saved;
return { $x: () => dy.div($x.add(1)) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.log1p($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes square root of the input `tf.Tensor` element-wise: `y = sqrt(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, 4, -1]);
*
* x.sqrt().print(); // or tf.sqrt(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function sqrt_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "sqrt");
const grad = (dy, saved) => {
const [$x] = saved;
return { x: () => dy.div($x.toFloat().sqrt().mul(2)) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.sqrt($x);
save([$x]);
return res;
},
{ x: $x },
grad,
"Sqrt",
{}
);
}
/**
* Computes reciprocal of square root of the input `tf.Tensor` element-wise:
* `y = 1 / sqrt(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, 4, -1]);
*
* x.rsqrt().print(); // or tf.rsqrt(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function rsqrt_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "rsqrt");
const grad = (dy, saved) => {
const [$x] = saved;
return { x: () => dy.div($x.pow(1.5).mul(2)).neg() };
};
const inputsToSave = [$x];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.rsqrt($x);
save([$x]);
return res;
},
{ x: $x },
grad,
"Rsqrt",
{} /* attrs */,
inputsToSave
);
}
/**
* Computes reciprocal of x element-wise: `1 / x`
*
* ```js
* const x = tf.tensor1d([0, 1, 2]);
*
* x.reciprocal().print(); // or tf.reciprocal(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function reciprocal_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "reciprocal");
const grad = (dy, saved) => {
const [$x] = saved;
return { $x: () => dy.div($x.square().neg()) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.reciprocal($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes absolute value element-wise: `abs(x)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.abs().print(); // or tf.abs(x)
* ```
* @param x The input `tf.Tensor`.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function abs_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "abs");
if ($x.dtype === "complex64") {
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.complexAbs($x), {
$x,
});
}
const grad = (dy, saved) => {
const [$x] = saved;
return { x: () => dy.mul($x.toFloat().step(-1)) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.abs($x);
save([$x]);
return res;
},
{ x: $x },
grad,
"Abs"
);
}
/**
* Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.clipByValue(-2, 3).print(); // or tf.clipByValue(x, -2, 3)
* ```
* @param x The input tensor.
* @param clipValueMin Lower-bound of range to be clipped to.
* @param clipValueMax Upper-bound of range to be clipped to.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function clipByValue_(x, clipValueMin, clipValueMax) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "clipByValue");
util["assert"](
clipValueMin <= clipValueMax,
() =>
`Error in clip: min (${clipValueMin}) must be ` +
`less than or equal to max (${clipValueMax}).`
);
const grad = (dy, saved) => {
const [$x] = saved;
return {
x: () =>
dy.where(
$x.greaterEqual(clipValueMin).logicalAnd($x.lessEqual(clipValueMax)),
Object(tensor_ops["o" /* zerosLike */])(dy)
),
};
};
const inputsToSave = [$x];
const attr = { min: clipValueMin, max: clipValueMax };
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.clip($x, clipValueMin, clipValueMax);
save([$x]);
return res;
},
{ x: $x },
grad,
"ClipByValue",
attr,
inputsToSave
);
}
/**
* Computes sigmoid element-wise, `1 / (1 + exp(-x))`
*
* ```js
* const x = tf.tensor1d([0, -1, 2, -3]);
*
* x.sigmoid().print(); // or tf.sigmoid(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function sigmoid_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "sigmoid");
const grad = (dy, saved) => {
const [y] = saved;
return { x: () => dy.mul(y.mul(Object(tensor_ops["e" /* scalar */])(1).sub(y))) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const y = backend.sigmoid($x);
save([y]);
return y;
},
{ x: $x },
grad,
"Sigmoid"
);
}
/**
* Computes log sigmoid of the input `tf.Tensor` element-wise:
* `logSigmoid(x)`. For numerical stability, we use `-tf.softplus(-x)`.
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.logSigmoid().print(); // or tf.logSigmoid(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function logSigmoid_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "logSigmoid");
const grad = (dy, saved) => {
const [$x] = saved;
return { $x: () => dy.mul($x.neg().sigmoid()) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.softplus($x.neg()).neg();
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes softplus of the input `tf.Tensor` element-wise: `log(exp(x) + 1)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.softplus().print(); // or tf.softplus(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function softplus_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "softplus");
const grad = (dy, saved) => {
const [$x] = saved;
return { $x: () => dy.mul($x.sigmoid()) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.softplus($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes sin of the input Tensor element-wise: `sin(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.sin().print(); // or tf.sin(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function sin_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "sin");
const grad = (dy, saved) => {
const [$x] = saved;
return { x: () => $x.toFloat().cos().mul(dy) };
};
const inputsToSave = [$x];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.sin($x);
save([$x]);
return res;
},
{ x: $x },
grad,
"Sin",
{} /* attrs */,
inputsToSave
);
}
/**
* Computes cos of the input `tf.Tensor` element-wise: `cos(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.cos().print(); // or tf.cos(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function cos_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "cos");
const grad = (dy, saved) => {
const [$x] = saved;
return { x: () => $x.toFloat().sin().neg().mul(dy) };
};
const inputsToSave = [$x];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.cos($x);
save([$x]);
return res;
},
{ x: $x },
grad,
"Cos",
{} /* attrs */,
inputsToSave
);
}
/**
* Computes tan of the input `tf.Tensor` element-wise, `tan(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.tan().print(); // or tf.tan(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function tan_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "tan");
const grad = (dy, saved) => {
const [$x] = saved;
return { $x: () => dy.div($x.cos().square()) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.tan($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes asin of the input `tf.Tensor` element-wise: `asin(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asin().print(); // or tf.asin(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function asin_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "asin");
const grad = (dy, saved) => {
const [$x] = saved;
return {
// tslint:disable-next-line: no-unnecessary-type-assertion
$x: () =>
dy.div(Object(tensor_ops["e" /* scalar */])(1).sub($x.toFloat().square()).sqrt()),
};
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.asin($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes acos of the input `tf.Tensor` element-wise: `acos(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.acos().print(); // or tf.acos(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function acos_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "acos");
const grad = (dy, saved) => {
const [$x] = saved;
return {
$x: () => {
const a = $x.toFloat().square();
const b = Object(tensor_ops["e" /* scalar */])(1).sub(a).sqrt();
// tslint:disable-next-line: no-unnecessary-type-assertion
return dy.div(b).neg();
},
};
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.acos($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes atan of the input `tf.Tensor` element-wise: `atan(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.atan().print(); // or tf.atan(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function atan_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "atan");
const grad = (dy, saved) => {
const [$x] = saved;
return { $x: () => dy.div($x.toFloat().square().add(1)) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.atan($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes hyperbolic sin of the input `tf.Tensor` element-wise: `sinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.sinh().print(); // or tf.sinh(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function sinh_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "sinh");
const grad = (dy, saved) => {
const [$x] = saved;
// tslint:disable-next-line: no-unnecessary-type-assertion
return { $x: () => $x.toFloat().cosh().mul(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.sinh($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.cosh().print(); // or tf.cosh(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function cosh_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "cosh");
const grad = (dy, saved) => {
const [$x] = saved;
// tslint:disable-next-line: no-unnecessary-type-assertion
return { $x: () => $x.toFloat().sinh().mul(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.cosh($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes hyperbolic tangent of the input `tf.Tensor` element-wise: `tanh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, 70]);
*
* x.tanh().print(); // or tf.tanh(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function tanh_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "tanh");
const grad = (dy, saved) => {
const [y] = saved;
// tslint:disable-next-line: no-unnecessary-type-assertion
return { x: () => Object(tensor_ops["e" /* scalar */])(1).sub(y.square()).mul(dy) };
};
const outputsToSave = [true];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const y = backend.tanh($x);
save([y]);
return y;
},
{ x: $x },
grad,
"Tanh",
{} /* attrs */,
null /* inputsToSave */,
outputsToSave
);
}
/**
* Computes inverse hyperbolic sin of the input `tf.Tensor` element-wise:
* `asinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asinh().print(); // or tf.asinh(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function asinh_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "asinh");
const grad = (dy, saved) => {
const [$x] = saved;
return {
$x: () => {
const a = Object(tensor_ops["e" /* scalar */])(1).add($x.toFloat().square()).sqrt();
// tslint:disable-next-line: no-unnecessary-type-assertion
return dy.div(a);
},
};
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.asinh($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes the inverse hyperbolic cos of the input `tf.Tensor` element-wise:
* `acosh(x)`
*
* ```js
* const x = tf.tensor1d([10, 1, 3, 5.7]);
*
* x.acosh().print(); // or tf.acosh(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function acosh_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "acosh");
const grad = (dy, saved) => {
const [$x] = saved;
return {
$x: () => {
const a = $x.toFloat().square().sub(1).sqrt();
// tslint:disable-next-line: no-unnecessary-type-assertion
return dy.div(a);
},
};
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.acosh($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:
* `atanh(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.atanh().print(); // or tf.atanh(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function atanh_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "atanh");
const grad = (dy, saved) => {
const [$x] = saved;
return {
$x: () => dy.div(Object(tensor_ops["e" /* scalar */])(1).sub($x.toFloat().square())),
};
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.atanh($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes gause error function of the input `tf.Tensor` element-wise:
* `erf(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.erf().print(); // or tf.erf(x);
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function erf_(x) {
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "erf");
util["assert"](
$x.dtype === "int32" || $x.dtype === "float32",
() => "Input dtype must be `int32` or `float32`."
);
if ($x.dtype === "int32") {
$x = $x.toFloat();
}
const grad = (dy, saved) => {
const [$x] = saved;
return {
$x: () =>
dy.mul(
$x
.square()
.neg()
.exp()
.mul(2 / Math.sqrt(Math.PI))
),
};
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.erf($x);
save([$x]);
return res;
},
{ $x },
grad
);
}
/**
* Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha * x`
*
* ```js
* const x = tf.tensor1d([0, 2, -1, -3]);
*
* x.step(.5).print(); // or tf.step(x, .5)
* ```
* @param x The input tensor.
* @param alpha The gradient when input is negative.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function step_(x, alpha = 0.0) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "step");
// TODO(manrajgrover): Return null for gradients when backprop supports
// it.
const grad = (dy) => {
return { $x: () => Object(tensor_ops["o" /* zerosLike */])(dy) };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.step($x, alpha),
{ $x },
grad
);
}
const abs = Object(operation["a" /* op */])({ abs_ });
const acos = Object(operation["a" /* op */])({ acos_ });
const acosh = Object(operation["a" /* op */])({ acosh_ });
const asin = Object(operation["a" /* op */])({ asin_ });
const asinh = Object(operation["a" /* op */])({ asinh_ });
const atan = Object(operation["a" /* op */])({ atan_ });
const atanh = Object(operation["a" /* op */])({ atanh_ });
const ceil = Object(operation["a" /* op */])({ ceil_ });
const clipByValue = Object(operation["a" /* op */])({ clipByValue_ });
const cos = Object(operation["a" /* op */])({ cos_ });
const cosh = Object(operation["a" /* op */])({ cosh_ });
const erf = Object(operation["a" /* op */])({ erf_ });
const unary_ops_exp = Object(operation["a" /* op */])({ exp_ });
const expm1 = Object(operation["a" /* op */])({ expm1_ });
const floor = Object(operation["a" /* op */])({ floor_ });
const log = Object(operation["a" /* op */])({ log_ });
const log1p = Object(operation["a" /* op */])({ log1p_ });
const logSigmoid = Object(operation["a" /* op */])({ logSigmoid_ });
const neg = Object(operation["a" /* op */])({ neg_ });
const reciprocal = Object(operation["a" /* op */])({ reciprocal_ });
const round = Object(operation["a" /* op */])({ round_ });
const rsqrt = Object(operation["a" /* op */])({ rsqrt_ });
const sigmoid = Object(operation["a" /* op */])({ sigmoid_ });
const sign = Object(operation["a" /* op */])({ sign_ });
const unary_ops_isNaN = Object(operation["a" /* op */])({ isNaN_ });
const isInf = Object(operation["a" /* op */])({ isInf_ });
const unary_ops_isFinite = Object(operation["a" /* op */])({ isFinite_ });
const sin = Object(operation["a" /* op */])({ sin_ });
const sinh = Object(operation["a" /* op */])({ sinh_ });
const softplus = Object(operation["a" /* op */])({ softplus_ });
const sqrt = Object(operation["a" /* op */])({ sqrt_ });
const unary_ops_step = Object(operation["a" /* op */])({ step_ });
const tan = Object(operation["a" /* op */])({ tan_ });
const tanh = Object(operation["a" /* op */])({ tanh_ });
//# sourceMappingURL=unary_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Atan2_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const atan2GradConfig = {
kernelName: kernel_names["c" /* Atan2 */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const d = add(square(a), square(b));
let res = mul(dy, div(b, d));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = sum(res, reduceAxes);
}
return reshape(res, a.shape);
};
const derB = () => {
const d = add(square(a), square(b));
let res = neg(mul(dy, div(a, d)));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = sum(res, reduceAxes);
}
return reshape(res, b.shape);
};
return { a: derA, b: derB };
},
};
//# sourceMappingURL=Atan2_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function computePool2DInfo(
inShape,
filterSize,
strides,
dilations,
pad,
roundingMode,
dataFormat = "channelsLast"
) {
const [filterHeight, filterWidth] = parseTupleParam(filterSize);
let filterShape;
if (dataFormat === "channelsLast") {
filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];
} else if (dataFormat === "channelsFirst") {
filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];
} else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
return computeConv2DInfo(
inShape,
filterShape,
strides,
dilations,
pad,
roundingMode,
false,
dataFormat
);
}
/**
* Computes the information for a forward pass of a pooling3D operation.
*/
function computePool3DInfo(
inShape,
filterSize,
strides,
dilations,
pad,
roundingMode,
dataFormat = "NDHWC"
) {
const [filterDepth, filterHeight, filterWidth] = parse3TupleParam(filterSize);
let filterShape;
let $dataFormat;
if (dataFormat === "NDHWC") {
$dataFormat = "channelsLast";
filterShape = [filterDepth, filterHeight, filterWidth, inShape[4], inShape[4]];
} else if (dataFormat === "NCDHW") {
$dataFormat = "channelsFirst";
filterShape = [filterDepth, filterHeight, filterWidth, inShape[1], inShape[1]];
} else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
return computeConv3DInfo(
inShape,
filterShape,
strides,
dilations,
pad,
false,
$dataFormat,
roundingMode
);
}
/**
* Computes the information for a forward pass of a convolution/pooling
* operation.
*/
function computeConv2DInfo(
inShape,
filterShape,
strides,
dilations,
pad,
roundingMode,
depthwise = false,
dataFormat = "channelsLast"
) {
let [batchSize, inHeight, inWidth, inChannels] = [-1, -1, -1, -1];
if (dataFormat === "channelsLast") {
[batchSize, inHeight, inWidth, inChannels] = inShape;
} else if (dataFormat === "channelsFirst") {
[batchSize, inChannels, inHeight, inWidth] = inShape;
} else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
const [filterHeight, filterWidth, , filterChannels] = filterShape;
const [strideHeight, strideWidth] = parseTupleParam(strides);
const [dilationHeight, dilationWidth] = parseTupleParam(dilations);
const effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
const effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
const { padInfo, outHeight, outWidth } = getPadAndOutInfo(
pad,
inHeight,
inWidth,
strideHeight,
strideWidth,
effectiveFilterHeight,
effectiveFilterWidth,
roundingMode,
dataFormat
);
const outChannels = depthwise ? filterChannels * inChannels : filterChannels;
let outShape;
if (dataFormat === "channelsFirst") {
outShape = [batchSize, outChannels, outHeight, outWidth];
} else if (dataFormat === "channelsLast") {
outShape = [batchSize, outHeight, outWidth, outChannels];
}
return {
batchSize,
dataFormat,
inHeight,
inWidth,
inChannels,
outHeight,
outWidth,
outChannels,
padInfo,
strideHeight,
strideWidth,
filterHeight,
filterWidth,
effectiveFilterHeight,
effectiveFilterWidth,
dilationHeight,
dilationWidth,
inShape,
outShape,
filterShape,
};
}
/**
* Computes the information for a forward pass of a 3D convolution/pooling
* operation.
*/
function computeConv3DInfo(
inShape,
filterShape,
strides,
dilations,
pad,
depthwise = false,
dataFormat = "channelsLast",
roundingMode
) {
let [batchSize, inDepth, inHeight, inWidth, inChannels] = [-1, -1, -1, -1, -1];
if (dataFormat === "channelsLast") {
[batchSize, inDepth, inHeight, inWidth, inChannels] = inShape;
} else if (dataFormat === "channelsFirst") {
[batchSize, inChannels, inDepth, inHeight, inWidth] = inShape;
} else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
const [filterDepth, filterHeight, filterWidth, , filterChannels] = filterShape;
const [strideDepth, strideHeight, strideWidth] = parse3TupleParam(strides);
const [dilationDepth, dilationHeight, dilationWidth] = parse3TupleParam(dilations);
const effectiveFilterDepth = getEffectiveFilterSize(filterDepth, dilationDepth);
const effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
const effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
const { padInfo, outDepth, outHeight, outWidth } = get3DPadAndOutInfo(
pad,
inDepth,
inHeight,
inWidth,
strideDepth,
strideHeight,
strideWidth,
effectiveFilterDepth,
effectiveFilterHeight,
effectiveFilterWidth,
roundingMode
);
const outChannels = depthwise ? filterChannels * inChannels : filterChannels;
let outShape;
if (dataFormat === "channelsFirst") {
outShape = [batchSize, outChannels, outDepth, outHeight, outWidth];
} else if (dataFormat === "channelsLast") {
outShape = [batchSize, outDepth, outHeight, outWidth, outChannels];
}
return {
batchSize,
dataFormat,
inDepth,
inHeight,
inWidth,
inChannels,
outDepth,
outHeight,
outWidth,
outChannels,
padInfo,
strideDepth,
strideHeight,
strideWidth,
filterDepth,
filterHeight,
filterWidth,
effectiveFilterDepth,
effectiveFilterHeight,
effectiveFilterWidth,
dilationDepth,
dilationHeight,
dilationWidth,
inShape,
outShape,
filterShape,
};
}
function computeOutputShape2D(inShape, fieldSize, stride, zeroPad, roundingMode) {
if (zeroPad == null) {
zeroPad = computeDefaultPad(inShape, fieldSize, stride);
}
const inputRows = inShape[0];
const inputCols = inShape[1];
const outputRows = conditionalRound(
(inputRows - fieldSize + 2 * zeroPad) / stride + 1,
roundingMode
);
util["assert"](
util["isInt"](outputRows),
() =>
`The output # of rows (${outputRows}) must be an integer. ` +
`Change the stride and/or zero pad parameters`
);
const outputCols = conditionalRound(
(inputCols - fieldSize + 2 * zeroPad) / stride + 1,
roundingMode
);
util["assert"](
util["isInt"](outputCols),
() =>
`The output # of columns (${outputCols}) must be an integer. ` +
`Change the stride and/or zero pad parameters`
);
return [outputRows, outputCols];
}
function computeOutputShape4D(
inShape,
fieldSize,
outChannels,
stride,
zeroPad,
roundingMode
) {
if (zeroPad == null) {
zeroPad = computeDefaultPad(inShape, fieldSize, stride);
}
const inputDepth = inShape[0];
const inputRows = inShape[1];
const inputCols = inShape[2];
const outputDepths = conditionalRound(
(inputDepth - fieldSize + 2 * zeroPad) / stride + 1,
roundingMode
);
util["assert"](
util["isInt"](outputDepths),
() =>
`The output # of depths (${outputDepths}) must be an integer. ` +
`Change the stride and/or zero pad parameters`
);
const outputRows = conditionalRound(
(inputRows - fieldSize + 2 * zeroPad) / stride + 1,
roundingMode
);
util["assert"](
util["isInt"](outputRows),
() =>
`The output # of rows (${outputRows}) must be an integer. ` +
`Change the stride and/or zero pad parameters`
);
const outputCols = conditionalRound(
(inputCols - fieldSize + 2 * zeroPad) / stride + 1,
roundingMode
);
util["assert"](
util["isInt"](outputCols),
() =>
`The output # of columns (${outputCols}) must be an integer. ` +
`Change the stride and/or zero pad parameters`
);
return [outputDepths, outputRows, outputCols, outChannels];
}
function computeDefaultPad(inputShape, fieldSize, stride, dilation = 1) {
const effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);
return Math.floor((inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);
}
function parseTupleParam(param) {
if (typeof param === "number") {
return [param, param, param];
}
if (param.length === 2) {
return [param[0], param[1], 1];
}
return param;
}
function parse3TupleParam(param) {
return typeof param === "number" ? [param, param, param] : param;
}
/* See https://www.tensorflow.org/api_docs/python/tf/nn/atrous_conv2d
* Atrous convolution is equivalent to standard convolution with upsampled
* filters with effective_filter_height =
* filter_height + (filter_height - 1) * (dilation - 1)
* and effective_filter_width =
* filter_width + (filter_width - 1) * (dilation - 1),
* produced by inserting dilation - 1 zeros along consecutive elements across
* the filters' spatial dimensions.
* When there is a dilation, this converts a filter dimension to the
* effective filter dimension, so it can be used in a standard convolution.
*/
function getEffectiveFilterSize(filterSize, dilation) {
if (dilation <= 1) {
return filterSize;
}
return filterSize + (filterSize - 1) * (dilation - 1);
}
function getPadAndOutInfo(
pad,
inHeight,
inWidth,
strideHeight,
strideWidth,
filterHeight,
filterWidth,
roundingMode,
dataFormat
) {
let padInfo;
let outHeight;
let outWidth;
if (typeof pad === "number") {
const padType = pad === 0 ? "VALID" : "NUMBER";
padInfo = { top: pad, bottom: pad, left: pad, right: pad, type: padType };
const outShape = computeOutputShape2D(
[inHeight, inWidth],
filterHeight,
strideHeight,
pad,
roundingMode
);
outHeight = outShape[0];
outWidth = outShape[1];
} else if (pad === "same") {
outHeight = Math.ceil(inHeight / strideHeight);
outWidth = Math.ceil(inWidth / strideWidth);
const padAlongHeight = Math.max(
0,
(outHeight - 1) * strideHeight + filterHeight - inHeight
);
const padAlongWidth = Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);
const top = Math.floor(padAlongHeight / 2);
const bottom = padAlongHeight - top;
const left = Math.floor(padAlongWidth / 2);
const right = padAlongWidth - left;
padInfo = { top, bottom, left, right, type: "SAME" };
} else if (pad === "valid") {
padInfo = { top: 0, bottom: 0, left: 0, right: 0, type: "VALID" };
outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
} else if (typeof pad === "object") {
const top = dataFormat === "channelsLast" ? pad[1][0] : pad[2][0];
const bottom = dataFormat === "channelsLast" ? pad[1][1] : pad[2][1];
const left = dataFormat === "channelsLast" ? pad[2][0] : pad[3][0];
const right = dataFormat === "channelsLast" ? pad[2][1] : pad[3][1];
const padType =
top === 0 && bottom === 0 && left === 0 && right === 0 ? "VALID" : "EXPLICIT";
padInfo = { top, bottom, left, right, type: padType };
outHeight = conditionalRound(
(inHeight - filterHeight + top + bottom) / strideHeight + 1,
roundingMode
);
outWidth = conditionalRound(
(inWidth - filterWidth + left + right) / strideWidth + 1,
roundingMode
);
} else {
throw Error(`Unknown padding parameter: ${pad}`);
}
return { padInfo, outHeight, outWidth };
}
function get3DPadAndOutInfo(
pad,
inDepth,
inHeight,
inWidth,
strideDepth,
strideHeight,
strideWidth,
filterDepth,
filterHeight,
filterWidth,
roundingMode
) {
let padInfo;
let outDepth;
let outHeight;
let outWidth;
if (typeof pad === "number") {
const padType = pad === 0 ? "VALID" : "NUMBER";
padInfo = {
top: pad,
bottom: pad,
left: pad,
right: pad,
front: pad,
back: pad,
type: padType,
};
const outShape = computeOutputShape4D(
[inDepth, inHeight, inWidth, 1],
filterDepth,
1,
strideDepth,
pad,
roundingMode
);
outDepth = outShape[0];
outHeight = outShape[1];
outWidth = outShape[2];
} else if (pad === "same") {
outDepth = Math.ceil(inDepth / strideDepth);
outHeight = Math.ceil(inHeight / strideHeight);
outWidth = Math.ceil(inWidth / strideWidth);
const padAlongDepth = (outDepth - 1) * strideDepth + filterDepth - inDepth;
const padAlongHeight = (outHeight - 1) * strideHeight + filterHeight - inHeight;
const padAlongWidth = (outWidth - 1) * strideWidth + filterWidth - inWidth;
const front = Math.floor(padAlongDepth / 2);
const back = padAlongDepth - front;
const top = Math.floor(padAlongHeight / 2);
const bottom = padAlongHeight - top;
const left = Math.floor(padAlongWidth / 2);
const right = padAlongWidth - left;
padInfo = { top, bottom, left, right, front, back, type: "SAME" };
} else if (pad === "valid") {
padInfo = {
top: 0,
bottom: 0,
left: 0,
right: 0,
front: 0,
back: 0,
type: "VALID",
};
outDepth = Math.ceil((inDepth - filterDepth + 1) / strideDepth);
outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
} else {
throw Error(`Unknown padding parameter: ${pad}`);
}
return { padInfo, outDepth, outHeight, outWidth };
}
/**
* Rounds a value depending on the rounding mode
* @param value
* @param roundingMode
*/
function conditionalRound(value, roundingMode) {
if (!roundingMode) {
return value;
}
switch (roundingMode) {
case "round":
// used for Caffe Conv
return Math.round(value);
case "ceil":
// used for Caffe Pool
return Math.ceil(value);
case "floor":
return Math.floor(value);
default:
throw new Error(`Unknown roundingMode ${roundingMode}`);
}
}
function tupleValuesAreOne(param) {
const [dimA, dimB, dimC] = parseTupleParam(param);
return dimA === 1 && dimB === 1 && dimC === 1;
}
function eitherStridesOrDilationsAreOne(strides, dilations) {
return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);
}
/**
* Convert Conv2D dataFormat from 'NHWC'|'NCHW' to
* 'channelsLast'|'channelsFirst'
* @param dataFormat in 'NHWC'|'NCHW' mode
* @return dataFormat in 'channelsLast'|'channelsFirst' mode
* @throws unknown dataFormat
*/
function convertConv2DDataFormat(dataFormat) {
if (dataFormat === "NHWC") {
return "channelsLast";
} else if (dataFormat === "NCHW") {
return "channelsFirst";
} else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
}
//# sourceMappingURL=conv_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/avg_pool_3d_backprop.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the backprop of a 3d avg pool.
*
* @param dy The dy error, of rank 5 of shape
* [batchSize, depth, height, width, channels].
* assumed.
* @param input The original input image, of rank 5 or rank4 of shape
* [batchSize, depth, height, width, channels].
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations Deprecated, this field will be gone in v3.0.0. The dilation
* rates: `[dilationDepth, dilationHeight, dilationWidth]`
* in which we sample input values across the depth, height and width
* dimensions in dilated pooling.
* Defaults to `[1, 1, 1]`. If `dilations` is a single number,
* then `dilationDepth == dilationHeight == dilationWidth`.
* If it is greater than 1, then all values of `strides` must be 1.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. The
* rounding mode used when computing output dimensions if pad is a
* number. If none is provided, it will not round and error if the output
* is of fractional size.
*/
function avgPool3dBackprop_(
dy,
input,
filterSize,
strides,
dilations = [1, 1, 1],
pad,
dimRoundingMode
) {
const $dy = Object(tensor_util_env["a" /* convertToTensor */])(
dy,
"dy",
"avgPool3dBackprop"
);
const $input = Object(tensor_util_env["a" /* convertToTensor */])(
input,
"input",
"avgPool3dBackprop"
);
let dy5D = $dy;
let input5D = $input;
let reshapedTo5D = false;
if ($input.rank === 4) {
reshapedTo5D = true;
dy5D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
input5D = reshape($input, [
1,
$input.shape[0],
$input.shape[1],
$input.shape[2],
$input.shape[3],
]);
}
util["assert"](
dy5D.rank === 5,
() => `Error in avgPool3dBackprop: dy must be rank 5 but got rank ` + `${dy5D.rank}.`
);
util["assert"](
input5D.rank === 5,
() =>
`Error in avgPool3dBackprop: input must be rank 5 but got rank ` + `${input5D.rank}.`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in avgPool3dBackprop: Either strides or dilations " +
`must be 1. Got strides ${strides} and dilations '${dilations}'`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in maxPool3dBackprop: pad must be an integer when ` +
`using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend) => {
const convInfo = computePool3DInfo(
input5D.shape,
filterSize,
strides,
dilations,
pad,
dimRoundingMode
);
return backend.avgPool3dBackprop(dy5D, input5D, convInfo);
};
const inputs = { dy: dy5D, input: input5D };
const attrs = { filterSize, strides, dilations, pad, dimRoundingMode };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["f" /* AvgPool3DBackprop */],
attrs
);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const avgPool3dBackprop = Object(operation["a" /* op */])({ avgPool3dBackprop_ });
//# sourceMappingURL=avg_pool_3d_backprop.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/AvgPool3D_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const avgPool3DGradConfig = {
kernelName: kernel_names["e" /* AvgPool3D */],
inputsToSave: ["x"],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { filterSize, strides, dilations, pad, dimRoundingMode } = attrs;
const $dilations = dilations == null ? [1, 1, 1] : dilations;
return {
x: () =>
avgPool3dBackprop(dy, x, filterSize, strides, $dilations, pad, dimRoundingMode),
};
},
};
//# sourceMappingURL=AvgPool3D_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/avg_pool_backprop.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the backprop of an 2D avg pool.
*
* @param dy The dy error, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param input The input image, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
*/
function avgPoolBackprop_(dy, input, filterSize, strides, pad) {
const $dy = Object(tensor_util_env["a" /* convertToTensor */])(dy, "dy", "avgPoolBackprop");
const $input = Object(tensor_util_env["a" /* convertToTensor */])(
input,
"input",
"avgPoolBackprop"
);
util["assert"](
$input.rank === $dy.rank,
() => `Rank of input (${$input.rank}) does not match rank of dy (${$dy.rank})`
);
let input4D = $input;
let dy4D = $dy;
let reshapedTo4D = false;
if ($input.rank === 3) {
reshapedTo4D = true;
input4D = reshape($input, [1, $input.shape[0], $input.shape[1], $input.shape[2]]);
dy4D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2]]);
}
util["assert"](
dy4D.rank === 4,
() => `Error in avgPoolBackprop: dy must be rank 4 but got rank ` + `${dy4D.rank}.`
);
util["assert"](
input4D.rank === 4,
() => `Error in avgPoolBackprop: input must be rank 4 but got rank ` + `${input4D.rank}.`
);
const forward = (backend) => {
const convInfo = computePool2DInfo(
input4D.shape,
filterSize,
strides,
1 /* dilations */,
pad
);
return backend.avgPoolBackprop(dy4D, input4D, convInfo);
};
const inputs = { dy: dy4D, input: input4D };
const attrs = { filterSize, strides, pad };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null,
kernel_names["g" /* AvgPoolBackprop */],
attrs
);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const avgPoolBackprop = Object(operation["a" /* op */])({ avgPoolBackprop_ });
//# sourceMappingURL=avg_pool_backprop.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/AvgPool_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const avgPoolGradConfig = {
kernelName: kernel_names["d" /* AvgPool */],
inputsToSave: ["x"],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { filterSize, strides, pad } = attrs;
return {
x: () => avgPoolBackprop(dy, x, filterSize, strides, pad),
};
},
};
//# sourceMappingURL=AvgPool_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/mat_mul.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the dot product of two matrices, A * B. These must be matrices.
*
* ```js
* const a = tf.tensor2d([1, 2], [1, 2]);
* const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* a.matMul(b).print(); // or tf.matMul(a, b)
* ```
* @param a First matrix in dot product operation.
* @param b Second matrix in dot product operation.
* @param transposeA If true, `a` is transposed before multiplication.
* @param transposeB If true, `b` is transposed before multiplication.
*/
/** @doc {heading: 'Operations', subheading: 'Matrices'} */
function matMul_(a, b, transposeA = false, transposeB = false) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "matMul");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "matMul");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
util["assert"](
$a.rank >= 2 && $b.rank >= 2 && $a.rank === $b.rank,
() =>
`Error in matMul: inputs must have the same rank of at least 2, ` +
`got ranks ${$a.rank} and ${$b.rank}.`
);
const innerShapeA = transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];
const innerShapeB = transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];
const outerShapeA = transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];
const outerShapeB = transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];
const outerDimsA = $a.shape.slice(0, -2);
const outerDimsB = $b.shape.slice(0, -2);
const batchDimA = util["sizeFromShape"](outerDimsA);
const batchDimB = util["sizeFromShape"](outerDimsB);
util["assert"](
util["arraysEqual"](outerDimsA, outerDimsB),
() =>
`Error in matMul: outer dimensions (${outerDimsA}) and (` +
`${outerDimsB}) of Tensors with shapes ${$a.shape} and ` +
`${$b.shape} must match.`
);
util["assert"](
innerShapeA === innerShapeB,
() =>
`Error in matMul: inner shapes (${innerShapeA}) and (` +
`${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +
`${$b.shape} and transposeA=${transposeA}` +
` and transposeB=${transposeB} must match.`
);
const outShape = $a.shape.slice(0, -2).concat([outerShapeA, outerShapeB]);
const a3D = transposeA
? reshape($a, [batchDimA, innerShapeA, outerShapeA])
: reshape($a, [batchDimA, outerShapeA, innerShapeA]);
const b3D = transposeB
? reshape($b, [batchDimB, outerShapeB, innerShapeB])
: reshape($b, [batchDimB, innerShapeB, outerShapeB]);
const forward = (backend, save) => {
save([a3D, b3D]);
return backend.batchMatMul(a3D, b3D, transposeA, transposeB);
};
const inputs = { a: a3D, b: b3D };
const attrs = { transposeA, transposeB };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["h" /* BatchMatMul */],
attrs
);
return reshape(res, outShape);
}
const matMul = Object(operation["a" /* op */])({ matMul_ });
//# sourceMappingURL=mat_mul.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/BatchMatMul_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const batchMatMulGradConfig = {
kernelName: kernel_names["h" /* BatchMatMul */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved, attrs) => {
const [a, b] = saved;
const { transposeA, transposeB } = attrs;
if (!transposeA && !transposeB) {
return {
a: () => matMul(dy, b, false, true),
b: () => matMul(a, dy, true, false),
};
} else if (!transposeA && transposeB) {
return {
a: () => matMul(dy, b, false, false),
b: () => matMul(dy, a, true, false),
};
} else if (transposeA && !transposeB) {
return {
a: () => matMul(b, dy, false, true),
b: () => matMul(a, dy, false, false),
};
} else {
return {
a: () => matMul(b, dy, true, true),
b: () => matMul(dy, a, true, true),
};
}
},
};
//# sourceMappingURL=BatchMatMul_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/space_to_batch_nd.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* This operation divides "spatial" dimensions `[1, ..., M]` of the input into
* a grid of blocks of shape `blockShape`, and interleaves these blocks with
* the "batch" dimension (0) such that in the output, the spatial
* dimensions `[1, ..., M]` correspond to the position within the grid,
* and the batch dimension combines both the position within a spatial block
* and the original batch position. Prior to division into blocks,
* the spatial dimensions of the input are optionally zero padded
* according to `paddings`. See below for a precise description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
* const blockShape = [2, 2];
* const paddings = [[0, 0], [0, 0]];
*
* x.spaceToBatchND(blockShape, paddings).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param paddings A 2-D array. Must have shape `[M, 2]`, all values must be >=
* 0. `paddings[i] = [padStart, padEnd]` specifies the amount to zero-pad
* from input dimension `i + 1`, which corresponds to spatial dimension `i`. It
* is required that
* `(inputShape[i + 1] + padStart + padEnd) % blockShape[i] === 0`
*
* This operation is equivalent to the following steps:
*
* 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input
* according to `paddings` to produce `padded` of shape paddedShape.
*
* 2. Reshape `padded` to `reshapedPadded` of shape:
* `[batch] + [paddedShape[1] / blockShape[0], blockShape[0], ...,
* paddedShape[M] / blockShape[M-1], blockShape[M-1]] + remainingShape`
*
* 3. Permute dimensions of `reshapedPadded` to produce `permutedReshapedPadded`
* of shape: `blockShape + [batch] + [paddedShape[1] / blockShape[0], ...,
* paddedShape[M] / blockShape[M-1]] + remainingShape`
*
* 4. Reshape `permutedReshapedPadded` to flatten `blockShape` into the
* batch dimension, producing an output tensor of shape:
* `[batch * prod(blockShape)] + [paddedShape[1] / blockShape[0], ...,
* paddedShape[M] / blockShape[M-1]] + remainingShape`
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function spaceToBatchND_(x, blockShape, paddings) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "spaceToBatchND");
util["assert"](
$x.rank >= 1 + blockShape.length,
() => `input rank ${$x.rank} should be > than [blockShape] ${blockShape.length}`
);
util["assert"](
paddings.length === blockShape.length,
() =>
`paddings.shape[0] ${paddings.length} must be equal to [blockShape] ${blockShape.length}`
);
util["assert"](
$x.shape.reduce((a, b, i) => {
if (i > 0 && i <= blockShape.length) {
return a && (b + paddings[i - 1][0] + paddings[i - 1][1]) % blockShape[i - 1] === 0;
}
return a;
}, true),
() =>
`input spatial dimensions ${$x.shape.slice(
1
)} with paddings ${paddings.toString()} must be divisible by blockShapes ${blockShape.toString()}`
);
const forward = (backend) => backend.spaceToBatchND($x, blockShape, paddings);
const inputs = { x: $x };
const attrs = { blockShape, paddings };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["mb" /* SpaceToBatchND */],
attrs
);
}
const spaceToBatchND = Object(operation["a" /* op */])({ spaceToBatchND_ });
//# sourceMappingURL=space_to_batch_nd.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/BatchToSpaceND_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const batchToSpaceNDGradConfig = {
kernelName: kernel_names["i" /* BatchToSpaceND */],
gradFunc: (dy, saved, attrs) => {
const { blockShape, crops } = attrs;
return { x: () => spaceToBatchND(dy, blockShape, crops) };
},
};
//# sourceMappingURL=BatchToSpaceND_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/BroadcastTo_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const broadcastToGradConfig = {
kernelName: kernel_names["j" /* BroadcastTo */],
gradFunc: (dy, saved, attrs) => {
const broadCastToAttrs = attrs;
const inputShape = broadCastToAttrs.inputShape;
const outputShape = broadCastToAttrs.shape;
const reps = Array.from(outputShape);
for (let i = inputShape.length - 1; i >= 0; i--) {
if (inputShape[i] === outputShape[i]) {
reps[i] = 1;
} else if (inputShape[i] !== 1) {
throw new Error(
`broadcastTo(): [${inputShape}] cannot be broadcast to [${outputShape}].`
);
}
}
const axes = [];
for (let i = 0; i < reps.length; i++) {
if (reps[i] > 1) {
axes.push(i);
}
}
return { x: () => sum(dy, axes, true /* keepDims */) };
},
};
//# sourceMappingURL=BroadcastTo_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/split.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Splits a `tf.Tensor` into sub tensors.
*
* If `numOrSizeSplits` is a number, splits `x` along dimension `axis`
* into `numOrSizeSplits` smaller tensors.
* Requires that `numOrSizeSplits` evenly divides `x.shape[axis]`.
*
* If `numOrSizeSplits` is a number array, splits `x` into
* `numOrSizeSplits.length` pieces. The shape of the `i`-th piece has the
* same size as `x` except along dimension `axis` where the size is
* `numOrSizeSplits[i]`.
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [2, 4]);
* const [a, b] = tf.split(x, 2, 1);
* a.print();
* b.print();
*
* const [c, d, e] = tf.split(x, [1, 2, 1], 1);
* c.print();
* d.print();
* e.print();
* ```
*
* @param x The input tensor to split.
* @param numOrSizeSplits Either an integer indicating the number of
* splits along the axis or an array of integers containing the sizes of
* each output tensor along the axis. If a number then it must evenly divide
* `x.shape[axis]`; otherwise the sum of sizes must match `x.shape[axis]`.
* @param axis The dimension along which to split. Defaults to 0 (the first
* dim).
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
function split_(x, numOrSizeSplits, axis = 0) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "split");
const $axis = Object(util["parseAxisParam"])(axis, $x.shape)[0];
let splitSizes;
if (typeof numOrSizeSplits === "number") {
Object(util["assert"])(
$x.shape[$axis] % numOrSizeSplits === 0,
() => "Number of splits must evenly divide the axis."
);
splitSizes = new Array(numOrSizeSplits).fill($x.shape[$axis] / numOrSizeSplits);
} else {
Object(util["assert"])(
$x.shape[$axis] === numOrSizeSplits.reduce((a, b) => a + b),
() => "The sum of sizes must match the size of the axis dimension."
);
splitSizes = numOrSizeSplits;
}
const forward = (backend, _) => {
return backend.split($x, splitSizes, $axis);
};
const inputs = { x: $x };
const attr = { numOrSizeSplits, axis };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["nb" /* SplitV */],
attr
);
}
const split = Object(operation["a" /* op */])({ split_ });
//# sourceMappingURL=split.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Concat_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const concatGradConfig = {
kernelName: kernel_names["l" /* Concat */],
saveAllInputs: true,
gradFunc: (dy, saved, attrs) => {
const shapes = saved.map((t) => t.shape);
const { axis } = attrs;
const $axis = Object(util["parseAxisParam"])(axis, saved[0].shape)[0];
const sizeSplits = shapes.map((s) => s[$axis]);
const derTensors = split(dy, sizeSplits, $axis);
return derTensors.map((t) => () => t);
},
};
//# sourceMappingURL=Concat_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv2d_backprop_filter.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the filter of a 2D convolution.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed.
* @param dy The dy image, of rank 4 or rank 3, of shape
* [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed.
* @param filterShape The shape of the filter, length 4,
* [filterHeight, filterWidth, inDepth, outDepth].
* @param strides The strides of the convolution: [strideHeight,
* strideWidth].
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. The
* rounding mode used when computing output dimensions if pad is a
* number. If none is provided, it will not round and error if the output
* is of fractional size.
*/
function conv2DBackpropFilter_(
x,
dy,
filterShape,
strides,
pad,
dataFormat = "NHWC",
dimRoundingMode
) {
let x4D = x;
if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
let dy4D = dy;
if (dy4D.rank === 3) {
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
util["assert"](
x4D.rank === 4,
() => `Error in conv2dDerFilter: input must be rank 4, but got shape ` + `${x4D.shape}.`
);
util["assert"](
dy4D.rank === 4,
() => `Error in conv2dDerFilter: dy must be rank 4, but got shape ` + `${dy4D.shape}.`
);
util["assert"](
filterShape.length === 4,
() =>
`Error in conv2dDerFilter: filterShape must be length 4, but got ` + `${filterShape}.`
);
const inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
const outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
util["assert"](
inDepth === filterShape[2],
() =>
`Error in conv2dDerFilter: depth of input ${inDepth}) must ` +
`match input depth in filter (${filterShape[2]}.`
);
util["assert"](
outDepth === filterShape[3],
() =>
`Error in conv2dDerFilter: depth of dy (${outDepth}) must ` +
`match output depth for filter (${filterShape[3]}).`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in conv2dDerFilter: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend) => {
const dilations = 1;
const $dataFormat = convertConv2DDataFormat(dataFormat);
const convInfo = computeConv2DInfo(
x4D.shape,
filterShape,
strides,
dilations,
pad,
dimRoundingMode,
false,
$dataFormat
);
return backend.conv2dDerFilter(x4D, dy4D, convInfo);
};
const inputs = { x: x4D, dy: dy4D };
const attrs = { strides, pad, dataFormat, dimRoundingMode };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null,
kernel_names["n" /* Conv2DBackpropFilter */],
attrs
);
}
const conv2DBackpropFilter = Object(operation["a" /* op */])({ conv2DBackpropFilter_ });
//# sourceMappingURL=conv2d_backprop_filter.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv2d_backprop_input.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the input of a 2D convolution.
*
* @param xShape The shape of the input: [batch, height, width, inDepth].
* If length of 3, batch of 1 is assumed.
* @param dy The derivative of the output, of rank 4 or rank 3 of shape
* `[batch, outHeight, outWidth, outDepth]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm used:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
function conv2DBackpropInput_(
xShape,
dy,
filter,
strides,
pad,
dataFormat = "NHWC",
dimRoundingMode
) {
util["assert"](
xShape.length === dy.rank,
() => `Length of inShape ` + `(${xShape.length}) and rank of dy (${dy.rank}) must match`
);
let xShape4D = xShape;
let dy4D = dy;
let reshapedTo4D = false;
if (dy.rank === 3) {
reshapedTo4D = true;
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
xShape4D = [1, xShape[0], xShape[1], xShape[2]];
}
util["assert"](
xShape4D.length === 4,
() =>
`Error in conv2dDerInput: inShape must be length 4, but got length ` +
`${xShape4D.length}.`
);
util["assert"](
dy4D.rank === 4,
() => `Error in conv2dDerInput: dy must be rank 4, but got ` + `rank ${dy4D.rank}`
);
util["assert"](
filter.rank === 4,
() => `Error in conv2dDerInput: filter must be rank 4, but got ` + `rank ${filter.rank}`
);
const inDepth = dataFormat === "NHWC" ? xShape4D[3] : xShape4D[1];
const outDepth = dataFormat === "NHWC" ? dy4D.shape[3] : dy4D.shape[1];
util["assert"](
inDepth === filter.shape[2],
() =>
`Error in conv2dDerInput: depth of input (${inDepth}) must ` +
`match input depth for filter ${filter.shape[2]}.`
);
util["assert"](
outDepth === filter.shape[3],
() =>
`Error in conv2dDerInput: depth of output (${outDepth}) must ` +
`match output depth for filter ${filter.shape[3]}.`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in conv2dDerInput: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend, save) => {
const dilations = 1;
const $dataFormat = convertConv2DDataFormat(dataFormat);
const convInfo = computeConv2DInfo(
xShape4D,
filter.shape,
strides,
dilations,
pad,
dimRoundingMode,
false,
$dataFormat
);
const res = backend.conv2dDerInput(dy4D, filter, convInfo);
save([dy4D, filter]);
return res;
};
const inputs = { dy: dy4D, filter };
const attrs = { strides, pad, dataFormat, dimRoundingMode };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["o" /* Conv2DBackpropInput */],
attrs
);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const conv2DBackpropInput = Object(operation["a" /* op */])({ conv2DBackpropInput_ });
//# sourceMappingURL=conv2d_backprop_input.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Conv2D_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const conv2DGradConfig = {
kernelName: kernel_names["m" /* Conv2D */],
inputsToSave: ["x", "filter"],
gradFunc: (dy, saved, attrs) => {
const [x4D, $filter] = saved;
const { dilations, strides, pad, dataFormat } = attrs;
util["assert"](
tupleValuesAreOne(dilations),
() =>
"Error in gradient of conv2D: dilation rates greater than 1 " +
`are not yet supported in gradients. Got dilations '${dilations}'`
);
return {
x: () => conv2DBackpropInput(x4D.shape, dy, $filter, strides, pad, dataFormat),
filter: () => conv2DBackpropFilter(x4D, dy, $filter.shape, strides, pad, dataFormat),
};
},
};
//# sourceMappingURL=Conv2D_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv2d.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes a 2D convolution over the input x.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function conv2d_(
x,
filter,
strides,
pad,
dataFormat = "NHWC",
dilations = [1, 1],
dimRoundingMode
) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "conv2d");
const $filter = Object(tensor_util_env["a" /* convertToTensor */])(
filter,
"filter",
"conv2d"
);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
util["assert"](
x4D.rank === 4,
() => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`
);
util["assert"](
$filter.rank === 4,
() => `Error in conv2d: filter must be rank 4, but got rank ` + `${$filter.rank}.`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in conv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const inDepth = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
util["assert"](
inDepth === $filter.shape[2],
() =>
`Error in conv2d: depth of input (${inDepth}) must match ` +
`input depth for filter ${$filter.shape[2]}.`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in conv2D: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
const forward = (backend, save) => {
const $dataFormat = convertConv2DDataFormat(dataFormat);
const convInfo = computeConv2DInfo(
x4D.shape,
$filter.shape,
strides,
dilations,
pad,
dimRoundingMode,
false,
$dataFormat
);
const res = backend.conv2d(x4D, $filter, convInfo);
save([x4D, $filter]);
return res;
};
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations, dimRoundingMode };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["m" /* Conv2D */],
attrs
);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const conv2d = Object(operation["a" /* op */])({ conv2d_ });
//# sourceMappingURL=conv2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Conv2DBackpropInput_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const conv2DBackpropInputGradConfig = {
kernelName: kernel_names["o" /* Conv2DBackpropInput */],
inputsToSave: ["dy", "filter"],
gradFunc: (ddx, saved, attrs) => {
const [dy, filter] = saved;
const { strides, pad, dataFormat, dimRoundingMode } = attrs;
return {
dy: () =>
conv2d(ddx, filter, strides, pad, dataFormat, 1 /* dilations */, dimRoundingMode),
filter: () =>
conv2DBackpropFilter(
ddx,
dy,
filter.shape,
strides,
pad,
dataFormat,
dimRoundingMode
),
};
},
};
//# sourceMappingURL=Conv2DBackpropInput_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv3d_backprop_filter.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the filter of a 3D convolution.
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* [batch, depth, height, width, inChannels]. If rank 4, batch of 1 is
* assumed.
* @param dy The dy image, of rank 5 or rank 4, of shape
* [batch, depth, height, width, outDepth]. If rank 4, batch of 1 is
* assumed.
* @param filterShape The shape of the filter, length 5,
* [filterDepth, filterHeight, filterWidth, inDepth, outDepth].
* @param strides The strides of the convolution: [strideDepth, strideHeight,
* strideWidth].
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
*/
function conv3DBackpropFilter_(x, dy, filterShape, strides, pad) {
let x5D = x;
if (x.rank === 4) {
x5D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2], x.shape[3]]);
}
let dy5D = dy;
if (dy5D.rank === 4) {
dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
}
util["assert"](
x5D.rank === 5,
() => `Error in conv3dDerFilter: input must be rank 5, but got shape ` + `${x5D.shape}.`
);
util["assert"](
dy5D.rank === 5,
() => `Error in conv3dDerFilter: dy must be rank 5, but got shape ` + `${dy5D.shape}.`
);
util["assert"](
filterShape.length === 5,
() =>
`Error in conv3dDerFilter: filterShape must be length 5, but got ` + `${filterShape}.`
);
util["assert"](
x5D.shape[4] === filterShape[3],
() =>
`Error in conv3dDerFilter: depth of input ${x5D.shape[4]}) must ` +
`match input depth in filter (${filterShape[3]}.`
);
util["assert"](
dy5D.shape[4] === filterShape[4],
() =>
`Error in conv3dDerFilter: depth of dy (${dy5D.shape[4]}) must ` +
`match output depth for filter (${filterShape[4]}).`
);
const forward = (backend) => {
const dilations = 1;
const convInfo = computeConv3DInfo(x5D.shape, filterShape, strides, dilations, pad);
return backend.conv3dDerFilter(x5D, dy5D, convInfo);
};
const inputs = { x: x5D, y: dy5D };
const attrs = { strides, pad };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null,
kernel_names["q" /* Conv3DBackpropFilterV2 */],
attrs
);
}
const conv3DBackpropFilter = Object(operation["a" /* op */])({ conv3DBackpropFilter_ });
//# sourceMappingURL=conv3d_backprop_filter.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv3d_backprop_input.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the input of a 3D convolution.
*
* @param xShape The shape of the input: [batch, depth, height, width,
* in_channels]. If length of 4, batch of 1 is assumed.
* @param dy The derivative of the output, of rank 5 or rank 4 of shape
* `[batch, outDepth, outHeight, outWidth, in_channels]`.
* If rank 4, batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm used:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
*/
function conv3DBackpropInput_(xShape, dy, filter, strides, pad) {
util["assert"](
xShape.length === dy.rank,
() => `Length of inShape ` + `(${xShape.length}) and rank of dy (${dy.rank}) must match`
);
let xShape5D = xShape;
let dy5D = dy;
let reshapedTo5D = false;
if (dy.rank === 4) {
reshapedTo5D = true;
dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
}
const inDepth = xShape5D[4];
const outDepth = dy5D.shape[4];
util["assert"](
xShape5D.length === 5,
() =>
`Error in conv3dDerInput: inShape must be length 5, but got length ` +
`${xShape5D.length}.`
);
util["assert"](
dy5D.rank === 5,
() => `Error in conv3dDerInput: dy must be rank 5, but got ` + `rank ${dy5D.rank}`
);
util["assert"](
filter.rank === 5,
() => `Error in conv3dDerInput: filter must be rank 5, but got ` + `rank ${filter.rank}`
);
util["assert"](
inDepth === filter.shape[3],
() =>
`Error in conv3dDerInput: depth of input (${inDepth}) must ` +
`match input depth for filter ${filter.shape[3]}.`
);
util["assert"](
outDepth === filter.shape[4],
() =>
`Error in conv3dDerInput: depth of output (${outDepth}) must ` +
`match output depth for filter ${filter.shape[4]}.`
);
const forward = (backend) => {
const dilations = 1;
const convInfo = computeConv3DInfo(xShape5D, filter.shape, strides, dilations, pad);
return backend.conv3dDerInput(dy5D, filter, convInfo);
};
const inputs = { dy: dy5D };
const attrs = { pad };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null,
kernel_names["r" /* Conv3DBackpropInputV2 */],
attrs
);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const conv3DBackpropInput = Object(operation["a" /* op */])({ conv3DBackpropInput_ });
//# sourceMappingURL=conv3d_backprop_input.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Conv3D_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const conv3DGradConfig = {
kernelName: kernel_names["p" /* Conv3D */],
inputsToSave: ["x", "filter"],
gradFunc: (dy, saved, attrs) => {
const { dilations, strides, pad } = attrs;
util["assert"](
tupleValuesAreOne(dilations),
() =>
"Error in gradient of conv3D: dilation rates greater than 1 are " +
`not yet supported in gradients. Got dilations '${dilations}'`
);
const [x5D, $filter] = saved;
return {
x: () => conv3DBackpropInput(x5D.shape, dy, $filter, strides, pad),
filter: () => conv3DBackpropFilter(x5D, dy, $filter.shape, strides, pad),
};
},
};
//# sourceMappingURL=Conv3D_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/transpose.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.
*
* The returned `tf.Tensor`'s dimension `i` will correspond to the input
* dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,
* where `n` is the rank of the input `tf.Tensor`. Hence by default, this
* operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);
*
* a.transpose().print(); // or tf.transpose(a)
* ```
*
* @param x The tensor to transpose.
* @param perm The permutation of the dimensions of a.
*/
/** @doc {heading: 'Operations', subheading: 'Matrices'} */
function transpose_(x, perm) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "transpose");
if (perm == null) {
perm = $x.shape.map((s, i) => i).reverse();
}
util["assert"](
$x.rank === perm.length,
() =>
`Error in transpose: rank of input ${$x.rank} ` + `must match length of perm ${perm}.`
);
perm.forEach((axis) => {
util["assert"](
axis >= 0 && axis < $x.rank,
() => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` + ` but got ${perm}`
);
});
if ($x.rank <= 1) {
return $x.clone();
}
const attrs = { perm };
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.transpose($x, perm),
{ x: $x },
null /* gradient */,
"Transpose",
attrs
);
}
const transpose = Object(operation["a" /* op */])({ transpose_ });
//# sourceMappingURL=transpose.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/cumsum.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the cumulative sum of a `tf.Tensor` along `axis`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4]);
* x.cumsum().print();
* ```
* ```js
* const x = tf.tensor([[1, 2], [3, 4]]);
* x.cumsum().print();
* ```
*
* @param x The input tensor to be summed.
* @param axis The axis along which to sum. Optional. Defaults to 0.
* @param exclusive Whether to perform exclusive cumulative sum. Optional.
* Defaults to false. If set to true then the sum of each tensor entry
* does not include its own value, but only the values previous to it
* along the specified axis.
* @param reverse Whether to sum in the opposite direction. Optional.
* Defaults to false.
*/
/** @doc {heading: 'Operations', subheading: 'Scan'} */
function cumsum_(x, axis = 0, exclusive = false, reverse = false) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "cumsum");
const forward = (backend, save) => {
const permutation = getAxesPermutation([axis], $x.rank);
let permutedX = $x;
if (permutation != null) {
permutedX = transpose($x, permutation);
}
const permutedAxis = getInnerMostAxes(1, $x.rank)[0];
let value = backend.cumsum(permutedX, permutedAxis, exclusive, reverse);
save([$x]);
if (permutation != null) {
value = transpose(value, permutation);
}
return value;
};
const inputs = { x: $x };
const attrs = { axis, exclusive, reverse };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["s" /* Cumsum */],
attrs
);
}
const cumsum = Object(operation["a" /* op */])({ cumsum_ });
//# sourceMappingURL=cumsum.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Cumsum_grad.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const cumsumGradConfig = {
kernelName: kernel_names["s" /* Cumsum */],
inputsToSave: ["x"],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { axis, exclusive, reverse } = attrs;
return {
x: () => {
const permutation = getAxesPermutation([axis], x.rank);
let out = cumsum(dy, axis, exclusive, !reverse);
if (permutation != null) {
out = transpose(out, permutation);
}
return out;
},
};
},
};
//# sourceMappingURL=Cumsum_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/depthwise_conv2d_native_backprop_filter.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, convInfo) {
let x4D = x;
if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
let dy4D = dy;
if (dy4D.rank === 3) {
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
const forward = (backend) => backend.depthwiseConv2DDerFilter(x4D, dy4D, convInfo);
const inputs = { x: x4D, dy: dy4D };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null,
kernel_names["v" /* DepthwiseConv2dNativeBackpropFilter */]
);
}
const depthwiseConv2dNativeBackpropFilter = Object(operation["a" /* op */])({
depthwiseConv2dNativeBackpropFilter_,
});
//# sourceMappingURL=depthwise_conv2d_native_backprop_filter.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/depthwise_conv2d_native_backprop_input.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, convInfo) {
let dy4D = dy;
let reshapedTo4D = false;
if (dy.rank === 3) {
reshapedTo4D = true;
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
const forward = (backend) => backend.depthwiseConv2DDerInput(dy4D, filter, convInfo);
const inputs = { dy: dy4D };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null,
kernel_names["w" /* DepthwiseConv2dNativeBackpropInput */]
);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const depthwiseConv2dNativeBackpropInput = Object(operation["a" /* op */])({
depthwiseConv2dNativeBackpropInput_,
});
//# sourceMappingURL=depthwise_conv2d_native_backprop_input.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/DepthwiseConv2dNative_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const depthwiseConv2dNativeGradConfig = {
kernelName: kernel_names["u" /* DepthwiseConv2dNative */],
inputsToSave: ["x", "filter"],
gradFunc: (dy, saved, attrs) => {
const { dilations, strides, pad, dimRoundingMode } = attrs;
const $dilations = dilations == null ? [1, 1] : dilations;
util["assert"](
tupleValuesAreOne($dilations),
() =>
"Error in gradient of depthwiseConv2dNative: dilation rates " +
`greater than 1 are not yet supported. Got dilations ` +
`'${$dilations}'`
);
const [x, filter] = saved;
util["assert"](
x.rank === 4,
() =>
`Error in gradient of depthwiseConv2dNative: input must be ` +
`rank 4, but got rank ${x.rank}.`
);
util["assert"](
filter.rank === 4,
() =>
`Error in gradient of depthwiseConv2dNative: filter must be ` +
`rank 4, but got rank ${filter.rank}.`
);
util["assert"](
x.shape[3] === filter.shape[2],
() =>
`Error in gradient of depthwiseConv2d: number of input ` +
`channels (${x.shape[3]}) must match the inChannels dimension ` +
`in filter ${filter.shape[2]}.`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, $dilations),
() =>
"Error in gradient of depthwiseConv2d: Either strides or " +
`dilations must be 1. Got strides ${strides} and dilations ` +
`'${$dilations}'.`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in depthwiseConv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const convInfo = computeConv2DInfo(
x.shape,
filter.shape,
strides,
$dilations,
pad,
dimRoundingMode,
true /* depthwise */
);
return {
x: () => depthwiseConv2dNativeBackpropInput(x.shape, dy, filter, convInfo),
filter: () => depthwiseConv2dNativeBackpropFilter(x, dy, filter.shape, convInfo),
};
},
};
//# sourceMappingURL=DepthwiseConv2dNative_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Div_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const divGradConfig = {
kernelName: kernel_names["y" /* Div */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = div(dy, b.toFloat());
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return sum(res, reduceAxes).reshape(a.shape);
}
return res;
};
const derB = () => {
let res = mul(dy, a.toFloat());
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = reshape(sum(res, reduceAxes), b.shape);
}
const tmp = square(b);
return neg(div(res, tmp.toFloat()));
};
return { a: derA, b: derB };
},
};
//# sourceMappingURL=Div_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Elu_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const eluGradConfig = {
kernelName: kernel_names["z" /* Elu */],
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
const backPropKernelFunc = (backend) => {
return backend.eluDer(dy, y);
};
const inputs = { dy, y };
return {
x: () =>
engine["a" /* ENGINE */].runKernelFunc(
backPropKernelFunc,
inputs,
null /* grad */,
kernel_names["A" /* EluGrad */]
),
};
},
};
//# sourceMappingURL=Elu_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/FloorDiv_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const floorDivGradConfig = {
kernelName: kernel_names["D" /* FloorDiv */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = dy.div(b.toFloat());
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return res.sum(reduceAxes).reshape(a.shape);
}
return res;
};
const derB = () => {
let res = dy.mul(a.toFloat());
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = res.sum(reduceAxes).reshape(b.shape);
}
const tmp = b.square();
return res.div(tmp.toFloat()).neg();
};
return { a: derA, b: derB };
},
};
//# sourceMappingURL=FloorDiv_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sub.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Subtracts two `tf.Tensor`s element-wise, A - B. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([10, 20, 30, 40]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.sub(b).print(); // or tf.sub(a, b)
* ```
*
* ```js
* // Broadcast subtract a with b.
* const a = tf.tensor1d([10, 20, 30, 40]);
* const b = tf.scalar(5);
*
* a.sub(b).print(); // or tf.sub(a, b)
* ```
* @param a The first `tf.Tensor` to subtract from.
* @param b The second `tf.Tensor` to be subtracted. Must have the same dtype as
* `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function sub_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "sub");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "sub");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
const forward = (backend, save) => {
const res = backend.subtract($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["qb" /* Sub */]
);
}
const sub = Object(operation["a" /* op */])({ sub_ });
//# sourceMappingURL=sub.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/tile.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Construct a tensor by repeating it the number of times given by reps.
*
* This operation creates a new tensor by replicating `input` `reps`
* times. The output tensor's i'th dimension has `input.shape[i] *
* reps[i]` elements, and the values of `input` are replicated
* `reps[i]` times along the i'th dimension. For example, tiling
* `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
*
* a.tile([2]).print(); // or a.tile([2])
* ```
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* a.tile([1, 2]).print(); // or a.tile([1, 2])
* ```
* @param x The tensor to tile.
* @param reps Determines the number of replications per dimension.
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
function tile_(x, reps) {
const parseAs = null;
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "tile", parseAs);
util["assert"](
$x.rank === reps.length,
() =>
`Error in transpose: rank of input ${$x.rank} ` + `must match length of reps ${reps}.`
);
const forward = (backend, save) => {
const res = backend.tile($x, reps);
save([$x]);
return res;
};
const inputsToSave = [$x];
const inputs = { x: $x };
const attrs = { reps };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["rb" /* Tile */],
attrs,
inputsToSave
);
}
const tile = Object(operation["a" /* op */])({ tile_ });
//# sourceMappingURL=tile.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/FusedBatchNorm_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const fusedBatchNormGradConfig = {
kernelName: kernel_names["F" /* FusedBatchNorm */],
inputsToSave: ["x", "mean", "variance", "scale"],
gradFunc: (dy, saved, attrs) => {
const { varianceEpsilon } = attrs;
const [x, mean, variance, scale] = saved;
const scaleValue = scale == null ? Object(tensor_ops["e" /* scalar */])(1) : scale;
const reductionAxes = getReductionAxes(mean.shape, x.shape);
const tileShape = [];
if (mean.rank === 1) {
for (let i = 0; i < x.shape.length - 1; ++i) {
tileShape.push(x.shape[i]);
}
tileShape.push(1);
}
const xMinusMean = sub(x, mean);
const dyTimesScaleValue = mul(dy, scaleValue);
const oneOverSqrtVariance = rsqrt(
add(variance, Object(tensor_ops["e" /* scalar */])(varianceEpsilon))
);
const minusHalfRCube = mul(
mul(mul(oneOverSqrtVariance, oneOverSqrtVariance), oneOverSqrtVariance),
Object(tensor_ops["e" /* scalar */])(-0.5)
);
const derX = () => {
if (mean.rank === 1) {
return reshape(
mul(
mul(dy, tile(oneOverSqrtVariance.as4D(1, 1, 1, mean.shape[0]), tileShape)),
scaleValue
),
x.shape
);
} else {
return reshape(mul(mul(dy, oneOverSqrtVariance), scaleValue), x.shape);
}
};
const derMean = () => {
let meanDer = mul(
mul(oneOverSqrtVariance, Object(tensor_ops["e" /* scalar */])(-1)),
dyTimesScaleValue
);
if (mean.rank === 1) {
meanDer = sum(meanDer, reductionAxes);
}
return reshape(meanDer, mean.shape);
};
const derVariance = () => {
let varianceDer = mul(mul(minusHalfRCube, xMinusMean), dyTimesScaleValue);
if (mean.rank === 1) {
varianceDer = sum(varianceDer, reductionAxes);
}
return reshape(varianceDer, mean.shape);
};
const derScale = () => {
const xMinusMean2TimesRsqrt = mul(xMinusMean, oneOverSqrtVariance);
let scaleDer = mul(dy, xMinusMean2TimesRsqrt);
if (mean.rank === 1) {
scaleDer = sum(scaleDer, reductionAxes);
}
return reshape(scaleDer, mean.shape);
};
const derOffset = () => {
let offsetDer = dy;
if (mean.rank === 1) {
offsetDer = sum(offsetDer, reductionAxes);
}
return reshape(offsetDer, mean.shape);
};
return {
x: derX,
mean: derMean,
variance: derVariance,
scale: derScale,
offset: derOffset,
};
},
};
//# sourceMappingURL=FusedBatchNorm_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/GreaterEqual_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const greaterEqualGradConfig = {
kernelName: kernel_names["I" /* GreaterEqual */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
return {
a: () => Object(tensor_ops["o" /* zerosLike */])(a),
b: () => Object(tensor_ops["o" /* zerosLike */])(b),
};
},
};
//# sourceMappingURL=GreaterEqual_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Identity_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const identityGradConfig = {
kernelName: kernel_names["J" /* Identity */],
gradFunc: (dy) => {
return { x: () => dy.toFloat() };
},
};
//# sourceMappingURL=Identity_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/local_response_normalization_backprop.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function localResponseNormalizationBackprop_(
x,
y,
dy,
depthRadius = 5,
bias = 1,
alpha = 1,
beta = 0.5
) {
const forward = (backend) => backend.LRNGrad(dy, x, y, depthRadius, bias, alpha, beta);
const inputs = { x, y, dy };
const attrs = { depthRadius, bias, alpha, beta };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["M" /* LRNBackprop */],
attrs
);
}
const localResponseNormalizationBackprop = Object(operation["a" /* op */])({
localResponseNormalizationBackprop_,
});
//# sourceMappingURL=local_response_normalization_backprop.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/LRN_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const lrnGradConfig = {
kernelName: kernel_names["L" /* LRN */],
inputsToSave: ["x"],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { depthRadius, bias, alpha, beta } = attrs;
return {
x: () => localResponseNormalizationBackprop(x, y, dy, depthRadius, bias, alpha, beta),
};
},
};
//# sourceMappingURL=LRN_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Max_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxGradConfig = {
kernelName: kernel_names["P" /* Max */],
inputsToSave: ["x"],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const maxAttrs = attrs;
const { reductionIndices } = maxAttrs;
const [x, y] = saved;
const origAxes = util["parseAxisParam"](reductionIndices, x.shape);
const permutedAxes = getAxesPermutation(origAxes, x.rank);
const maxGrad = gradForMinAndMax(dy, y, x, origAxes, permutedAxes);
return {
x: () => {
let out = maxGrad["x"]();
if (permutedAxes != null) {
out = transpose(out);
}
return out;
},
};
},
};
//# sourceMappingURL=Max_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/greater_equal.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a >= b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.greaterEqual(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function greaterEqual_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "greaterEqual");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "greaterEqual");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend, save) => {
const res = backend.greaterEqual($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["I" /* GreaterEqual */]
);
}
const greaterEqual = Object(operation["a" /* op */])({ greaterEqual_ });
//# sourceMappingURL=greater_equal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/less.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a < b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.less(b).print();
* ```
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function less_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "less");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "less");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend) => backend.less($a, $b);
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["N" /* Less */]
);
}
const less = Object(operation["a" /* op */])({ less_ });
//# sourceMappingURL=less.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Maximum_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maximumGradConfig = {
kernelName: kernel_names["V" /* Maximum */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const derA = () => mul(dy, cast(greaterEqual(a, b), "float32"));
const derB = () => mul(dy, cast(less(a, b), "float32"));
return { a: derA, b: derB };
},
};
//# sourceMappingURL=Maximum_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max_pool_3d_backprop.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the backprop of a 3d max pool.
*
* @param dy The dy error, of rank 5 of shape
* [batchSize, depth, height, width, channels].
* assumed.
* @param input The original input image, of rank 5 or rank 4 of shape
* [batchSize, depth, height, width, channels].
* @param output The original output image, of rank 5 of shape
* [batchSize, outDepth, outHeight, outWidth, channels].
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations Deprecated, this field will be gone in v3.0.0.
* The dilation rates: `[dilationDepth, dilationHeight, dilationWidth]`
* in which we sample input values across the depth, height and width
* dimensions in dilated pooling.
* Defaults to `[1, 1, 1]`. If `dilations` is a single number,
* then `dilationDepth == dilationHeight == dilationWidth`.
* If it is greater than 1, then all values of `strides` must be 1.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. The
* rounding mode used when computing output dimensions if pad is a
* number. If none is provided, it will not round and error if the output
* is of fractional size.
*/
function maxPool3dBackprop_(
dy,
input,
output,
filterSize,
strides,
dilations = [1, 1, 1],
pad,
dimRoundingMode
) {
const $dy = Object(tensor_util_env["a" /* convertToTensor */])(
dy,
"dy",
"maxPool3dBackprop"
);
const $input = Object(tensor_util_env["a" /* convertToTensor */])(
input,
"input",
"maxPool3dBackprop"
);
const $output = Object(tensor_util_env["a" /* convertToTensor */])(
output,
"output",
"maxPool3dBackprop"
);
let dy5D = $dy;
let input5D = $input;
let output5D = $output;
let reshapedTo5D = false;
if ($input.rank === 4) {
reshapedTo5D = true;
dy5D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
input5D = reshape($input, [
1,
$input.shape[0],
$input.shape[1],
$input.shape[2],
$input.shape[3],
]);
output5D = reshape($output, [
1,
$output.shape[0],
$output.shape[1],
$output.shape[2],
$output.shape[3],
]);
}
util["assert"](
dy5D.rank === 5,
() => `Error in maxPool3dBackprop: dy must be rank 5 but got rank ` + `${dy5D.rank}.`
);
util["assert"](
input5D.rank === 5,
() =>
`Error in maxPool3dBackprop: input must be rank 5 but got rank ` + `${input5D.rank}.`
);
util["assert"](
output5D.rank === 5,
() =>
`Error in maxPool3dBackprop: output must be rank 5 but got rank ` + `${output5D.rank}.`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in maxPool3dBackprop: Either strides or dilations " +
`must be 1. Got strides ${strides} and dilations '${dilations}'`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in maxPool3dBackprop: pad must be an integer when ` +
`using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend) => {
const convInfo = computePool3DInfo(
input5D.shape,
filterSize,
strides,
dilations,
pad,
dimRoundingMode
);
return backend.maxPool3dBackprop(dy5D, input5D, output5D, convInfo);
};
const inputs = { dy: dy5D, input: input5D, output: output5D };
const attrs = { filterSize, strides, dilations, pad, dimRoundingMode };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["S" /* MaxPool3DBackprop */],
attrs
);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const maxPool3dBackprop = Object(operation["a" /* op */])({ maxPool3dBackprop_ });
//# sourceMappingURL=max_pool_3d_backprop.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/MaxPool3D_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxPool3DGradConfig = {
kernelName: kernel_names["R" /* MaxPool3D */],
inputsToSave: ["x"],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { filterSize, strides, dilations, pad, dimRoundingMode } = attrs;
const $dilations = dilations == null ? [1, 1, 1] : dilations;
return {
x: () =>
maxPool3dBackprop(dy, x, y, filterSize, strides, $dilations, pad, dimRoundingMode),
};
},
};
//# sourceMappingURL=MaxPool3D_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max_pool_backprop.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the backprop of a 2D max pool.
*
* @param dy The dy error, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param input The original input image, of rank 4, of shape
* [batchSize, height, width, channels].
* @param output The original output image, of rank 4, of shape
* [batchSize, outHeight, outWidth, channels].
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. The
* rounding mode used when computing output dimensions if pad is a
* number. If none is provided, it will not round and error if the output
* is of fractional size.
*/
function maxPoolBackprop_(dy, input, output, filterSize, strides, pad, dimRoundingMode) {
const $dy = Object(tensor_util_env["a" /* convertToTensor */])(dy, "dy", "maxPoolBackprop");
const $input = Object(tensor_util_env["a" /* convertToTensor */])(
input,
"input",
"maxPoolBackprop"
);
const $output = Object(tensor_util_env["a" /* convertToTensor */])(
output,
"output",
"maxPoolBackprop"
);
util["assert"](
$input.rank === $dy.rank,
() => `Rank of input (${$input.rank}) does not match rank of dy ` + `(${$dy.rank})`
);
util["assert"](
$dy.rank === 4,
() => `Error in maxPoolBackprop: dy must be rank 4 but got rank ` + `${$dy.rank}.`
);
util["assert"](
$input.rank === 4,
() => `Error in maxPoolBackprop: input must be rank 4 but got rank ` + `${$input.rank}.`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in maxPoolBackprop: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend) => {
const convInfo = computePool2DInfo(
$input.shape,
filterSize,
strides,
1 /* dilations */,
pad,
dimRoundingMode
);
return backend.maxPoolBackprop($dy, $input, $output, convInfo);
};
const inputs = { dy: $dy, input: $input, output: $output };
const attrs = { filterSize, strides, pad, dimRoundingMode };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null,
kernel_names["T" /* MaxPoolBackprop */],
attrs
);
}
const maxPoolBackprop = Object(operation["a" /* op */])({ maxPoolBackprop_ });
//# sourceMappingURL=max_pool_backprop.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/MaxPool_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxPoolGradConfig = {
kernelName: kernel_names["Q" /* MaxPool */],
inputsToSave: ["x"],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { filterSize, strides, pad } = attrs;
return {
x: () => maxPoolBackprop(dy, x, y, filterSize, strides, pad),
};
},
};
//# sourceMappingURL=MaxPool_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/greater.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a > b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.greater(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function greater_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "greater");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "greater");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend) => backend.greater($a, $b);
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["H" /* Greater */]
);
}
const greater = Object(operation["a" /* op */])({ greater_ });
//# sourceMappingURL=greater.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/less_equal.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a <= b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.lessEqual(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function lessEqual_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "lessEqual");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "lessEqual");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend, save) => {
const res = backend.lessEqual($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["O" /* LessEqual */]
);
}
const lessEqual = Object(operation["a" /* op */])({ lessEqual_ });
//# sourceMappingURL=less_equal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Minimum_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const minimumGradConfig = {
kernelName: kernel_names["W" /* Minimum */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const derA = () => mul(dy, cast(lessEqual(a, b), "float32"));
const derB = () => mul(dy, cast(greater(a, b), "float32"));
return { a: derA, b: derB };
},
};
//# sourceMappingURL=Minimum_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Mod_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const modGradConfig = {
kernelName: kernel_names["X" /* Mod */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum(dy, reduceAxes), a.shape);
}
return dy;
};
const derB = () => {
const res = mul(dy, neg(floor(div(a, b))));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum(res, reduceAxes), b.shape);
}
return res;
};
return { a: derA, b: derB };
},
};
//# sourceMappingURL=Mod_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Multiply_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const multiplyGradConfig = {
kernelName: kernel_names["Y" /* Multiply */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = mul(dy, cast(b, "float32"));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum(res, reduceAxes), a.shape);
}
return res;
};
const derB = () => {
const res = mul(dy, cast(a, "float32"));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum(res, reduceAxes), b.shape);
}
return res;
};
return { a: derA, b: derB };
},
};
//# sourceMappingURL=Multiply_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/OneHot_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const oneHotGradConfig = {
kernelName: kernel_names["cb" /* OneHot */],
inputsToSave: ["indices"],
gradFunc: (dy, saved) => {
const indices = saved[0];
return { indices: () => Object(tensor_ops["n" /* zeros */])(indices.shape, "float32") };
},
};
//# sourceMappingURL=OneHot_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/PadV2_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const padV2GradConfig = {
kernelName: kernel_names["db" /* PadV2 */],
inputsToSave: ["x"],
gradFunc: (dy, saved, attrs) => {
// Pad introduces values around the original tensor, so the gradient
// slices the original shape out of the gradient.
const x = saved[0];
const { paddings } = attrs;
const begin = paddings.map((p) => p[0]);
return { x: () => dy.slice(begin, x.shape) };
},
};
//# sourceMappingURL=PadV2_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/where_impl.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** An implementation of the Where kernel shared between cpu and webgl */
function whereImpl(condShape, condVals) {
const indices = [];
for (let i = 0; i < condVals.length; i++) {
if (condVals[i]) {
indices.push(i);
}
}
const inBuffer = array_ops_buffer(condShape, "int32");
const out = array_ops_buffer([indices.length, condShape.length], "int32");
for (let i = 0; i < indices.length; i++) {
const loc = inBuffer.indexToLoc(indices[i]);
const offset = i * condShape.length;
out.values.set(loc, offset);
}
return out.toTensor();
}
//# sourceMappingURL=where_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/logical_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of `NOT x` element-wise.
*
* ```js
* const a = tf.tensor1d([false, true], 'bool');
*
* a.logicalNot().print();
* ```
*
* @param x The input tensor. Must be of dtype 'bool'.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function logicalNot_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "logicalNot", "bool");
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.logicalNot($x), { $x });
}
/**
* Returns the truth value of `a AND b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalAnd(b).print();
* ```
*
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function logicalAnd_(a, b) {
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "logicalAnd", "bool");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "logicalAnd", "bool");
assertAndGetBroadcastShape($a.shape, $b.shape);
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.logicalAnd($a, $b),
{ a: $a, b: $b },
null /* grad */,
"LogicalAnd"
);
}
/**
* Returns the truth value of `a OR b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalOr(b).print();
* ```
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function logicalOr_(a, b) {
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "logicalOr", "bool");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "logicalOr", "bool");
assertAndGetBroadcastShape($a.shape, $b.shape);
return engine["a" /* ENGINE */].runKernelFunc((backend) => backend.logicalOr($a, $b), {
$a,
$b,
});
}
/**
* Returns the truth value of `a XOR b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalXor(b).print();
* ```
*
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function logicalXor_(a, b) {
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "logicalXor", "bool");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "logicalXor", "bool");
assertAndGetBroadcastShape($a.shape, $b.shape);
// x ^ y = (x | y) & ~(x & y)
return logicalOr(a, b).logicalAnd(logicalAnd(a, b).logicalNot());
}
/**
* Returns the elements, either `a` or `b` depending on the `condition`.
*
* If the condition is true, select from `a`, otherwise select from `b`.
*
* ```js
* const cond = tf.tensor1d([false, false, true], 'bool');
* const a = tf.tensor1d([1 , 2, 3]);
* const b = tf.tensor1d([-1, -2, -3]);
*
* a.where(cond, b).print();
* ```
*
* @param condition The input condition. Must be of dtype bool.
* @param a If `condition` is rank 1, `a` may have a higher rank but
* its first dimension must match the size of `condition`.
* @param b A tensor with the same shape and type as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function where_(condition, a, b) {
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "where");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "where");
const $condition = Object(tensor_util_env["a" /* convertToTensor */])(
condition,
"condition",
"where",
"bool"
);
Object(util["assertShapesMatch"])($a.shape, $b.shape, "Error in where: ");
if ($condition.rank === 1) {
// If condition rank is 1, then the first dimension must match the size of
// condition.
Object(util["assert"])(
$condition.shape[0] === $a.shape[0],
() => "The first dimension of `a` must match the size of `condition`."
);
} else {
// A must have the same shape as condition.
Object(util["assertShapesMatch"])($condition.shape, $b.shape, "Error in where: ");
}
// TODO(julianoks): Return null for condition gradient
// when backprop supports it.
const grad = (dy, saved) => {
const [$condition] = saved;
return {
condition: () => Object(tensor_ops["o" /* zerosLike */])($condition).toFloat(),
t: () => dy.mul($condition.cast(dy.dtype)),
e: () => dy.mul($condition.logicalNot().cast(dy.dtype)),
};
};
const inputs = { condition: $condition, t: $a, e: $b };
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.select($condition, $a, $b);
save([$condition]);
return res;
},
inputs,
grad,
kernel_names["kb" /* SelectV2 */]
);
}
/**
* Returns the coordinates of true elements of condition.
*
* The coordinates are returned in a 2-D tensor where the first dimension (rows)
* represents the number of true elements, and the second dimension (columns)
* represents the coordinates of the true elements. Keep in mind, the shape of
* the output tensor can vary depending on how many true values there are in
* input. Indices are output in row-major order. The resulting tensor has the
* shape `[numTrueElems, condition.rank]`.
*
* This is analogous to calling the python `tf.where(cond)` without an x or y.
*
* ```js
* const cond = tf.tensor1d([false, false, true], 'bool');
* const result = await tf.whereAsync(cond);
* result.print();
* ```
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
async function whereAsync_(condition) {
const $condition = Object(tensor_util_env["a" /* convertToTensor */])(
condition,
"condition",
"whereAsync",
"bool"
);
const vals = await $condition.data();
const res = whereImpl($condition.shape, vals);
if (condition !== $condition) {
$condition.dispose();
}
return res;
}
const logicalAnd = Object(operation["a" /* op */])({ logicalAnd_ });
const logicalNot = Object(operation["a" /* op */])({ logicalNot_ });
const logicalOr = Object(operation["a" /* op */])({ logicalOr_ });
const logicalXor = Object(operation["a" /* op */])({ logicalXor_ });
const where = Object(operation["a" /* op */])({ where_ });
const whereAsync = whereAsync_;
//# sourceMappingURL=logical_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pow.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the power of one `tf.Tensor` to another. Supports broadcasting.
*
* Given a `tf.Tensor` x and a `tf.Tensor` y, this operation computes x^y for
* corresponding elements in x and y. The result's dtype will be the upcasted
* type of the `base` and `exp` dtypes.
*
* ```js
* const a = tf.tensor([[2, 3], [4, 5]])
* const b = tf.tensor([[1, 2], [3, 0]]).toInt();
*
* a.pow(b).print(); // or tf.pow(a, b)
* ```
*
* ```js
* const a = tf.tensor([[1, 2], [3, 4]])
* const b = tf.tensor(2).toInt();
*
* a.pow(b).print(); // or tf.pow(a, b)
* ```
* We also expose `powStrict` which has the same signature as this op and
* asserts that `base` and `exp` are the same shape (does not broadcast).
*
* @param base The base `tf.Tensor` to pow element-wise.
* @param exp The exponent `tf.Tensor` to pow element-wise.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function pow_(base, exp) {
let $base = Object(tensor_util_env["a" /* convertToTensor */])(base, "base", "pow");
let $exp = Object(tensor_util_env["a" /* convertToTensor */])(exp, "exp", "pow");
[$base, $exp] = Object(tensor_util["makeTypesMatch"])($base, $exp);
const inputs = { a: $base, b: $exp };
const forward = (backend, save) => {
const y = backend.pow($base, $exp);
save([$base, $exp, y]);
return y;
};
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["fb" /* Pow */]
);
}
const pow = Object(operation["a" /* op */])({ pow_ });
//# sourceMappingURL=pow.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Pow_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const powGradConfig = {
kernelName: kernel_names["fb" /* Pow */],
inputsToSave: ["a", "b"],
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [a, b, y] = saved;
const base = a;
const exp = b;
const outShape = assertAndGetBroadcastShape(base.shape, exp.shape);
const derBase = () => {
const expFloat = cast(exp, "float32");
let res = mul(
dy,
mul(expFloat, pow(base, sub(expFloat, Object(tensor_ops["e" /* scalar */])(1))))
);
const reduceAxes = getReductionAxes(base.shape, outShape);
if (reduceAxes.length > 0) {
res = sum(res, reduceAxes);
}
return reshape(res, base.shape);
};
const derExp = () => {
const condition = greater(base, 0);
const logBase = where(
condition,
log(base),
Object(tensor_ops["o" /* zerosLike */])(base)
);
let res = mul(dy, mul(y, logBase));
const reduceAxes = getReductionAxes(exp.shape, outShape);
if (reduceAxes.length > 0) {
res = sum(res, reduceAxes);
}
return reshape(res, exp.shape);
};
return { a: derBase, b: derExp };
},
};
//# sourceMappingURL=Pow_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Prelu_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const preluGradConfig = {
kernelName: kernel_names["gb" /* Prelu */],
inputsToSave: ["x", "alpha"],
gradFunc: (dy, saved) => {
const [x, alpha] = saved;
const mask = greater(x, 0);
return {
x: () => where(mask, dy, mul(dy, alpha)),
alpha: () => {
let res = where(mask, Object(tensor_ops["o" /* zerosLike */])(dy), mul(dy, x));
const reduceAxes = getReductionAxes(alpha.shape, dy.shape);
if (reduceAxes.length > 0) {
res = sum(res, reduceAxes);
}
return reshape(res, alpha.shape);
},
};
},
};
//# sourceMappingURL=Prelu_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Relu6_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const relu6GradConfig = {
kernelName: kernel_names["jb" /* Relu6 */],
inputsToSave: ["x"],
gradFunc: (dy, saved) => {
const [x] = saved;
const mask = mul(lessEqual(x, 6), unary_ops_step(x));
return { x: () => mul(dy, cast(mask, "float32")) };
},
};
//# sourceMappingURL=Relu6_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Relu_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const reluGradConfig = {
kernelName: kernel_names["ib" /* Relu */],
inputsToSave: ["x"],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, cast(unary_ops_step(x), "float32")) };
},
};
//# sourceMappingURL=Relu_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/selu_util.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const SELU_SCALEALPHA = 1.7580993408473768599402175208123;
const SELU_SCALE = 1.0507009873554804934193349852946;
//# sourceMappingURL=selu_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Selu_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const seluGradConfig = {
kernelName: kernel_names["lb" /* Selu */],
inputsToSave: ["x"],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const mask = greater(x, Object(tensor_ops["e" /* scalar */])(0));
const scaleAlpha = Object(tensor_ops["e" /* scalar */])(SELU_SCALEALPHA);
const scale = Object(tensor_ops["e" /* scalar */])(SELU_SCALE);
const greaterThanZeroDer = mul(dy, scale);
const lessEqualZeroDer = mul(mul(dy, scaleAlpha), unary_ops_exp(cast(x, "float32")));
return where(mask, greaterThanZeroDer, lessEqualZeroDer);
},
};
},
};
//# sourceMappingURL=Selu_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batch_to_space_nd.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of
* shape `blockShape + [batch]`, interleaves these blocks back into the grid
* defined by the spatial dimensions `[1, ..., M]`, to obtain a result with
* the same rank as the input. The spatial dimensions of this intermediate
* result are then optionally cropped according to `crops` to produce the
* output. This is the reverse of `tf.spaceToBatchND`. See below for a precise
* description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);
* const blockShape = [2, 2];
* const crops = [[0, 0], [0, 0]];
*
* x.batchToSpaceND(blockShape, crops).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param crops A 2-D array. Must have shape `[M, 2]`, all values must be >= 0.
* `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input
* dimension `i + 1`, which corresponds to spatial dimension `i`. It is required
* that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`
*
* This operation is equivalent to the following steps:
*
* 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,
* blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,
* x.shape[N-1]]`
*
* 2. Permute dimensions of `reshaped`to produce `permuted` of shape `[batch /
* prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /
* prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`
* according to `crops` to produce the output of shape: `[batch /
* prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],
* ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -
* crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function batchToSpaceND_(x, blockShape, crops) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "batchToSpaceND");
const prod = blockShape.reduce((a, b) => a * b);
util["assert"](
$x.rank >= 1 + blockShape.length,
() =>
`input rank is ${$x.rank} but should be > than blockShape.length ${blockShape.length}`
);
util["assert"](
crops.length === blockShape.length,
() =>
`crops.length is ${crops.length} but should be equal to blockShape.length ${blockShape.length}`
);
util["assert"](
$x.shape[0] % prod === 0,
() =>
`input tensor batch is ${$x.shape[0]} but is not divisible by the product of ` +
`the elements of blockShape ${blockShape.join(" * ")} === ${prod}`
);
const forward = (backend) => {
return backend.batchToSpaceND($x, blockShape, crops);
};
const inputs = { x: $x };
const attrs = { blockShape, crops };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["i" /* BatchToSpaceND */],
attrs
);
}
const batchToSpaceND = Object(operation["a" /* op */])({ batchToSpaceND_ });
//# sourceMappingURL=batch_to_space_nd.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/SpaceToBatchND_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const spaceToBatchNDGradConfig = {
kernelName: kernel_names["mb" /* SpaceToBatchND */],
gradFunc: (dy, saved, attrs) => {
const { blockShape, paddings } = attrs;
return { x: () => batchToSpaceND(dy, blockShape, paddings) };
},
};
//# sourceMappingURL=SpaceToBatchND_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/SplitV_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const splitVGradConfig = {
kernelName: kernel_names["nb" /* SplitV */],
gradFunc: (dy, saved, attrs) => {
const { axis } = attrs;
return { x: () => concat(dy, axis) };
},
};
//# sourceMappingURL=SplitV_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Square_grad.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const squareGradConfig = {
kernelName: kernel_names["ob" /* Square */],
inputsToSave: ["x"],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, mul(x.toFloat(), 2)) };
},
};
//# sourceMappingURL=Square_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/SquaredDifference_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const squaredDifferenceGradConfig = {
kernelName: kernel_names["pb" /* SquaredDifference */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const two = Object(tensor_ops["e" /* scalar */])(2);
const derA = () => mul(dy, mul(two, sub(a, b)));
const derB = () => mul(dy, mul(two, sub(b, a)));
return { a: derA, b: derB };
},
};
//# sourceMappingURL=SquaredDifference_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Sub_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const subGradConfig = {
kernelName: kernel_names["qb" /* Sub */],
inputsToSave: ["a", "b"],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
let res = dy;
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = sum(res, reduceAxes);
}
return reshape(res, a.shape);
};
const derB = () => {
let res = dy;
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = sum(res, reduceAxes);
}
return reshape(neg(res), b.shape);
};
return { a: derA, b: derB };
},
};
//# sourceMappingURL=Sub_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Pads a `tf.Tensor` with a given value and paddings.
*
* This operation currently only implements the `CONSTANT` mode.
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that `paddings` is of given length.
* - `tf.pad1d`
* - `tf.pad2d`
* - `tf.pad3d`
* - `tf.pad4d`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* x.pad([[1, 2]]).print();
* ```
* @param x The tensor to pad.
* @param paddings An array of length `R` (the rank of the tensor), where
* each element is a length-2 tuple of ints `[padBefore, padAfter]`,
* specifying how much to pad along each dimension of the tensor.
* @param constantValue The pad value to use. Defaults to 0.
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function pad_(x, paddings, constantValue = 0) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "pad");
if ($x.rank === 0) {
throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
}
const forward = (backend, save) => {
save([$x]);
return backend.pad($x, paddings, constantValue);
};
const attrs = { paddings, constantValue };
const inputs = { x: $x };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["db" /* PadV2 */],
attrs
);
}
const pad_pad = Object(operation["a" /* op */])({ pad_ });
//# sourceMappingURL=pad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/slice_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function assertParamsValid(input, begin, size) {
util["assert"](
input.rank === begin.length,
() =>
`Error in slice${input.rank}D: Length of begin ${begin} must ` +
`match the rank of the array (${input.rank}).`
);
util["assert"](
input.rank === size.length,
() =>
`Error in slice${input.rank}D: Length of size ${size} must ` +
`match the rank of the array (${input.rank}).`
);
for (let i = 0; i < input.rank; ++i) {
util["assert"](
begin[i] + size[i] <= input.shape[i],
() =>
`Error in slice${input.rank}D: begin[${i}] + size[${i}] ` +
`(${begin[i] + size[i]}) would overflow input.shape[${i}] (${input.shape[i]})`
);
}
}
/** Converts a binary mask to an array of axes. Used in stridedSlice(). */
function maskToAxes(mask) {
const axes = [];
let axis = 0;
while (mask > 0) {
if (mask & 1) {
axes.push(axis);
}
mask /= 2;
axis++;
}
return axes;
}
/** Computes the output shape given the strided slice params. */
function slice_util_computeOutShape(begin, end, strides) {
const size = [];
for (let axis = 0; axis < begin.length; axis++) {
size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);
}
return size;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current stride value. Otherwise, insert.
function stridesWithElidedDims(strides, ellipsisInsertionIndex, numElidedAxes) {
const newStrides = [...strides];
for (let i = 0; i < numElidedAxes; i++) {
if (i === 0) {
newStrides[ellipsisInsertionIndex] = 1;
} else {
newStrides.splice(
ellipsisInsertionIndex,
0 /* num elements to delete */,
1 /* element to add */
);
newStrides.pop();
}
}
return newStrides;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current start value. Otherwise, insert.
function startIndicesWithElidedDims(startIndices, ellipsisInsertionIndex, numElidedAxes) {
const newIndices = [...startIndices];
for (let i = 0; i < numElidedAxes; i++) {
if (i === 0) {
newIndices[ellipsisInsertionIndex] = 0;
} else {
newIndices.splice(
ellipsisInsertionIndex,
0 /* num elements to delete */,
0 /* element to add */
);
newIndices.pop();
}
}
return newIndices;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current stop value. Otherwise, insert.
function stopIndicesWithElidedDims(
stopIndices,
ellipsisInsertionIndex,
numElidedAxes,
inputShape
) {
const newIndices = [...stopIndices];
for (let i = 0; i < numElidedAxes; i++) {
if (i === 0) {
newIndices[ellipsisInsertionIndex] = Number.MAX_SAFE_INTEGER;
} else {
newIndices.splice(
ellipsisInsertionIndex,
0 /* num elements to delete */,
Number.MAX_SAFE_INTEGER /* element to add */
);
newIndices.pop();
}
}
for (let i = 0; i < newIndices.length; i++) {
newIndices[i] = util["clamp"](0, newIndices[i], inputShape[i]);
}
return newIndices;
}
function stridesForAxis(strides, axis, ellipsisMask) {
let stride = strides[axis];
if (ellipsisMask & (1 << axis) || stride == null) {
stride = 1;
}
return stride;
}
function startForAxis(beginMask, startIndices, strides, inputShape, axis, ellipsisMask) {
// Begin with the specified index
let start = startIndices[axis];
const stride = strides[axis] || 1;
// Check the axis bit from right of masked axes, or the begin index is not set
// for the axis.
if (beginMask & (1 << axis) || ellipsisMask & (1 << axis) || start == null) {
if (stride > 0) {
// Forward iteration - use the first element. These values will get
// clamped below (Note: We could have set them to 0 and axis_size-1, but
// use lowest() and max() to maintain symmetry with StopForAxis())
start = Number.MIN_SAFE_INTEGER;
} else {
// Backward iteration - use the last element.
start = Number.MAX_SAFE_INTEGER;
}
}
// Handle negative indices
const axisSize = inputShape[axis];
if (start < 0) {
start += axisSize;
}
// Clamping
start = util["clamp"](0, start, axisSize - 1);
return start;
}
function stopForAxis(endMask, stopIndices, strides, inputShape, axis, ellipsisMask) {
// Begin with the specified index
let stop = stopIndices[axis];
const stride = strides[axis] || 1;
// Check the axis bit from right of masked axes, or if the stop index is not
// set for this axis.
if (endMask & (1 << axis) || ellipsisMask & (1 << axis) || stop == null) {
if (stride > 0) {
// Forward iteration - use the last element. These values will get
// clamped below
stop = Number.MAX_SAFE_INTEGER;
} else {
// Backward iteration - use the first element.
stop = Number.MIN_SAFE_INTEGER;
}
}
// Handle negative indices
const axisSize = inputShape[axis];
if (stop < 0) {
stop += axisSize;
}
// Clamping
// Because the end index points one past the last element, we need slightly
// different clamping ranges depending on the direction.
if (stride > 0) {
// Forward iteration
stop = util["clamp"](0, stop, axisSize);
} else {
// Backward iteration
stop = util["clamp"](-1, stop, axisSize - 1);
}
return stop;
}
/**
* Returns true if the slice occupies a continous set of elements in the
* 'flat' space.
*/
function isSliceContinous(shape, begin, size) {
// Index of the first axis that has size > 1.
let firstNonOneAxis = size.length;
for (let i = 0; i < size.length; i++) {
if (size[i] > 1) {
firstNonOneAxis = i;
break;
}
}
for (let i = firstNonOneAxis + 1; i < size.length; i++) {
if (begin[i] > 0 || size[i] !== shape[i]) {
return false;
}
}
return true;
}
function computeFlatOffset(begin, strides) {
let flatOffset = begin.length > 0 ? begin[begin.length - 1] : 1;
for (let i = 0; i < begin.length - 1; i++) {
flatOffset += begin[i] * strides[i];
}
return flatOffset;
}
//# sourceMappingURL=slice_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/slice.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a 1D slice from 1D array starting at coordinates `begin` and is
* of length `size`. See `slice` for details.
*/
function slice1d_(x, begin, size) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "slice1d");
util["assert"](
$x.rank === 1,
() => `slice1d expects a rank-1 tensor, but got a rank-${$x.rank} tensor`
);
return slice($x, [begin], [size]);
}
/**
* Extracts a 2D slice from a 2D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice2d_(x, begin, size) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "slice2d");
util["assert"](
$x.rank === 2,
() => `slice2d expects a rank-2 tensor, but got a rank-${$x.rank} tensor`
);
return slice($x, begin, size);
}
/**
* Extracts a 3D slice from a 3D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice3d_(x, begin, size) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "slice3d");
util["assert"](
$x.rank === 3,
() => `slice3d expects a rank-3 tensor, but got a rank-${$x.rank} tensor`
);
return slice($x, begin, size);
}
/**
* Extracts a 4D slice from a 4D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice4d_(x, begin, size) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "slice4d");
util["assert"](
$x.rank === 4,
() => `slice4d expects a rank-4 tensor, but got a rank-${$x.rank} tensor`
);
return slice($x, begin, size);
}
/**
* Extracts a slice from a `tf.Tensor` starting at coordinates `begin`
* and is of size `size`.
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that `x` is of the given rank:
* - `tf.slice1d`
* - `tf.slice2d`
* - `tf.slice3d`
* - `tf.slice4d`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.slice([1], [2]).print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* x.slice([1, 0], [1, 2]).print();
* ```
* @param x The input `tf.Tensor` to slice from.
* @param begin The coordinates to start the slice from. The length can be
* less than the rank of x - the rest of the axes will have implicit 0 as
* start. Can also be a single number, in which case it specifies the
* first axis.
* @param size The size of the slice. The length can be less than the rank of
* x - the rest of the axes will have implicit -1. A value of -1 requests
* the rest of the dimensions in the axis. Can also be a single number,
* in which case it specifies the size of the first axis.
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
function slice_(x, begin, size) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "slice");
if ($x.rank === 0) {
throw new Error("Slicing scalar is not possible");
}
// The following logic allows for more ergonomic calls.
let begin_;
if (typeof begin === "number") {
begin_ = [begin, ...new Array($x.rank - 1).fill(0)];
} else if (begin.length < $x.rank) {
begin_ = begin.concat(new Array($x.rank - begin.length).fill(0));
} else {
begin_ = begin.slice();
}
begin_.forEach((d) => {
util["assert"](d !== -1, () => "slice() does not support negative begin indexing.");
});
let size_;
if (size == null) {
size_ = new Array($x.rank).fill(-1);
} else if (typeof size === "number") {
size_ = [size, ...new Array($x.rank - 1).fill(-1)];
} else if (size.length < $x.rank) {
size_ = size.concat(new Array($x.rank - size.length).fill(-1));
} else {
size_ = size;
}
size_ = size_.map((d, i) => {
if (d >= 0) {
return d;
} else {
util["assert"](
d === -1,
() =>
`Negative size values should be exactly -1 but got ` +
`${d} for the slice() size at index ${i}.`
);
return $x.shape[i] - begin_[i];
}
});
assertParamsValid($x, begin_, size_);
const inputShape = $x.shape;
const grad = (dy) => {
// Create an Nx2 padding where the first column represents how many
// zeros are prepended (at start) for each dimension, and the second
// column indicates how many zeros are appended (at end).
// The number of zeros to append is the shape of the input
// elementwise-subtracted by both the begin vector and sizes vector.
const paddings = [];
for (let i = 0; i < dy.rank; i++) {
paddings.push([begin_[i], inputShape[i] - begin_[i] - size_[i]]);
}
return { x: () => pad_pad(dy, paddings) };
};
const attrs = { begin: begin_, size: size_ };
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.slice($x, begin_, size_),
{ x: $x },
grad,
"Slice",
attrs
);
}
const slice = Object(operation["a" /* op */])({ slice_ });
const slice1d = Object(operation["a" /* op */])({ slice1d_ });
const slice2d = Object(operation["a" /* op */])({ slice2d_ });
const slice3d = Object(operation["a" /* op */])({ slice3d_ });
const slice4d = Object(operation["a" /* op */])({ slice4d_ });
//# sourceMappingURL=slice.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Tile_grad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const tileGradConfig = {
kernelName: kernel_names["rb" /* Tile */],
inputsToSave: ["x"],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { reps } = attrs;
const derX = () => {
let xGrad = Object(tensor_ops["o" /* zerosLike */])(x);
// TODO(cais): Maybe reduce memory footprint by avoiding repeated
// slicing.
if (x.rank === 1) {
for (let i = 0; i < reps[0]; ++i) {
xGrad = add(xGrad, slice(dy, [i * x.shape[0]], [x.shape[0]]));
}
} else if (x.rank === 2) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
xGrad = add(
xGrad,
slice(dy, [i * x.shape[0], j * x.shape[1]], [x.shape[0], x.shape[1]])
);
}
}
} else if (x.rank === 3) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
for (let k = 0; k < reps[2]; ++k) {
xGrad = add(
xGrad,
slice(
dy,
[i * x.shape[0], j * x.shape[1], k * x.shape[2]],
[x.shape[0], x.shape[1], x.shape[2]]
)
);
}
}
}
} else if (x.rank === 4) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
for (let k = 0; k < reps[2]; ++k) {
for (let l = 0; l < reps[3]; ++l) {
xGrad = add(
xGrad,
slice(
dy,
[i * x.shape[0], j * x.shape[1], k * x.shape[2], l * x.shape[3]],
[x.shape[0], x.shape[1], x.shape[2], x.shape[3]]
)
);
}
}
}
}
} else {
throw new Error(
`Gradient for tile operation is not implemented for rank-` +
`${x.rank} tensors yet.`
);
}
return xGrad;
};
return { x: derX };
},
};
//# sourceMappingURL=Tile_grad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/gradients/Transpose_grad.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const transposeGradConfig = {
kernelName: kernel_names["sb" /* Transpose */],
gradFunc: (dy, saved, attrs) => {
const transposeAttrs = attrs;
const { perm } = transposeAttrs;
const undoPerm = getUndoAxesPermutation(perm);
return { x: () => transpose(dy, undoPerm) };
},
};
//# sourceMappingURL=Transpose_grad.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/kernel_registry.js
var kernel_registry = __webpack_require__(17);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/register_all_gradients.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Export all kernel configs here so that the package can auto register them
const gradConfigs = [
addGradConfig,
addNGradConfig,
atan2GradConfig,
avgPoolGradConfig,
avgPool3DGradConfig,
batchMatMulGradConfig,
batchToSpaceNDGradConfig,
broadcastToGradConfig,
concatGradConfig,
conv2DGradConfig,
conv2DBackpropInputGradConfig,
conv3DGradConfig,
cumsumGradConfig,
depthwiseConv2dNativeGradConfig,
divGradConfig,
eluGradConfig,
floorDivGradConfig,
fusedBatchNormGradConfig,
greaterEqualGradConfig,
identityGradConfig,
lrnGradConfig,
oneHotGradConfig,
padV2GradConfig,
splitVGradConfig,
maxGradConfig,
spaceToBatchNDGradConfig,
maxGradConfig,
maximumGradConfig,
maxPoolGradConfig,
maxPool3DGradConfig,
minimumGradConfig,
modGradConfig,
multiplyGradConfig,
oneHotGradConfig,
padV2GradConfig,
powGradConfig,
preluGradConfig,
reluGradConfig,
relu6GradConfig,
seluGradConfig,
spaceToBatchNDGradConfig,
splitVGradConfig,
squareGradConfig,
squaredDifferenceGradConfig,
tileGradConfig,
transposeGradConfig,
subGradConfig,
];
for (const gradientConfig of gradConfigs) {
Object(kernel_registry["d" /* registerGradient */])(gradientConfig);
}
//# sourceMappingURL=register_all_gradients.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/environment.js
var environment = __webpack_require__(10);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/platforms/platform_browser.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.
* =============================================================================
*/
class PlatformBrowser {
fetch(path, init) {
return fetch(path, init);
}
now() {
return performance.now();
}
encode(text, encoding) {
if (encoding !== "utf-8" && encoding !== "utf8") {
throw new Error(`Browser's encoder only supports utf-8, but got ${encoding}`);
}
if (this.textEncoder == null) {
this.textEncoder = new TextEncoder();
}
return this.textEncoder.encode(text);
}
decode(bytes, encoding) {
return new TextDecoder(encoding).decode(bytes);
}
}
if (Object(environment["c" /* env */])().get("IS_BROWSER")) {
Object(environment["c" /* env */])().setPlatform("browser", new PlatformBrowser());
}
//# sourceMappingURL=platform_browser.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/platforms/platform_node.js
var platform_node = __webpack_require__(62);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/io_utils.js
var io_utils = __webpack_require__(13);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/router_registry.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class IORouterRegistry {
constructor() {
this.saveRouters = [];
this.loadRouters = [];
}
static getInstance() {
if (IORouterRegistry.instance == null) {
IORouterRegistry.instance = new IORouterRegistry();
}
return IORouterRegistry.instance;
}
/**
* Register a save-handler router.
*
* @param saveRouter A function that maps a URL-like string onto an instance
* of `IOHandler` with the `save` method defined or `null`.
*/
static registerSaveRouter(saveRouter) {
IORouterRegistry.getInstance().saveRouters.push(saveRouter);
}
/**
* Register a load-handler router.
*
* @param loadRouter A function that maps a URL-like string onto an instance
* of `IOHandler` with the `load` method defined or `null`.
*/
static registerLoadRouter(loadRouter) {
IORouterRegistry.getInstance().loadRouters.push(loadRouter);
}
/**
* Look up IOHandler for saving, given a URL-like string.
*
* @param url
* @returns If only one match is found, an instance of IOHandler with the
* `save` method defined. If no match is found, `null`.
* @throws Error, if more than one match is found.
*/
static getSaveHandlers(url) {
return IORouterRegistry.getHandlers(url, "save");
}
/**
* Look up IOHandler for loading, given a URL-like string.
*
* @param url
* @param loadOptions Optional, custom load options.
* @returns All valid handlers for `url`, given the currently registered
* handler routers.
*/
static getLoadHandlers(url, loadOptions) {
return IORouterRegistry.getHandlers(url, "load", loadOptions);
}
static getHandlers(url, handlerType, loadOptions) {
const validHandlers = [];
const routers =
handlerType === "load"
? IORouterRegistry.getInstance().loadRouters
: IORouterRegistry.getInstance().saveRouters;
routers.forEach((router) => {
const handler = router(url, loadOptions);
if (handler !== null) {
validHandlers.push(handler);
}
});
return validHandlers;
}
}
const registerSaveRouter = (loudRouter) => IORouterRegistry.registerSaveRouter(loudRouter);
const registerLoadRouter = (loudRouter) => IORouterRegistry.registerLoadRouter(loudRouter);
const getSaveHandlers = (url) => IORouterRegistry.getSaveHandlers(url);
const getLoadHandlers = (url, loadOptions) =>
IORouterRegistry.getLoadHandlers(url, loadOptions);
//# sourceMappingURL=router_registry.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/model_management.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Classes and functions for model management across multiple storage mediums.
*
* Supported client actions:
* - Listing models on all registered storage mediums.
* - Remove model by URL from any registered storage mediums, by using URL
* string.
* - Moving or copying model from one path to another in the same medium or from
* one medium to another, by using URL strings.
*/
const URL_SCHEME_SUFFIX = "://";
class model_management_ModelStoreManagerRegistry {
constructor() {
this.managers = {};
}
static getInstance() {
if (model_management_ModelStoreManagerRegistry.instance == null) {
model_management_ModelStoreManagerRegistry.instance =
new model_management_ModelStoreManagerRegistry();
}
return model_management_ModelStoreManagerRegistry.instance;
}
/**
* Register a save-handler router.
*
* @param saveRouter A function that maps a URL-like string onto an instance
* of `IOHandler` with the `save` method defined or `null`.
*/
static registerManager(scheme, manager) {
Object(util["assert"])(scheme != null, () => "scheme must not be undefined or null.");
if (scheme.endsWith(URL_SCHEME_SUFFIX)) {
scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));
}
Object(util["assert"])(scheme.length > 0, () => "scheme must not be an empty string.");
const registry = model_management_ModelStoreManagerRegistry.getInstance();
Object(util["assert"])(
registry.managers[scheme] == null,
() => `A model store manager is already registered for scheme '${scheme}'.`
);
registry.managers[scheme] = manager;
}
static getManager(scheme) {
const manager = this.getInstance().managers[scheme];
if (manager == null) {
throw new Error(`Cannot find model manager for scheme '${scheme}'`);
}
return manager;
}
static getSchemes() {
return Object.keys(this.getInstance().managers);
}
}
/**
* Helper method for parsing a URL string into a scheme and a path.
*
* @param url E.g., 'localstorage://my-model'
* @returns A dictionary with two fields: scheme and path.
* Scheme: e.g., 'localstorage' in the example above.
* Path: e.g., 'my-model' in the example above.
*/
function parseURL(url) {
if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {
throw new Error(
`The url string provided does not contain a scheme. ` +
`Supported schemes are: ` +
`${model_management_ModelStoreManagerRegistry.getSchemes().join(",")}`
);
}
return {
scheme: url.split(URL_SCHEME_SUFFIX)[0],
path: url.split(URL_SCHEME_SUFFIX)[1],
};
}
async function cloneModelInternal(sourceURL, destURL, deleteSource = false) {
Object(util["assert"])(
sourceURL !== destURL,
() => `Old path and new path are the same: '${sourceURL}'`
);
const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);
Object(util["assert"])(
loadHandlers.length > 0,
() => `Copying failed because no load handler is found for source URL ${sourceURL}.`
);
Object(util["assert"])(
loadHandlers.length < 2,
() =>
`Copying failed because more than one (${loadHandlers.length}) ` +
`load handlers for source URL ${sourceURL}.`
);
const loadHandler = loadHandlers[0];
const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);
Object(util["assert"])(
saveHandlers.length > 0,
() =>
`Copying failed because no save handler is found for destination ` + `URL ${destURL}.`
);
Object(util["assert"])(
saveHandlers.length < 2,
() =>
`Copying failed because more than one (${loadHandlers.length}) ` +
`save handlers for destination URL ${destURL}.`
);
const saveHandler = saveHandlers[0];
const sourceScheme = parseURL(sourceURL).scheme;
const sourcePath = parseURL(sourceURL).path;
const sameMedium = sourceScheme === parseURL(sourceURL).scheme;
const modelArtifacts = await loadHandler.load();
// If moving within the same storage medium, remove the old model as soon as
// the loading is done. Without doing this, it is possible that the combined
// size of the two models will cause the cloning to fail.
if (deleteSource && sameMedium) {
await model_management_ModelStoreManagerRegistry
.getManager(sourceScheme)
.removeModel(sourcePath);
}
const saveResult = await saveHandler.save(modelArtifacts);
// If moving between mediums, the deletion is done after the save succeeds.
// This guards against the case in which saving to the destination medium
// fails.
if (deleteSource && !sameMedium) {
await model_management_ModelStoreManagerRegistry
.getManager(sourceScheme)
.removeModel(sourcePath);
}
return saveResult.modelArtifactsInfo;
}
/**
* List all models stored in registered storage mediums.
*
* For a web browser environment, the registered mediums are Local Storage and
* IndexedDB.
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Delete the model.
* await tf.io.removeModel('localstorage://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
* ```
*
* @returns A `Promise` of a dictionary mapping URLs of existing models to
* their model artifacts info. URLs include medium-specific schemes, e.g.,
* 'indexeddb://my/model/1'. Model artifacts info include type of the
* model's topology, byte sizes of the topology, weights, etc.
*/
/**
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
async function listModels() {
const schemes = model_management_ModelStoreManagerRegistry.getSchemes();
const out = {};
for (const scheme of schemes) {
const schemeOut = await model_management_ModelStoreManagerRegistry
.getManager(scheme)
.listModels();
for (const path in schemeOut) {
const url = scheme + URL_SCHEME_SUFFIX + path;
out[url] = schemeOut[path];
}
}
return out;
}
/**
* Remove a model specified by URL from a reigstered storage medium.
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Delete the model.
* await tf.io.removeModel('localstorage://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
* ```
*
* @param url A URL to a stored model, with a scheme prefix, e.g.,
* 'localstorage://my-model-1', 'indexeddb://my/model/2'.
* @returns ModelArtifactsInfo of the deleted model (if and only if deletion
* is successful).
* @throws Error if deletion fails, e.g., if no model exists at `path`.
*/
/**
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
async function removeModel(url) {
const schemeAndPath = parseURL(url);
const manager = model_management_ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);
return manager.removeModel(schemeAndPath.path);
}
/**
* Copy a model from one URL to another.
*
* This function supports:
*
* 1. Copying within a storage medium, e.g.,
* `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`
* 2. Copying between two storage mediums, e.g.,
* `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Copy the model, from Local Storage to IndexedDB.
* await tf.io.copyModel(
* 'localstorage://demo/management/model1',
* 'indexeddb://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Remove both models.
* await tf.io.removeModel('localstorage://demo/management/model1');
* await tf.io.removeModel('indexeddb://demo/management/model1');
* ```
*
* @param sourceURL Source URL of copying.
* @param destURL Destination URL of copying.
* @returns ModelArtifactsInfo of the copied model (if and only if copying
* is successful).
* @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or
* if `oldPath` and `newPath` are identical.
*/
/**
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
async function copyModel(sourceURL, destURL) {
const deleteSource = false;
return cloneModelInternal(sourceURL, destURL, deleteSource);
}
/**
* Move a model from one URL to another.
*
* This function supports:
*
* 1. Moving within a storage medium, e.g.,
* `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`
* 2. Moving between two storage mediums, e.g.,
* `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Move the model, from Local Storage to IndexedDB.
* await tf.io.moveModel(
* 'localstorage://demo/management/model1',
* 'indexeddb://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Remove the moved model.
* await tf.io.removeModel('indexeddb://demo/management/model1');
* ```
*
* @param sourceURL Source URL of moving.
* @param destURL Destination URL of moving.
* @returns ModelArtifactsInfo of the copied model (if and only if copying
* is successful).
* @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or
* if `oldPath` and `newPath` are identical.
*/
/**
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
async function moveModel(sourceURL, destURL) {
const deleteSource = true;
return cloneModelInternal(sourceURL, destURL, deleteSource);
}
//# sourceMappingURL=model_management.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/indexed_db.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const DATABASE_NAME = "tensorflowjs";
const DATABASE_VERSION = 1;
// Model data and ModelArtifactsInfo (metadata) are stored in two separate
// stores for efficient access of the list of stored models and their metadata.
// 1. The object store for model data: topology, weights and weight manifests.
const MODEL_STORE_NAME = "models_store";
// 2. The object store for ModelArtifactsInfo, including meta-information such
// as the type of topology (JSON vs binary), byte size of the topology, byte
// size of the weights, etc.
const INFO_STORE_NAME = "model_info_store";
/**
* Delete the entire database for tensorflow.js, including the models store.
*/
async function deleteDatabase() {
const idbFactory = getIndexedDBFactory();
return new Promise((resolve, reject) => {
const deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);
deleteRequest.onsuccess = () => resolve();
deleteRequest.onerror = (error) => reject(error);
});
}
function getIndexedDBFactory() {
if (!Object(environment["c" /* env */])().getBool("IS_BROWSER")) {
// TODO(cais): Add more info about what IOHandler subtypes are available.
// Maybe point to a doc page on the web and/or automatically determine
// the available IOHandlers and print them in the error message.
throw new Error(
"Failed to obtain IndexedDB factory because the current environment" +
"is not a web browser."
);
}
// tslint:disable-next-line:no-any
const theWindow = typeof window === "undefined" ? self : window;
const factory =
theWindow.indexedDB ||
theWindow.mozIndexedDB ||
theWindow.webkitIndexedDB ||
theWindow.msIndexedDB ||
theWindow.shimIndexedDB;
if (factory == null) {
throw new Error("The current browser does not appear to support IndexedDB.");
}
return factory;
}
function setUpDatabase(openRequest) {
const db = openRequest.result;
db.createObjectStore(MODEL_STORE_NAME, { keyPath: "modelPath" });
db.createObjectStore(INFO_STORE_NAME, { keyPath: "modelPath" });
}
/**
* IOHandler subclass: Browser IndexedDB.
*
* See the doc string of `browserIndexedDB` for more details.
*/
class indexed_db_BrowserIndexedDB {
constructor(modelPath) {
this.indexedDB = getIndexedDBFactory();
if (modelPath == null || !modelPath) {
throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");
}
this.modelPath = modelPath;
}
async save(modelArtifacts) {
// TODO(cais): Support saving GraphDef models.
if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
throw new Error(
"BrowserLocalStorage.save() does not support saving model topology " +
"in binary formats yet."
);
}
return this.databaseAction(this.modelPath, modelArtifacts);
}
async load() {
return this.databaseAction(this.modelPath);
}
/**
* Perform database action to put model artifacts into or read model artifacts
* from IndexedDB object store.
*
* Whether the action is put or get depends on whether `modelArtifacts` is
* specified. If it is specified, the action will be put; otherwise the action
* will be get.
*
* @param modelPath A unique string path for the model.
* @param modelArtifacts If specified, it will be the model artifacts to be
* stored in IndexedDB.
* @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`
* of `ModelArtifacts`, if the action is get.
*/
databaseAction(modelPath, modelArtifacts) {
return new Promise((resolve, reject) => {
const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
openRequest.onupgradeneeded = () => setUpDatabase(openRequest);
openRequest.onsuccess = () => {
const db = openRequest.result;
if (modelArtifacts == null) {
// Read model out from object store.
const modelTx = db.transaction(MODEL_STORE_NAME, "readonly");
const modelStore = modelTx.objectStore(MODEL_STORE_NAME);
const getRequest = modelStore.get(this.modelPath);
getRequest.onsuccess = () => {
if (getRequest.result == null) {
db.close();
return reject(
new Error(
`Cannot find model with path '${this.modelPath}' ` + `in IndexedDB.`
)
);
} else {
resolve(getRequest.result.modelArtifacts);
}
};
getRequest.onerror = (error) => {
db.close();
return reject(getRequest.error);
};
modelTx.oncomplete = () => db.close();
} else {
// Put model into object store.
const modelArtifactsInfo = Object(io_utils["g" /* getModelArtifactsInfoForJSON */])(
modelArtifacts
);
// First, put ModelArtifactsInfo into info store.
const infoTx = db.transaction(INFO_STORE_NAME, "readwrite");
let infoStore = infoTx.objectStore(INFO_STORE_NAME);
const putInfoRequest = infoStore.put({
modelPath: this.modelPath,
modelArtifactsInfo,
});
let modelTx;
putInfoRequest.onsuccess = () => {
// Second, put model data into model store.
modelTx = db.transaction(MODEL_STORE_NAME, "readwrite");
const modelStore = modelTx.objectStore(MODEL_STORE_NAME);
const putModelRequest = modelStore.put({
modelPath: this.modelPath,
modelArtifacts,
modelArtifactsInfo,
});
putModelRequest.onsuccess = () => resolve({ modelArtifactsInfo });
putModelRequest.onerror = (error) => {
// If the put-model request fails, roll back the info entry as
// well.
infoStore = infoTx.objectStore(INFO_STORE_NAME);
const deleteInfoRequest = infoStore.delete(this.modelPath);
deleteInfoRequest.onsuccess = () => {
db.close();
return reject(putModelRequest.error);
};
deleteInfoRequest.onerror = (error) => {
db.close();
return reject(putModelRequest.error);
};
};
};
putInfoRequest.onerror = (error) => {
db.close();
return reject(putInfoRequest.error);
};
infoTx.oncomplete = () => {
if (modelTx == null) {
db.close();
} else {
modelTx.oncomplete = () => db.close();
}
};
}
};
openRequest.onerror = (error) => reject(openRequest.error);
});
}
}
indexed_db_BrowserIndexedDB.URL_SCHEME = "indexeddb://";
const indexedDBRouter = (url) => {
if (!Object(environment["c" /* env */])().getBool("IS_BROWSER")) {
return null;
} else {
if (!Array.isArray(url) && url.startsWith(indexed_db_BrowserIndexedDB.URL_SCHEME)) {
return browserIndexedDB(url.slice(indexed_db_BrowserIndexedDB.URL_SCHEME.length));
} else {
return null;
}
}
};
IORouterRegistry.registerSaveRouter(indexedDBRouter);
IORouterRegistry.registerLoadRouter(indexedDBRouter);
/**
* Creates a browser IndexedDB IOHandler for saving and loading models.
*
* ```js
* const model = tf.sequential();
* model.add(
* tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));
*
* const saveResult = await model.save('indexeddb://MyModel'));
* console.log(saveResult);
* ```
*
* @param modelPath A unique identifier for the model to be saved. Must be a
* non-empty string.
* @returns An instance of `BrowserIndexedDB` (sublcass of `IOHandler`),
* which can be used with, e.g., `tf.Model.save`.
*/
function browserIndexedDB(modelPath) {
return new indexed_db_BrowserIndexedDB(modelPath);
}
function maybeStripScheme(key) {
return key.startsWith(indexed_db_BrowserIndexedDB.URL_SCHEME)
? key.slice(indexed_db_BrowserIndexedDB.URL_SCHEME.length)
: key;
}
class BrowserIndexedDBManager {
constructor() {
this.indexedDB = getIndexedDBFactory();
}
async listModels() {
return new Promise((resolve, reject) => {
const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
openRequest.onupgradeneeded = () => setUpDatabase(openRequest);
openRequest.onsuccess = () => {
const db = openRequest.result;
const tx = db.transaction(INFO_STORE_NAME, "readonly");
const store = tx.objectStore(INFO_STORE_NAME);
// tslint:disable:max-line-length
// Need to cast `store` as `any` here because TypeScript's DOM
// library does not have the `getAll()` method even though the
// method is supported in the latest version of most mainstream
// browsers:
// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll
// tslint:enable:max-line-length
// tslint:disable-next-line:no-any
const getAllInfoRequest = store.getAll();
getAllInfoRequest.onsuccess = () => {
const out = {};
for (const item of getAllInfoRequest.result) {
out[item.modelPath] = item.modelArtifactsInfo;
}
resolve(out);
};
getAllInfoRequest.onerror = (error) => {
db.close();
return reject(getAllInfoRequest.error);
};
tx.oncomplete = () => db.close();
};
openRequest.onerror = (error) => reject(openRequest.error);
});
}
async removeModel(path) {
path = maybeStripScheme(path);
return new Promise((resolve, reject) => {
const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
openRequest.onupgradeneeded = () => setUpDatabase(openRequest);
openRequest.onsuccess = () => {
const db = openRequest.result;
const infoTx = db.transaction(INFO_STORE_NAME, "readwrite");
const infoStore = infoTx.objectStore(INFO_STORE_NAME);
const getInfoRequest = infoStore.get(path);
let modelTx;
getInfoRequest.onsuccess = () => {
if (getInfoRequest.result == null) {
db.close();
return reject(
new Error(`Cannot find model with path '${path}' ` + `in IndexedDB.`)
);
} else {
// First, delete the entry in the info store.
const deleteInfoRequest = infoStore.delete(path);
const deleteModelData = () => {
// Second, delete the entry in the model store.
modelTx = db.transaction(MODEL_STORE_NAME, "readwrite");
const modelStore = modelTx.objectStore(MODEL_STORE_NAME);
const deleteModelRequest = modelStore.delete(path);
deleteModelRequest.onsuccess = () =>
resolve(getInfoRequest.result.modelArtifactsInfo);
deleteModelRequest.onerror = (error) => reject(getInfoRequest.error);
};
// Proceed with deleting model data regardless of whether deletion
// of info data succeeds or not.
deleteInfoRequest.onsuccess = deleteModelData;
deleteInfoRequest.onerror = (error) => {
deleteModelData();
db.close();
return reject(getInfoRequest.error);
};
}
};
getInfoRequest.onerror = (error) => {
db.close();
return reject(getInfoRequest.error);
};
infoTx.oncomplete = () => {
if (modelTx == null) {
db.close();
} else {
modelTx.oncomplete = () => db.close();
}
};
};
openRequest.onerror = (error) => reject(openRequest.error);
});
}
}
if (Object(environment["c" /* env */])().getBool("IS_BROWSER")) {
// Wrap the construction and registration, to guard against browsers that
// don't support Local Storage.
try {
model_management_ModelStoreManagerRegistry.registerManager(
indexed_db_BrowserIndexedDB.URL_SCHEME,
new BrowserIndexedDBManager()
);
} catch (err) {}
}
//# sourceMappingURL=indexed_db.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/local_storage.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const PATH_SEPARATOR = "/";
const PATH_PREFIX = "tensorflowjs_models";
const INFO_SUFFIX = "info";
const MODEL_TOPOLOGY_SUFFIX = "model_topology";
const WEIGHT_SPECS_SUFFIX = "weight_specs";
const WEIGHT_DATA_SUFFIX = "weight_data";
const MODEL_METADATA_SUFFIX = "model_metadata";
/**
* Purge all tensorflow.js-saved model artifacts from local storage.
*
* @returns Paths of the models purged.
*/
function purgeLocalStorageArtifacts() {
if (
!Object(environment["c" /* env */])().getBool("IS_BROWSER") ||
typeof window === "undefined" ||
typeof window.localStorage === "undefined"
) {
throw new Error(
"purgeLocalStorageModels() cannot proceed because local storage is " +
"unavailable in the current environment."
);
}
const LS = window.localStorage;
const purgedModelPaths = [];
for (let i = 0; i < LS.length; ++i) {
const key = LS.key(i);
const prefix = PATH_PREFIX + PATH_SEPARATOR;
if (key.startsWith(prefix) && key.length > prefix.length) {
LS.removeItem(key);
const modelName = getModelPathFromKey(key);
if (purgedModelPaths.indexOf(modelName) === -1) {
purgedModelPaths.push(modelName);
}
}
}
return purgedModelPaths;
}
function getModelKeys(path) {
return {
info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),
topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),
weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),
weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),
modelMetadata: [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR),
};
}
/**
* Get model path from a local-storage key.
*
* E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'
*
* @param key
*/
function getModelPathFromKey(key) {
const items = key.split(PATH_SEPARATOR);
if (items.length < 3) {
throw new Error(`Invalid key format: ${key}`);
}
return items.slice(1, items.length - 1).join(PATH_SEPARATOR);
}
function local_storage_maybeStripScheme(key) {
return key.startsWith(local_storage_BrowserLocalStorage.URL_SCHEME)
? key.slice(local_storage_BrowserLocalStorage.URL_SCHEME.length)
: key;
}
/**
* IOHandler subclass: Browser Local Storage.
*
* See the doc string to `browserLocalStorage` for more details.
*/
class local_storage_BrowserLocalStorage {
constructor(modelPath) {
if (
!Object(environment["c" /* env */])().getBool("IS_BROWSER") ||
typeof window === "undefined" ||
typeof window.localStorage === "undefined"
) {
// TODO(cais): Add more info about what IOHandler subtypes are
// available.
// Maybe point to a doc page on the web and/or automatically determine
// the available IOHandlers and print them in the error message.
throw new Error("The current environment does not support local storage.");
}
this.LS = window.localStorage;
if (modelPath == null || !modelPath) {
throw new Error("For local storage, modelPath must not be null, undefined or empty.");
}
this.modelPath = modelPath;
this.keys = getModelKeys(this.modelPath);
}
/**
* Save model artifacts to browser local storage.
*
* See the documentation to `browserLocalStorage` for details on the saved
* artifacts.
*
* @param modelArtifacts The model artifacts to be stored.
* @returns An instance of SaveResult.
*/
async save(modelArtifacts) {
if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
throw new Error(
"BrowserLocalStorage.save() does not support saving model topology " +
"in binary formats yet."
);
} else {
const topology = JSON.stringify(modelArtifacts.modelTopology);
const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);
const modelArtifactsInfo = Object(io_utils["g" /* getModelArtifactsInfoForJSON */])(
modelArtifacts
);
try {
this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));
this.LS.setItem(this.keys.topology, topology);
this.LS.setItem(this.keys.weightSpecs, weightSpecs);
this.LS.setItem(
this.keys.weightData,
Object(io_utils["a" /* arrayBufferToBase64String */])(modelArtifacts.weightData)
);
this.LS.setItem(
this.keys.modelMetadata,
JSON.stringify({
format: modelArtifacts.format,
generatedBy: modelArtifacts.generatedBy,
convertedBy: modelArtifacts.convertedBy,
userDefinedMetadata: modelArtifacts.userDefinedMetadata,
})
);
return { modelArtifactsInfo };
} catch (err) {
// If saving failed, clean up all items saved so far.
this.LS.removeItem(this.keys.info);
this.LS.removeItem(this.keys.topology);
this.LS.removeItem(this.keys.weightSpecs);
this.LS.removeItem(this.keys.weightData);
this.LS.removeItem(this.keys.modelMetadata);
throw new Error(
`Failed to save model '${this.modelPath}' to local storage: ` +
`size quota being exceeded is a possible cause of this failure: ` +
`modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +
`weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +
`weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`
);
}
}
}
/**
* Load a model from local storage.
*
* See the documentation to `browserLocalStorage` for details on the saved
* artifacts.
*
* @returns The loaded model (if loading succeeds).
*/
async load() {
const info = JSON.parse(this.LS.getItem(this.keys.info));
if (info == null) {
throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);
}
if (info.modelTopologyType !== "JSON") {
throw new Error(
"BrowserLocalStorage does not support loading non-JSON model " + "topology yet."
);
}
const out = {};
// Load topology.
const topology = JSON.parse(this.LS.getItem(this.keys.topology));
if (topology == null) {
throw new Error(
`In local storage, the topology of model '${this.modelPath}' ` + `is missing.`
);
}
out.modelTopology = topology;
// Load weight specs.
const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
if (weightSpecs == null) {
throw new Error(
`In local storage, the weight specs of model '${this.modelPath}' ` + `are missing.`
);
}
out.weightSpecs = weightSpecs;
// Load meta-data fields.
const metadataString = this.LS.getItem(this.keys.modelMetadata);
if (metadataString != null) {
const metadata = JSON.parse(metadataString);
out.format = metadata["format"];
out.generatedBy = metadata["generatedBy"];
out.convertedBy = metadata["convertedBy"];
out.userDefinedMetadata = metadata["userDefinedMetadata"];
}
// Load weight data.
const weightDataBase64 = this.LS.getItem(this.keys.weightData);
if (weightDataBase64 == null) {
throw new Error(
`In local storage, the binary weight values of model ` +
`'${this.modelPath}' are missing.`
);
}
out.weightData = Object(io_utils["b" /* base64StringToArrayBuffer */])(weightDataBase64);
return out;
}
}
local_storage_BrowserLocalStorage.URL_SCHEME = "localstorage://";
const localStorageRouter = (url) => {
if (!Object(environment["c" /* env */])().getBool("IS_BROWSER")) {
return null;
} else {
if (!Array.isArray(url) && url.startsWith(local_storage_BrowserLocalStorage.URL_SCHEME)) {
return browserLocalStorage(
url.slice(local_storage_BrowserLocalStorage.URL_SCHEME.length)
);
} else {
return null;
}
}
};
IORouterRegistry.registerSaveRouter(localStorageRouter);
IORouterRegistry.registerLoadRouter(localStorageRouter);
/**
* Factory function for local storage IOHandler.
*
* This `IOHandler` supports both `save` and `load`.
*
* For each model's saved artifacts, four items are saved to local storage.
* - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the
* model, such as date saved, type of the topology, size in bytes, etc.
* - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-
* style models, this is a stringized JSON.
* - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the
* model, can be used to decode the saved binary weight values (see
* item below).
* - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary
* weight values, stored as a base64-encoded string.
*
* Saving may throw an `Error` if the total size of the artifacts exceed the
* browser-specific quota.
*
* @param modelPath A unique identifier for the model to be saved. Must be a
* non-empty string.
* @returns An instance of `IOHandler`, which can be used with, e.g.,
* `tf.Model.save`.
*/
function browserLocalStorage(modelPath) {
return new local_storage_BrowserLocalStorage(modelPath);
}
class local_storage_BrowserLocalStorageManager {
constructor() {
Object(util["assert"])(
Object(environment["c" /* env */])().getBool("IS_BROWSER"),
() => "Current environment is not a web browser"
);
Object(util["assert"])(
typeof window === "undefined" || typeof window.localStorage !== "undefined",
() => "Current browser does not appear to support localStorage"
);
this.LS = window.localStorage;
}
async listModels() {
const out = {};
const prefix = PATH_PREFIX + PATH_SEPARATOR;
const suffix = PATH_SEPARATOR + INFO_SUFFIX;
for (let i = 0; i < this.LS.length; ++i) {
const key = this.LS.key(i);
if (key.startsWith(prefix) && key.endsWith(suffix)) {
const modelPath = getModelPathFromKey(key);
out[modelPath] = JSON.parse(this.LS.getItem(key));
}
}
return out;
}
async removeModel(path) {
path = local_storage_maybeStripScheme(path);
const keys = getModelKeys(path);
if (this.LS.getItem(keys.info) == null) {
throw new Error(`Cannot find model at path '${path}'`);
}
const info = JSON.parse(this.LS.getItem(keys.info));
this.LS.removeItem(keys.info);
this.LS.removeItem(keys.topology);
this.LS.removeItem(keys.weightSpecs);
this.LS.removeItem(keys.weightData);
return info;
}
}
if (Object(environment["c" /* env */])().getBool("IS_BROWSER")) {
// Wrap the construction and registration, to guard against browsers that
// don't support Local Storage.
try {
model_management_ModelStoreManagerRegistry.registerManager(
local_storage_BrowserLocalStorage.URL_SCHEME,
new local_storage_BrowserLocalStorageManager()
);
} catch (err) {}
}
//# sourceMappingURL=local_storage.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/browser_files.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* IOHandlers related to files, such as browser-triggered file downloads,
* user-selected files in browser.
*/
const DEFAULT_FILE_NAME_PREFIX = "model";
const DEFAULT_JSON_EXTENSION_NAME = ".json";
const DEFAULT_WEIGHT_DATA_EXTENSION_NAME = ".weights.bin";
function defer(f) {
return new Promise((resolve) => setTimeout(resolve)).then(f);
}
class browser_files_BrowserDownloads {
constructor(fileNamePrefix) {
if (!Object(environment["c" /* env */])().getBool("IS_BROWSER")) {
// TODO(cais): Provide info on what IOHandlers are available under the
// current environment.
throw new Error(
"browserDownloads() cannot proceed because the current environment " +
"is not a browser."
);
}
if (fileNamePrefix.startsWith(browser_files_BrowserDownloads.URL_SCHEME)) {
fileNamePrefix = fileNamePrefix.slice(browser_files_BrowserDownloads.URL_SCHEME.length);
}
if (fileNamePrefix == null || fileNamePrefix.length === 0) {
fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;
}
this.modelTopologyFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;
this.weightDataFileName = fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;
}
async save(modelArtifacts) {
if (typeof document === "undefined") {
throw new Error(
"Browser downloads are not supported in " +
"this environment since `document` is not present"
);
}
const weightsURL = window.URL.createObjectURL(
new Blob([modelArtifacts.weightData], { type: "application/octet-stream" })
);
if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
throw new Error(
"BrowserDownloads.save() does not support saving model topology " +
"in binary formats yet."
);
} else {
const weightsManifest = [
{
paths: ["./" + this.weightDataFileName],
weights: modelArtifacts.weightSpecs,
},
];
const modelTopologyAndWeightManifest = {
modelTopology: modelArtifacts.modelTopology,
format: modelArtifacts.format,
generatedBy: modelArtifacts.generatedBy,
convertedBy: modelArtifacts.convertedBy,
weightsManifest,
};
const modelTopologyAndWeightManifestURL = window.URL.createObjectURL(
new Blob([JSON.stringify(modelTopologyAndWeightManifest)], {
type: "application/json",
})
);
// If anchor elements are not provided, create them without attaching them
// to parents, so that the downloaded file names can be controlled.
const jsonAnchor =
this.jsonAnchor == null ? document.createElement("a") : this.jsonAnchor;
jsonAnchor.download = this.modelTopologyFileName;
jsonAnchor.href = modelTopologyAndWeightManifestURL;
// Trigger downloads by evoking a click event on the download anchors.
// When multiple downloads are started synchronously, Firefox will only
// save the last one.
await defer(() => jsonAnchor.dispatchEvent(new MouseEvent("click")));
if (modelArtifacts.weightData != null) {
const weightDataAnchor =
this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor;
weightDataAnchor.download = this.weightDataFileName;
weightDataAnchor.href = weightsURL;
await defer(() => weightDataAnchor.dispatchEvent(new MouseEvent("click")));
}
return {
modelArtifactsInfo: Object(io_utils["g" /* getModelArtifactsInfoForJSON */])(
modelArtifacts
),
};
}
}
}
browser_files_BrowserDownloads.URL_SCHEME = "downloads://";
class browser_files_BrowserFiles {
constructor(files) {
if (files == null || files.length < 1) {
throw new Error(
`When calling browserFiles, at least 1 file is required, ` + `but received ${files}`
);
}
this.files = files;
}
async load() {
const jsonFile = this.files[0];
const weightFiles = this.files.slice(1);
return new Promise((resolve, reject) => {
const jsonReader = new FileReader();
jsonReader.onload = (event) => {
// tslint:disable-next-line:no-any
const modelJSON = JSON.parse(event.target.result);
const modelTopology = modelJSON.modelTopology;
if (modelTopology == null) {
reject(new Error(`modelTopology field is missing from file ${jsonFile.name}`));
return;
}
if (weightFiles.length === 0) {
resolve({ modelTopology });
}
const weightsManifest = modelJSON.weightsManifest;
if (weightsManifest == null) {
reject(new Error(`weightManifest field is missing from file ${jsonFile.name}`));
return;
}
let pathToFile;
try {
pathToFile = this.checkManifestAndWeightFiles(weightsManifest, weightFiles);
} catch (err) {
reject(err);
return;
}
const weightSpecs = [];
const paths = [];
const perFileBuffers = [];
weightsManifest.forEach((weightsGroup) => {
weightsGroup.paths.forEach((path) => {
paths.push(path);
perFileBuffers.push(null);
});
weightSpecs.push(...weightsGroup.weights);
});
weightsManifest.forEach((weightsGroup) => {
weightsGroup.paths.forEach((path) => {
const weightFileReader = new FileReader();
weightFileReader.onload = (event) => {
// tslint:disable-next-line:no-any
const weightData = event.target.result;
const index = paths.indexOf(path);
perFileBuffers[index] = weightData;
if (perFileBuffers.indexOf(null) === -1) {
resolve({
modelTopology,
weightSpecs,
weightData: Object(io_utils["d" /* concatenateArrayBuffers */])(
perFileBuffers
),
format: modelJSON.format,
generatedBy: modelJSON.generatedBy,
convertedBy: modelJSON.convertedBy,
userDefinedMetadata: modelJSON.userDefinedMetadata,
});
}
};
weightFileReader.onerror = (error) =>
reject(`Failed to weights data from file of path '${path}'.`);
weightFileReader.readAsArrayBuffer(pathToFile[path]);
});
});
};
jsonReader.onerror = (error) =>
reject(
`Failed to read model topology and weights manifest JSON ` +
`from file '${jsonFile.name}'. BrowserFiles supports loading ` +
`Keras-style tf.Model artifacts only.`
);
jsonReader.readAsText(jsonFile);
});
}
/**
* Check the compatibility between weights manifest and weight files.
*/
checkManifestAndWeightFiles(manifest, files) {
const basenames = [];
const fileNames = files.map((file) => Object(io_utils["c" /* basename */])(file.name));
const pathToFile = {};
for (const group of manifest) {
group.paths.forEach((path) => {
const pathBasename = Object(io_utils["c" /* basename */])(path);
if (basenames.indexOf(pathBasename) !== -1) {
throw new Error(
`Duplicate file basename found in weights manifest: ` + `'${pathBasename}'`
);
}
basenames.push(pathBasename);
if (fileNames.indexOf(pathBasename) === -1) {
throw new Error(`Weight file with basename '${pathBasename}' is not provided.`);
} else {
pathToFile[path] = files[fileNames.indexOf(pathBasename)];
}
});
}
if (basenames.length !== files.length) {
throw new Error(
`Mismatch in the number of files in weights manifest ` +
`(${basenames.length}) and the number of weight files provided ` +
`(${files.length}).`
);
}
return pathToFile;
}
}
const browserDownloadsRouter = (url) => {
if (!Object(environment["c" /* env */])().getBool("IS_BROWSER")) {
return null;
} else {
if (!Array.isArray(url) && url.startsWith(browser_files_BrowserDownloads.URL_SCHEME)) {
return browserDownloads(url.slice(browser_files_BrowserDownloads.URL_SCHEME.length));
} else {
return null;
}
}
};
IORouterRegistry.registerSaveRouter(browserDownloadsRouter);
/**
* Creates an IOHandler that triggers file downloads from the browser.
*
* The returned `IOHandler` instance can be used as model exporting methods such
* as `tf.Model.save` and supports only saving.
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* const saveResult = await model.save('downloads://mymodel');
* // This will trigger downloading of two files:
* // 'mymodel.json' and 'mymodel.weights.bin'.
* console.log(saveResult);
* ```
*
* @param fileNamePrefix Prefix name of the files to be downloaded. For use with
* `tf.Model`, `fileNamePrefix` should follow either of the following two
* formats:
* 1. `null` or `undefined`, in which case the default file
* names will be used:
* - 'model.json' for the JSON file containing the model topology and
* weights manifest.
* - 'model.weights.bin' for the binary file containing the binary weight
* values.
* 2. A single string or an Array of a single string, as the file name prefix.
* For example, if `'foo'` is provided, the downloaded JSON
* file and binary weights file will be named 'foo.json' and
* 'foo.weights.bin', respectively.
* @param config Additional configuration for triggering downloads.
* @returns An instance of `BrowserDownloads` `IOHandler`.
*/
/**
* @doc {
* heading: 'Models',
* subheading: 'Loading',
* namespace: 'io',
* ignoreCI: true
* }
*/
function browserDownloads(fileNamePrefix = "model") {
return new browser_files_BrowserDownloads(fileNamePrefix);
}
/**
* Creates an IOHandler that loads model artifacts from user-selected files.
*
* This method can be used for loading from files such as user-selected files
* in the browser.
* When used in conjunction with `tf.loadLayersModel`, an instance of
* `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.
*
* ```js
* // Note: This code snippet won't run properly without the actual file input
* // elements in the HTML DOM.
*
* // Suppose there are two HTML file input (`<input type="file" ...>`)
* // elements.
* const uploadJSONInput = document.getElementById('upload-json');
* const uploadWeightsInput = document.getElementById('upload-weights');
* const model = await tf.loadLayersModel(tf.io.browserFiles(
* [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));
* ```
*
* @param files `File`s to load from. Currently, this function supports only
* loading from files that contain Keras-style models (i.e., `tf.Model`s), for
* which an `Array` of `File`s is expected (in that order):
* - A JSON file containing the model topology and weight manifest.
* - Optionally, One or more binary files containing the binary weights.
* These files must have names that match the paths in the `weightsManifest`
* contained by the aforementioned JSON file, or errors will be thrown
* during loading. These weights files have the same format as the ones
* generated by `tensorflowjs_converter` that comes with the `tensorflowjs`
* Python PIP package. If no weights files are provided, only the model
* topology will be loaded from the JSON file above.
* @returns An instance of `Files` `IOHandler`.
*/
/**
* @doc {
* heading: 'Models',
* subheading: 'Loading',
* namespace: 'io',
* ignoreCI: true
* }
*/
function browserFiles(files) {
return new browser_files_BrowserFiles(files);
}
//# sourceMappingURL=browser_files.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/progress.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Monitor Promise.all progress, fire onProgress callback function.
*
* @param promises Promise list going to be monitored
* @param onProgress Callback function. Fired when a promise resolved.
* @param startFraction Optional fraction start. Default to 0.
* @param endFraction Optional fraction end. Default to 1.
*/
function monitorPromisesProgress(promises, onProgress, startFraction, endFraction) {
checkPromises(promises);
startFraction = startFraction == null ? 0 : startFraction;
endFraction = endFraction == null ? 1 : endFraction;
checkFraction(startFraction, endFraction);
let resolvedPromise = 0;
const registerMonitor = (promise) => {
promise.then((value) => {
const fraction =
startFraction + (++resolvedPromise / promises.length) * (endFraction - startFraction);
// pass fraction as parameter to callback function.
onProgress(fraction);
return value;
});
return promise;
};
function checkPromises(promises) {
Object(util["assert"])(
promises != null && Array.isArray(promises) && promises.length > 0,
() => "promises must be a none empty array"
);
}
function checkFraction(startFraction, endFraction) {
Object(util["assert"])(
startFraction >= 0 && startFraction <= 1,
() =>
`Progress fraction must be in range [0, 1], but ` +
`got startFraction ${startFraction}`
);
Object(util["assert"])(
endFraction >= 0 && endFraction <= 1,
() =>
`Progress fraction must be in range [0, 1], but ` + `got endFraction ${endFraction}`
);
Object(util["assert"])(
endFraction >= startFraction,
() =>
`startFraction must be no more than endFraction, but ` +
`got startFraction ${startFraction} and endFraction ` +
`${endFraction}`
);
}
return Promise.all(promises.map(registerMonitor));
}
//# sourceMappingURL=progress.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/types.js
var types = __webpack_require__(34);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/weights_loader.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reads binary weights data from a number of URLs.
*
* @param fetchURLs URLs to send the HTTP requests at, using `fetch` calls.
* @param requestOptions RequestInit (options) for the HTTP requests.
* @param fetchFunc Optional overriding value for the `window.fetch` function.
* @param onProgress Optional, progress callback function, fired periodically
* before the load is completed.
* @returns A `Promise` of an Array of `ArrayBuffer`. The Array has the same
* length as `fetchURLs`.
*/
async function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) {
if (loadOptions == null) {
loadOptions = {};
}
const fetchFunc =
loadOptions.fetchFunc == null
? Object(environment["c" /* env */])().platform.fetch
: loadOptions.fetchFunc;
// Create the requests for all of the weights in parallel.
const requests = fetchURLs.map((fetchURL) =>
fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true })
);
const fetchStartFraction = 0;
const fetchEndFraction = 0.5;
const responses =
loadOptions.onProgress == null
? await Promise.all(requests)
: await monitorPromisesProgress(
requests,
loadOptions.onProgress,
fetchStartFraction,
fetchEndFraction
);
const bufferPromises = responses.map((response) => response.arrayBuffer());
const bufferStartFraction = 0.5;
const bufferEndFraction = 1;
const buffers =
loadOptions.onProgress == null
? await Promise.all(bufferPromises)
: await monitorPromisesProgress(
bufferPromises,
loadOptions.onProgress,
bufferStartFraction,
bufferEndFraction
);
return buffers;
}
/**
* Reads a weights manifest JSON configuration, fetches the weights and
* returns them as `Tensor`s.
*
* @param manifest The weights manifest JSON.
* @param filePathPrefix The path prefix for filenames given in the manifest.
* Defaults to the empty string.
* @param weightNames The names of the weights to be fetched.
*/
async function loadWeights(manifest, filePathPrefix = "", weightNames, requestInit) {
// TODO(nsthorat): Groups are currently fetched atomically. If you need a
// single weight from a group, the whole group will be fetched. At a future
// date, we should support fetching only the individual shards within a
// group that are needed to reconstruct the requested weight.
// TODO(cais): Use `decodeWeights` for implementation.
const fetchWeights = (fetchUrls) => loadWeightsAsArrayBuffer(fetchUrls, { requestInit });
const loadWeights = weightsLoaderFactory(fetchWeights);
return loadWeights(manifest, filePathPrefix, weightNames);
}
/**
* Creates a function, which reads a weights manifest JSON configuration,
* fetches the weight files using the specified function and returns them as
* `Tensor`s.
*
* ```js
* // example for creating a nodejs weight loader, which reads the weight files
* // from disk using fs.readFileSync
*
* import * as fs from 'fs'
*
* const fetchWeightsFromDisk = (filePaths: string[]) =>
* filePaths.map(filePath => fs.readFileSync(filePath).buffer)
*
* const loadWeights = tf.io.weightsLoaderFactory(fetchWeightsFromDisk)
*
* const manifest = JSON.parse(
* fs.readFileSync('./my_model-weights_manifest').toString()
* )
* const weightMap = await loadWeights(manifest, './')
* ```
* @param fetchWeightsFunction The function used for fetching the weight files.
* @returns Weight loading function.
*/
function weightsLoaderFactory(fetchWeightsFunction) {
return async (manifest, filePathPrefix = "", weightNames) => {
// Collect all the groups, weights, and their relative offsets to be
// fetched.
const groupIndicesToFetchMap = manifest.map(() => false);
const groupWeightsToFetch = {};
const weightsFound = weightNames != null ? weightNames.map(() => false) : [];
const allManifestWeightNames = [];
manifest.forEach((manifestGroupConfig, groupIndex) => {
let groupOffset = 0;
manifestGroupConfig.weights.forEach((weightsEntry) => {
const rawDtype =
"quantization" in weightsEntry
? weightsEntry.quantization.dtype
: weightsEntry.dtype;
const weightsBytes =
types["a" /* DTYPE_VALUE_SIZE_MAP */][rawDtype] *
util["sizeFromShape"](weightsEntry.shape);
const enqueueWeightsForFetchingFn = () => {
groupIndicesToFetchMap[groupIndex] = true;
if (groupWeightsToFetch[groupIndex] == null) {
groupWeightsToFetch[groupIndex] = [];
}
groupWeightsToFetch[groupIndex].push({
manifestEntry: weightsEntry,
groupOffset,
sizeBytes: weightsBytes,
});
};
if (weightNames != null) {
weightNames.forEach((weightName, weightIndex) => {
if (weightName === weightsEntry.name) {
enqueueWeightsForFetchingFn();
weightsFound[weightIndex] = true;
}
});
} else {
enqueueWeightsForFetchingFn();
}
allManifestWeightNames.push(weightsEntry.name);
groupOffset += weightsBytes;
});
});
if (!weightsFound.every((found) => found)) {
const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]);
throw new Error(
`Could not find weights in manifest with names: ` +
`${weightsNotFound.join(", ")}. \n` +
`Manifest JSON has weights with names: ` +
`${allManifestWeightNames.join(", ")}.`
);
}
// Convert the one-hot boolean groupId => shouldFetch map to a list of group
// IDs.
const groupIndicesToFetch = groupIndicesToFetchMap.reduce(
(accumulator, shouldFetch, i) => {
if (shouldFetch) {
accumulator.push(i);
}
return accumulator;
},
[]
);
const fetchUrls = [];
groupIndicesToFetch.forEach((i) => {
manifest[i].paths.forEach((filepath) => {
const fetchUrl =
filePathPrefix + (!filePathPrefix.endsWith("/") ? "/" : "") + filepath;
fetchUrls.push(fetchUrl);
});
});
const buffers = await fetchWeightsFunction(fetchUrls);
const weightsTensorMap = {};
let bufferIndexOffset = 0;
groupIndicesToFetch.forEach((i) => {
const numBuffers = manifest[i].paths.length;
let groupBytes = 0;
for (let i = 0; i < numBuffers; i++) {
groupBytes += buffers[bufferIndexOffset + i].byteLength;
}
// Create a buffer for the whole group.
const groupBuffer = new ArrayBuffer(groupBytes);
const groupByteBuffer = new Uint8Array(groupBuffer);
let groupBufferOffset = 0;
for (let i = 0; i < numBuffers; i++) {
const buffer = new Uint8Array(buffers[bufferIndexOffset + i]);
groupByteBuffer.set(buffer, groupBufferOffset);
groupBufferOffset += buffer.byteLength;
}
const weightsEntries = groupWeightsToFetch[i];
weightsEntries.forEach((weightsEntry) => {
const byteBuffer = groupBuffer.slice(
weightsEntry.groupOffset,
weightsEntry.groupOffset + weightsEntry.sizeBytes
);
const nameToTensorMap = Object(io_utils["e" /* decodeWeights */])(byteBuffer, [
weightsEntry.manifestEntry,
]);
for (const name in nameToTensorMap) {
weightsTensorMap[name] = nameToTensorMap[name];
}
});
bufferIndexOffset += numBuffers;
});
return weightsTensorMap;
};
}
//# sourceMappingURL=weights_loader.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/http.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* IOHandler implementations based on HTTP requests in the web browser.
*
* Uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
*/
const OCTET_STREAM_MIME_TYPE = "application/octet-stream";
const JSON_TYPE = "application/json";
class http_HTTPRequest {
constructor(path, loadOptions) {
this.DEFAULT_METHOD = "POST";
if (loadOptions == null) {
loadOptions = {};
}
this.weightPathPrefix = loadOptions.weightPathPrefix;
this.onProgress = loadOptions.onProgress;
if (loadOptions.fetchFunc != null) {
Object(util["assert"])(
typeof loadOptions.fetchFunc === "function",
() =>
"Must pass a function that matches the signature of " +
"`fetch` (see " +
"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"
);
this.fetch = loadOptions.fetchFunc;
} else {
this.fetch = Object(environment["c" /* env */])().platform.fetch;
}
Object(util["assert"])(
path != null && path.length > 0,
() => "URL path for http must not be null, undefined or " + "empty."
);
if (Array.isArray(path)) {
Object(util["assert"])(
path.length === 2,
() =>
"URL paths for http must have a length of 2, " +
`(actual length is ${path.length}).`
);
}
this.path = path;
if (loadOptions.requestInit != null && loadOptions.requestInit.body != null) {
throw new Error("requestInit is expected to have no pre-existing body, but has one.");
}
this.requestInit = loadOptions.requestInit || {};
}
async save(modelArtifacts) {
if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
throw new Error(
"BrowserHTTPRequest.save() does not support saving model topology " +
"in binary formats yet."
);
}
const init = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
init.body = new FormData();
const weightsManifest = [
{
paths: ["./model.weights.bin"],
weights: modelArtifacts.weightSpecs,
},
];
const modelTopologyAndWeightManifest = {
modelTopology: modelArtifacts.modelTopology,
format: modelArtifacts.format,
generatedBy: modelArtifacts.generatedBy,
convertedBy: modelArtifacts.convertedBy,
userDefinedMetadata: modelArtifacts.userDefinedMetadata,
weightsManifest,
};
init.body.append(
"model.json",
new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }),
"model.json"
);
if (modelArtifacts.weightData != null) {
init.body.append(
"model.weights.bin",
new Blob([modelArtifacts.weightData], { type: OCTET_STREAM_MIME_TYPE }),
"model.weights.bin"
);
}
const response = await this.fetch(this.path, init);
if (response.ok) {
return {
modelArtifactsInfo: Object(io_utils["g" /* getModelArtifactsInfoForJSON */])(
modelArtifacts
),
responses: [response],
};
} else {
throw new Error(
`BrowserHTTPRequest.save() failed due to HTTP response status ` +
`${response.status}.`
);
}
}
/**
* Load model artifacts via HTTP request(s).
*
* See the documentation to `tf.io.http` for details on the saved
* artifacts.
*
* @returns The loaded model artifacts (if loading succeeds).
*/
async load() {
const modelConfigRequest = await this.fetch(this.path, this.requestInit);
if (!modelConfigRequest.ok) {
throw new Error(
`Request to ${this.path} failed with status code ` +
`${modelConfigRequest.status}. Please verify this URL points to ` +
`the model JSON of the model to load.`
);
}
let modelConfig;
try {
modelConfig = await modelConfigRequest.json();
} catch (e) {
let message = `Failed to parse model JSON of response from ${this.path}.`;
// TODO(nsthorat): Remove this after some time when we're comfortable that
// .pb files are mostly gone.
if (this.path.endsWith(".pb")) {
message +=
" 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.";
} else {
message +=
" Please make sure the server is serving valid " + "JSON for this request.";
}
throw new Error(message);
}
const modelTopology = modelConfig.modelTopology;
const weightsManifest = modelConfig.weightsManifest;
const generatedBy = modelConfig.generatedBy;
const convertedBy = modelConfig.convertedBy;
const format = modelConfig.format;
const userDefinedMetadata = modelConfig.userDefinedMetadata;
// We do not allow both modelTopology and weightsManifest to be missing.
if (modelTopology == null && weightsManifest == null) {
throw new Error(
`The JSON from HTTP path ${this.path} contains neither model ` +
`topology or manifest for weights.`
);
}
let weightSpecs;
let weightData;
if (weightsManifest != null) {
const results = await this.loadWeights(weightsManifest);
[weightSpecs, weightData] = results;
}
return {
modelTopology,
weightSpecs,
weightData,
userDefinedMetadata,
generatedBy,
convertedBy,
format,
};
}
async loadWeights(weightsManifest) {
const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;
const [prefix, suffix] = parseUrl(weightPath);
const pathPrefix = this.weightPathPrefix || prefix;
const weightSpecs = [];
for (const entry of weightsManifest) {
weightSpecs.push(...entry.weights);
}
const fetchURLs = [];
weightsManifest.forEach((weightsGroup) => {
weightsGroup.paths.forEach((path) => {
fetchURLs.push(pathPrefix + path + suffix);
});
});
const buffers = await loadWeightsAsArrayBuffer(fetchURLs, {
requestInit: this.requestInit,
fetchFunc: this.fetch,
onProgress: this.onProgress,
});
return [weightSpecs, Object(io_utils["d" /* concatenateArrayBuffers */])(buffers)];
}
}
http_HTTPRequest.URL_SCHEME_REGEX = /^https?:\/\//;
/**
* Extract the prefix and suffix of the url, where the prefix is the path before
* the last file, and suffix is the search params after the last file.
* ```
* const url = 'http://tfhub.dev/model/1/tensorflowjs_model.pb?tfjs-format=file'
* [prefix, suffix] = parseUrl(url)
* // prefix = 'http://tfhub.dev/model/1/'
* // suffix = '?tfjs-format=file'
* ```
* @param url the model url to be parsed.
*/
function parseUrl(url) {
const lastSlash = url.lastIndexOf("/");
const lastSearchParam = url.lastIndexOf("?");
const prefix = url.substring(0, lastSlash);
const suffix = lastSearchParam > lastSlash ? url.substring(lastSearchParam) : "";
return [prefix + "/", suffix];
}
function isHTTPScheme(url) {
return url.match(http_HTTPRequest.URL_SCHEME_REGEX) != null;
}
const httpRouter = (url, loadOptions) => {
if (
typeof fetch === "undefined" &&
(loadOptions == null || loadOptions.fetchFunc == null)
) {
// `http` uses `fetch` or `node-fetch`, if one wants to use it in
// an environment that is not the browser or node they have to setup a
// global fetch polyfill.
return null;
} else {
let isHTTP = true;
if (Array.isArray(url)) {
isHTTP = url.every((urlItem) => isHTTPScheme(urlItem));
} else {
isHTTP = isHTTPScheme(url);
}
if (isHTTP) {
return http(url, loadOptions);
}
}
return null;
};
IORouterRegistry.registerSaveRouter(httpRouter);
IORouterRegistry.registerLoadRouter(httpRouter);
/**
* Creates an IOHandler subtype that sends model artifacts to HTTP server.
*
* An HTTP request of the `multipart/form-data` mime type will be sent to the
* `path` URL. The form data includes artifacts that represent the topology
* and/or weights of the model. In the case of Keras-style `tf.Model`, two
* blobs (files) exist in form-data:
* - A JSON file consisting of `modelTopology` and `weightsManifest`.
* - A binary weights file consisting of the concatenated weight values.
* These files are in the same format as the one generated by
* [tfjs_converter](https://js.tensorflow.org/tutorials/import-keras.html).
*
* The following code snippet exemplifies the client-side code that uses this
* function:
*
* ```js
* const model = tf.sequential();
* model.add(
* tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));
*
* const saveResult = await model.save(tf.io.http(
* 'http://model-server:5000/upload', {requestInit: {method: 'PUT'}}));
* console.log(saveResult);
* ```
*
* If the default `POST` method is to be used, without any custom parameters
* such as headers, you can simply pass an HTTP or HTTPS URL to `model.save`:
*
* ```js
* const saveResult = await model.save('http://model-server:5000/upload');
* ```
*
* The following GitHub Gist
* https://gist.github.com/dsmilkov/1b6046fd6132d7408d5257b0976f7864
* implements a server based on [flask](https://github.com/pallets/flask) that
* can receive the request. Upon receiving the model artifacts via the requst,
* this particular server reconsistutes instances of [Keras
* Models](https://keras.io/models/model/) in memory.
*
*
* @param path A URL path to the model.
* Can be an absolute HTTP path (e.g.,
* 'http://localhost:8000/model-upload)') or a relative path (e.g.,
* './model-upload').
* @param requestInit Request configurations to be used when sending
* HTTP request to server using `fetch`. It can contain fields such as
* `method`, `credentials`, `headers`, `mode`, etc. See
* https://developer.mozilla.org/en-US/docs/Web/API/Request/Request
* for more information. `requestInit` must not have a body, because the
* body will be set by TensorFlow.js. File blobs representing the model
* topology (filename: 'model.json') and the weights of the model (filename:
* 'model.weights.bin') will be appended to the body. If `requestInit` has a
* `body`, an Error will be thrown.
* @param loadOptions Optional configuration for the loading. It includes the
* following fields:
* - weightPathPrefix Optional, this specifies the path prefix for weight
* files, by default this is calculated from the path param.
* - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,
* the `fetch` from node-fetch can be used here.
* - onProgress Optional, progress callback function, fired periodically
* before the load is completed.
* @returns An instance of `IOHandler`.
*/
/**
* @doc {
* heading: 'Models',
* subheading: 'Loading',
* namespace: 'io',
* ignoreCI: true
* }
*/
function http(path, loadOptions) {
return new http_HTTPRequest(path, loadOptions);
}
/**
* Deprecated. Use `tf.io.http`.
* @param path
* @param loadOptions
*/
function browserHTTPRequest(path, loadOptions) {
return http(path, loadOptions);
}
//# sourceMappingURL=http.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/passthrough.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class PassthroughLoader {
constructor(modelArtifacts) {
this.modelArtifacts = modelArtifacts;
}
async load() {
return this.modelArtifacts;
}
}
class PassthroughSaver {
constructor(saveHandler) {
this.saveHandler = saveHandler;
}
async save(modelArtifacts) {
return this.saveHandler(modelArtifacts);
}
}
/**
* Creates an IOHandler that loads model artifacts from memory.
*
* When used in conjunction with `tf.loadLayersModel`, an instance of
* `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.
*
* ```js
* const model = await tf.loadLayersModel(tf.io.fromMemory(
* modelTopology, weightSpecs, weightData));
* ```
*
* @param modelArtifacts a object containing model topology (i.e., parsed from
* the JSON format).
* @param weightSpecs An array of `WeightsManifestEntry` objects describing the
* names, shapes, types, and quantization of the weight data.
* @param weightData A single `ArrayBuffer` containing the weight data,
* concatenated in the order described by the weightSpecs.
* @param trainingConfig Model training configuration. Optional.
*
* @returns A passthrough `IOHandler` that simply loads the provided data.
*/
function fromMemory(modelArtifacts, weightSpecs, weightData, trainingConfig) {
if (arguments.length === 1) {
const isModelArtifacts =
modelArtifacts.modelTopology != null || modelArtifacts.weightSpecs != null;
if (isModelArtifacts) {
return new PassthroughLoader(modelArtifacts);
} else {
// Legacy support: with only modelTopology.
// TODO(cais): Remove this deprecated API.
console.warn(
"Please call tf.io.fromMemory() with only one argument. " +
"The argument should be of type ModelArtifacts. " +
"The multi-argument signature of tf.io.fromMemory() has been " +
"deprecated and will be removed in a future release."
);
return new PassthroughLoader({ modelTopology: modelArtifacts });
}
} else {
// Legacy support.
// TODO(cais): Remove this deprecated API.
console.warn(
"Please call tf.io.fromMemory() with only one argument. " +
"The argument should be of type ModelArtifacts. " +
"The multi-argument signature of tf.io.fromMemory() has been " +
"deprecated and will be removed in a future release."
);
return new PassthroughLoader({
modelTopology: modelArtifacts,
weightSpecs,
weightData,
trainingConfig,
});
}
}
/**
* Creates an IOHandler that passes saved model artifacts to a callback.
*
* ```js
* function handleSave(artifacts) {
* // ... do something with the artifacts ...
* return {modelArtifactsInfo: {...}, ...};
* }
*
* const saveResult = model.save(tf.io.withSaveHandler(handleSave));
* ```
*
* @param saveHandler A function that accepts a `ModelArtifacts` and returns a
* `SaveResult`.
*/
function withSaveHandler(saveHandler) {
return new PassthroughSaver(saveHandler);
}
//# sourceMappingURL=passthrough.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/io/io.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Importing local_storage and indexed_db is necessary for the routers to be
// registered.
//# sourceMappingURL=io.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/one_hot.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a one-hot `tf.Tensor`. The locations represented by `indices` take
* value `onValue` (defaults to 1), while all other locations take value
* `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank
* `R+1` with the last axis of size `depth`.
*
* ```js
* tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();
* ```
*
* @param indices `tf.Tensor` of indices with dtype `int32`.
* @param depth The depth of the one hot dimension.
* @param onValue A number used to fill in the output when the index matches
* the location.
* @param offValue A number used to fill in the output when the index does
* not match the location.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function oneHot_(indices, depth, onValue = 1, offValue = 0) {
if (depth < 2) {
throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);
}
let $indices = Object(tensor_util_env["a" /* convertToTensor */])(
indices,
"indices",
"oneHot",
"int32"
);
const outShape = [...$indices.shape, depth];
$indices = $indices.flatten();
const forward = (backend, save) => {
save([$indices]);
return reshape(backend.oneHot($indices, depth, onValue, offValue), outShape);
};
const inputs = { indices: $indices };
const attrs = { depth, onValue, offValue };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["cb" /* OneHot */],
attrs
);
}
const oneHot = Object(operation["a" /* op */])({ oneHot_ });
//# sourceMappingURL=one_hot.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/confusion_matrix.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the confusion matrix from true labels and predicted labels.
*
* ```js
* const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');
* const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');
* const numClasses = 3;
* const out = tf.math.confusionMatrix(labels, predictions, numClasses);
* out.print();
* // Expected output matrix:
* // [[2, 0, 0],
* // [0, 1, 1],
* // [0, 0, 1]]
* ```
*
* @param labels The target labels, assumed to be 0-based integers
* for the classes. The shape is `[numExamples]`, where
* `numExamples` is the number of examples included.
* @param predictions The predicted classes, assumed to be
* 0-based integers for the classes. Must have the same shape as `labels`.
* @param numClasses Number of all classes, as an integer.
* Its value must be larger than the largest element in `labels` and
* `predictions`.
* @returns The confusion matrix as a int32-type 2D tensor. The value at
* row `r` and column `c` is the number of times examples of actual class
* `r` were predicted as class `c`.
*/
/** @doc {heading: 'Operations', subheading: 'Evaluation'} */
function confusionMatrix_(labels, predictions, numClasses) {
const $labels = Object(tensor_util_env["a" /* convertToTensor */])(
labels,
"labels",
"confusionMatrix"
);
const $predictions = Object(tensor_util_env["a" /* convertToTensor */])(
predictions,
"predictions",
"confusionMatrix"
);
util["assert"](
numClasses == null || (numClasses > 0 && Number.isInteger(numClasses)),
() => `If provided, numClasses must be a positive integer, ` + `but got ${numClasses}`
);
util["assert"](
$labels.rank === 1,
() => `Expected the rank of labels to be 1, but got ${$labels.rank}`
);
util["assert"](
$predictions.rank === 1,
() => `Expected the rank of predictions to be 1, ` + `but got ${$predictions.rank}`
);
util["assert"](
$labels.shape[0] === $predictions.shape[0],
() =>
`Mismatch in the number of examples: ` +
`${$labels.shape[0]} vs. ${$predictions.shape[0]}. ` +
`Labels and predictions should have the same number of elements.`
);
util["assert"](
numClasses > 0 && Number.isInteger(numClasses),
() => `numClasses is required to be a positive integer, but got ` + `${numClasses}`
);
// TODO(cais): In the future, if oneHot supports tensors inputs for
// `numClasses`, `confusionMatrix` can make `numClasses` optional.
const oneHotLabels = oneHot($labels.asType("int32"), numClasses);
const oneHotPredictions = oneHot($predictions.asType("int32"), numClasses);
const oneHotLabelsT = oneHotLabels.transpose();
return oneHotLabelsT.matMul(oneHotPredictions).asType("int32");
}
const confusionMatrix = Object(operation["a" /* op */])({ confusionMatrix_ });
//# sourceMappingURL=confusion_matrix.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/math.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Exports under the tf.math.* namespace.
*/
//# sourceMappingURL=math.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/browser.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
let fromPixels2DContext;
/**
* Creates a `tf.Tensor` from an image.
*
* ```js
* const image = new ImageData(1, 1);
* image.data[0] = 100;
* image.data[1] = 150;
* image.data[2] = 200;
* image.data[3] = 255;
*
* tf.browser.fromPixels(image).print();
* ```
*
* @param pixels The input image to construct the tensor from. The
* supported image types are all 4-channel. You can also pass in an image
* object with following attributes:
* `{data: Uint8Array; width: number; height: number}`
* @param numChannels The number of channels of the output tensor. A
* numChannels value less than 4 allows you to ignore channels. Defaults to
* 3 (ignores alpha channel of input image).
*/
/** @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true} */
function fromPixels_(pixels, numChannels = 3) {
// Sanity checks.
if (numChannels > 4) {
throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");
}
if (pixels == null) {
throw new Error("pixels passed to tf.browser.fromPixels() can not be null");
}
let isPixelData = false;
let isImageData = false;
let isVideo = false;
let isImage = false;
let isCanvasLike = false;
if (pixels.data instanceof Uint8Array) {
isPixelData = true;
} else if (typeof ImageData !== "undefined" && pixels instanceof ImageData) {
isImageData = true;
} else if (typeof HTMLVideoElement !== "undefined" && pixels instanceof HTMLVideoElement) {
isVideo = true;
} else if (typeof HTMLImageElement !== "undefined" && pixels instanceof HTMLImageElement) {
isImage = true;
// tslint:disable-next-line: no-any
} else if (pixels.getContext != null) {
isCanvasLike = true;
} else {
throw new Error(
"pixels passed to tf.browser.fromPixels() must be either an " +
`HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData ` +
`in browser, or OffscreenCanvas, ImageData in webworker` +
` or {data: Uint32Array, width: number, height: number}, ` +
`but was ${pixels.constructor.name}`
);
}
if (isVideo) {
const HAVE_CURRENT_DATA_READY_STATE = 2;
if (isVideo && pixels.readyState < HAVE_CURRENT_DATA_READY_STATE) {
throw new Error(
"The video element has not loaded data yet. Please wait for " +
"`loadeddata` event on the <video> element."
);
}
}
// If the current backend has 'FromPixels' registered, it has a more
// efficient way of handling pixel uploads, so we call that.
const kernel = Object(kernel_registry["b" /* getKernel */])(
kernel_names["E" /* FromPixels */],
engine["a" /* ENGINE */].backendName
);
if (kernel != null) {
const inputs = { pixels };
const attrs = { numChannels };
return engine["a" /* ENGINE */].runKernel(
kernel_names["E" /* FromPixels */],
inputs,
attrs
);
}
const [width, height] = isVideo
? [pixels.videoWidth, pixels.videoHeight]
: [pixels.width, pixels.height];
let vals;
if (isCanvasLike) {
vals =
// tslint:disable-next-line:no-any
pixels.getContext("2d").getImageData(0, 0, width, height).data;
} else if (isImageData || isPixelData) {
vals = pixels.data;
} else if (isImage || isVideo) {
if (fromPixels2DContext == null) {
fromPixels2DContext = document.createElement("canvas").getContext("2d");
}
fromPixels2DContext.canvas.width = width;
fromPixels2DContext.canvas.height = height;
fromPixels2DContext.drawImage(pixels, 0, 0, width, height);
vals = fromPixels2DContext.getImageData(0, 0, width, height).data;
}
let values;
if (numChannels === 4) {
values = new Int32Array(vals);
} else {
const numPixels = width * height;
values = new Int32Array(numPixels * numChannels);
for (let i = 0; i < numPixels; i++) {
for (let channel = 0; channel < numChannels; ++channel) {
values[i * numChannels + channel] = vals[i * 4 + channel];
}
}
}
const outShape = [height, width, numChannels];
return Object(tensor_ops["i" /* tensor3d */])(values, outShape, "int32");
}
/**
* Draws a `tf.Tensor` of pixel values to a byte array or optionally a
* canvas.
*
* When the dtype of the input is 'float32', we assume values in the range
* [0-1]. Otherwise, when input is 'int32', we assume values in the range
* [0-255].
*
* Returns a promise that resolves when the canvas has been drawn to.
*
* @param img A rank-2 or rank-3 tensor. If rank-2, draws grayscale. If
* rank-3, must have depth of 1, 3 or 4. When depth of 1, draws
* grayscale. When depth of 3, we draw with the first three components of
* the depth dimension corresponding to r, g, b and alpha = 1. When depth of
* 4, all four components of the depth dimension correspond to r, g, b, a.
* @param canvas The canvas to draw to.
*/
/** @doc {heading: 'Browser', namespace: 'browser'} */
async function toPixels(img, canvas) {
let $img = Object(tensor_util_env["a" /* convertToTensor */])(img, "img", "toPixels");
if (!(img instanceof dist_tensor["a" /* Tensor */])) {
// Assume int32 if user passed a native array.
const originalImgTensor = $img;
$img = originalImgTensor.toInt();
originalImgTensor.dispose();
}
if ($img.rank !== 2 && $img.rank !== 3) {
throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${$img.rank}.`);
}
const [height, width] = $img.shape.slice(0, 2);
const depth = $img.rank === 2 ? 1 : $img.shape[2];
if (depth > 4 || depth === 2) {
throw new Error(`toPixels only supports depth of size ` + `1, 3 or 4 but got ${depth}`);
}
const data = await $img.data();
const minTensor = $img.min();
const maxTensor = $img.max();
const vals = await Promise.all([minTensor.data(), maxTensor.data()]);
const minVals = vals[0];
const maxVals = vals[1];
const min = minVals[0];
const max = maxVals[0];
minTensor.dispose();
maxTensor.dispose();
if ($img.dtype === "float32") {
if (min < 0 || max > 1) {
throw new Error(
`Tensor values for a float32 Tensor must be in the ` +
`range [0 - 1] but got range [${min} - ${max}].`
);
}
} else if ($img.dtype === "int32") {
if (min < 0 || max > 255) {
throw new Error(
`Tensor values for a int32 Tensor must be in the ` +
`range [0 - 255] but got range [${min} - ${max}].`
);
}
} else {
throw new Error(
`Unsupported type for toPixels: ${$img.dtype}.` +
` Please use float32 or int32 tensors.`
);
}
const multiplier = $img.dtype === "float32" ? 255 : 1;
const bytes = new Uint8ClampedArray(width * height * 4);
for (let i = 0; i < height * width; ++i) {
let r, g, b, a;
if (depth === 1) {
r = data[i] * multiplier;
g = data[i] * multiplier;
b = data[i] * multiplier;
a = 255;
} else if (depth === 3) {
r = data[i * 3] * multiplier;
g = data[i * 3 + 1] * multiplier;
b = data[i * 3 + 2] * multiplier;
a = 255;
} else if (depth === 4) {
r = data[i * 4] * multiplier;
g = data[i * 4 + 1] * multiplier;
b = data[i * 4 + 2] * multiplier;
a = data[i * 4 + 3] * multiplier;
}
const j = i * 4;
bytes[j + 0] = Math.round(r);
bytes[j + 1] = Math.round(g);
bytes[j + 2] = Math.round(b);
bytes[j + 3] = Math.round(a);
}
if (canvas != null) {
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
const imageData = new ImageData(bytes, width, height);
ctx.putImageData(imageData, 0, 0);
}
if ($img !== img) {
$img.dispose();
}
return bytes;
}
const fromPixels = Object(operation["a" /* op */])({ fromPixels_ });
//# sourceMappingURL=browser.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/gather_nd_util.js
/**
* Validate gather nd inputs.
*
* @param tensor The tensor contains the source values.
* @param indices The tensor contains the indices to slice the source.
*
* @returns [resultShape, numUpdates, sliceSize, strides]
*/
function prepareAndValidate(tensor, indices) {
if (tensor.rank < 1) {
throw new Error(
"tf.gatherND() expects the input to be rank 1 or higher," +
` but the rank was ${tensor.rank}.`
);
}
if (indices.rank < 1) {
throw new Error(
"tf.gatherND() expects the indices to be rank 1 or higher," +
` but the rank was ${indices.rank}.`
);
}
if (indices.dtype !== "int32") {
throw new Error(
"tf.gatherND() expects the indices to be int32 type," +
` but the dtype was ${indices.dtype}.`
);
}
if (indices.shape[indices.rank - 1] > tensor.rank) {
throw new Error(
"index innermost dimension length must be <= tensor rank; saw: " +
`${indices.shape[indices.rank - 1]} vs. ${tensor.rank}`
);
}
if (tensor.size === 0) {
throw new Error(
"Requested more than 0 entries, but input is empty." + ` Input shape: ${tensor.shape}.`
);
}
const indicesShape = indices.shape;
const sliceRank = indicesShape[indicesShape.length - 1];
// The result shape is
// indices.shape[:-1] + params.shape[indices.shape[-1]:]
let nResult = 1;
for (let i = 0; i < indicesShape.length - 1; ++i) {
nResult *= indicesShape[i];
}
const inputShape = tensor.shape;
const resultShape = indicesShape.slice();
resultShape.pop();
let sliceSize = 1;
for (let i = sliceRank; i < tensor.rank; ++i) {
sliceSize *= inputShape[i];
resultShape.push(inputShape[i]);
}
const strides = [
...Object(util["computeStrides"])(tensor.shape).map((stride) => stride / sliceSize),
1,
].slice(0, sliceRank);
return [resultShape, nResult, sliceSize, strides];
}
//# sourceMappingURL=gather_nd_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/scatter_nd_util.js
/**
* Check whether updates.shape = indices.shape[:batchDim] +
* shape[sliceDim:]
*
* @param x The input tensor.
*/
function validateUpdateShape(shape, indices, updates) {
const sliceDim = indices.rank > 1 ? indices.shape[indices.rank - 1] : 1;
const batchDim = indices.rank > 1 ? indices.rank - 1 : 1;
const shapeError =
"Must have updates.shape = indices.shape[:batchDim] + " +
`shape[sliceDim:], got updates.shape: ${updates.shape}` +
`, indices.shape: ${indices.shape}, shape: ${shape}` +
`, sliceDim: ${sliceDim}, and batchDim: ${batchDim}.`;
if (updates.rank < batchDim) {
throw new Error(shapeError + ` update.rank < ${batchDim}. `);
}
if (shape.length < sliceDim + (updates.rank - batchDim)) {
throw new Error(
shapeError + ` Output shape length < ${sliceDim + (updates.rank - batchDim)}`
);
}
if (updates.rank !== batchDim + shape.length - sliceDim) {
throw new Error(shapeError + ` update.rank != ${batchDim + shape.length - sliceDim}`);
}
for (let d = 0; d < batchDim; ++d) {
if (updates.shape[d] !== indices.shape[d]) {
throw new Error(
shapeError +
` updates.shape[${d}] (${updates.shape[d]}) != indices.shape[${d}] (${indices.shape[d]}).`
);
}
}
for (let d = 0; d < updates.rank - batchDim; ++d) {
if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {
throw new Error(
shapeError +
` updates.shape[${d + batchDim}] (${updates.shape[d + batchDim]}) != shape[${
d + batchDim
}] (${shape[d + batchDim]})`
);
}
}
}
/**
* Validate scatter nd inputs.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*/
function validateInput(updates, indices, shape) {
if (indices.rank < 1) {
throw new Error(
"tf.scatterND() expects the indices to be rank 1 or higher," +
` but the rank was ${indices.rank}.`
);
}
if (updates.rank < 1) {
throw new Error(
"tf.scatterND() expects the updates to be rank 1 or higher," +
` but the rank was ${updates.rank}.`
);
}
if (indices.dtype !== "int32") {
throw new Error(
`The dtype of 'indices' should be int32, but got dtype: ${indices.dtype}`
);
}
if (shape.length < 1) {
throw new Error(`Output rank must be greater or equal to 1, but got shape: ${shape}`);
}
if (shape.length === 0) {
if (indices.size === 0) {
throw new Error(`Indices specified for empty output. indices shape: ${indices.shape}`);
}
if (updates.size === 0) {
throw new Error(`Updates specified for empty output. updates shape: ${updates.shape}`);
}
}
validateUpdateShape(shape, indices, updates);
}
/**
* Calculate the shape information for the output.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*
* @returns ScatterShapeInfo
*/
function calculateShapes(updates, indices, shape) {
// Calculate the number of dimensions in indices
const indicesRank = indices.shape.length;
const sliceRank = indicesRank > 1 ? indices.shape[indicesRank - 1] : 1;
// Calculate the number of elements that make up each slice of our updated
// tensor. This allows us to work with flattened tensors and copy over whole
// slices at a time.
const totalNd = shape.length;
let sliceSize = 1;
for (let i = sliceRank; i < totalNd; ++i) {
sliceSize *= shape[i];
}
const safeSliceDim = sliceRank < 1 ? 1 : sliceRank;
const numUpdates = Object(util["sizeFromShape"])(indices.shape) / safeSliceDim;
const strides = [...Object(util["computeStrides"])(shape.slice(0, sliceRank)), 1];
const outputSize = Object(util["sizeFromShape"])(shape);
return { sliceRank, numUpdates, sliceSize, strides, outputSize };
}
//# sourceMappingURL=scatter_nd_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/serialization.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Serializable defines the serialization contract.
*
* TFJS requires serializable classes to return their className when asked
* to avoid issues with minification.
*/
class Serializable {
/**
* Return the class name for this class to use in serialization contexts.
*
* Generally speaking this will be the same thing that constructor.name
* would have returned. However, the class name needs to be robust
* against minification for serialization/deserialization to work properly.
*
* There's also places such as initializers.VarianceScaling, where
* implementation details between different languages led to different
* class hierarchies and a non-leaf node is used for serialization purposes.
*/
getClassName() {
return this.constructor.className;
}
/**
* Creates an instance of T from a ConfigDict.
*
* This works for most descendants of serializable. A few need to
* provide special handling.
* @param cls A Constructor for the class to instantiate.
* @param config The Configuration for the object.
*/
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(config);
}
}
/**
* Maps string keys to class constructors.
*
* Used during (de)serialization from the cross-language JSON format, which
* requires the class name in the serialization format matches the class
* names as used in Python, should it exist.
*/
class SerializationMap {
constructor() {
this.classNameMap = {};
}
/**
* Returns the singleton instance of the map.
*/
static getMap() {
if (SerializationMap.instance == null) {
SerializationMap.instance = new SerializationMap();
}
return SerializationMap.instance;
}
/**
* Registers the class as serializable.
*/
static register(cls) {
SerializationMap.getMap().classNameMap[cls.className] = [cls, cls.fromConfig];
}
}
/**
* Register a class with the serialization map of TensorFlow.js.
*
* This is often used for registering custom Layers, so they can be
* serialized and deserialized.
*
* Example:
*
* ```js
* class MyCustomLayer extends tf.layers.Layer {
* static className = 'MyCustomLayer';
*
* constructor(config) {
* super(config);
* }
* }
* tf.serialization.registerClass(MyCustomLayer);
* ```
*
* @param cls The class to be registered. It must have a public static member
* called `className` defined and the value must be a non-empty string.
*/
/** @doc {heading: 'Models', subheading: 'Serialization', ignoreCI: true} */
function registerClass(cls) {
Object(util["assert"])(
cls.className != null,
() => `Class being registered does not have the static className ` + `property defined.`
);
Object(util["assert"])(
typeof cls.className === "string",
() => `className is required to be a string, but got type ` + typeof cls.className
);
Object(util["assert"])(
cls.className.length > 0,
() =>
`Class being registered has an empty-string as its className, ` + `which is disallowed.`
);
SerializationMap.register(cls);
}
//# sourceMappingURL=serialization.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/test_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const TEST_EPSILON_FLOAT32 = 1e-3;
const TEST_EPSILON_FLOAT16 = 1e-1;
function expectArraysClose(actual, expected, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
return expectArraysPredicate(actual, expected, (a, b) => areClose(a, b, epsilon));
}
function testEpsilon() {
return engine["a" /* ENGINE */].backend.floatPrecision() === 32
? TEST_EPSILON_FLOAT32
: TEST_EPSILON_FLOAT16;
}
function expectArraysPredicate(actual, expected, predicate) {
let checkClassType = true;
if (Object(util["isTypedArray"])(actual) || Object(util["isTypedArray"])(expected)) {
checkClassType = false;
}
if (Object(util["isTypedArray"])(actual) && Object(util["isTypedArray"])(expected)) {
checkClassType = true;
}
if (checkClassType) {
const aType = actual.constructor.name;
const bType = expected.constructor.name;
if (aType !== bType) {
throw new Error(
`Arrays are of different type. Actual: ${aType}. ` + `Expected: ${bType}`
);
}
}
if (Array.isArray(actual) && Array.isArray(expected)) {
const actualShape = Object(tensor_util_env["c" /* inferShape */])(actual);
const expectedShape = Object(tensor_util_env["c" /* inferShape */])(expected);
if (!Object(util["arraysEqual"])(actualShape, expectedShape)) {
throw new Error(
`Arrays have different shapes. ` +
`Actual: [${actualShape}]. Expected: [${expectedShape}]`
);
}
}
const actualFlat = Object(util["isTypedArray"])(actual)
? actual
: Object(util["flatten"])(actual);
const expectedFlat = Object(util["isTypedArray"])(expected)
? expected
: Object(util["flatten"])(expected);
if (actualFlat.length !== expectedFlat.length) {
throw new Error(
`Arrays have different lengths actual: ${actualFlat.length} vs ` +
`expected: ${expectedFlat.length}.\n` +
`Actual: ${actualFlat}.\n` +
`Expected: ${expectedFlat}.`
);
}
for (let i = 0; i < expectedFlat.length; ++i) {
const a = actualFlat[i];
const e = expectedFlat[i];
if (!predicate(a, e)) {
throw new Error(
`Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${e}.\n` +
`Actual: ${actualFlat}.\n` +
`Expected: ${expectedFlat}.`
);
}
}
}
function expectPromiseToFail(fn, done) {
fn().then(
() => done.fail(),
() => done()
);
}
function expectArraysEqual(actual, expected) {
const exp =
typeof expected === "string" ||
typeof expected === "number" ||
typeof expected === "boolean"
? [expected]
: expected;
if (
Object(util["isString"])(actual) ||
Object(util["isString"])(actual[0]) ||
Object(util["isString"])(expected) ||
Object(util["isString"])(expected[0])
) {
// tslint:disable-next-line: triple-equals
return expectArraysPredicate(actual, exp, (a, b) => a == b);
}
return expectArraysPredicate(actual, expected, (a, b) => areClose(a, b, 0));
}
function expectNumbersClose(a, e, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
if (!areClose(a, e, epsilon)) {
throw new Error(`Numbers differ: actual === ${a}, expected === ${e}`);
}
}
function areClose(a, e, epsilon) {
if (!isFinite(a) && !isFinite(e)) {
return true;
}
if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) {
return false;
}
return true;
}
function expectValuesInRange(actual, low, high) {
for (let i = 0; i < actual.length; i++) {
if (actual[i] < low || actual[i] > high) {
throw new Error(`Value out of range:${actual[i]} low: ${low}, high: ${high}`);
}
}
}
function expectArrayBuffersEqual(actual, expected) {
// Safari & Jasmine don't like comparing ArrayBuffers directly. Wrapping in
// a Float32Array solves this issue.
expect(new Float32Array(actual)).toEqual(new Float32Array(expected));
}
//# sourceMappingURL=test_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/version.js
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
const version = "2.0.1";
//# sourceMappingURL=version.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/globals.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Enables production mode which disables correctness checks in favor of
* performance.
*/
/** @doc {heading: 'Environment'} */
function enableProdMode() {
Object(environment["c" /* env */])().set("PROD", true);
}
/**
* Enables debug mode which will log information about all executed kernels:
* the elapsed time of the kernel execution, as well as the rank, shape, and
* size of the output tensor.
*
* Debug mode will significantly slow down your application as it will
* download the result of every operation to the CPU. This should not be used in
* production. Debug mode does not affect the timing information of the kernel
* execution as we do not measure download time in the kernel execution time.
*
* See also: `tf.profile`, `tf.memory`.
*/
/** @doc {heading: 'Environment'} */
function enableDebugMode() {
Object(environment["c" /* env */])().set("DEBUG", true);
}
/** Globally disables deprecation warnings */
function disableDeprecationWarnings() {
Object(environment["c" /* env */])().set("DEPRECATION_WARNINGS_ENABLED", false);
console.warn(`TensorFlow.js deprecation warnings have been disabled.`);
}
/** Warn users about deprecated functionality. */
function deprecationWarn(msg) {
if (Object(environment["c" /* env */])().getBool("DEPRECATION_WARNINGS_ENABLED")) {
console.warn(
msg + " You can disable deprecation warnings with " + "tf.disableDeprecationWarnings()."
);
}
}
Object(dist_tensor["d" /* setDeprecationWarningFn */])(deprecationWarn);
/**
* Dispose all variables kept in backend engine.
*/
/** @doc {heading: 'Environment'} */
function disposeVariables() {
engine["a" /* ENGINE */].disposeVariables();
}
/**
* It returns the global engine that keeps track of all tensors and backends.
*/
/** @doc {heading: 'Environment'} */
function globals_engine() {
return engine["a" /* ENGINE */];
}
/**
* Returns memory info at the current time in the program. The result is an
* object with the following properties:
*
* - `numBytes`: Number of bytes allocated (undisposed) at this time.
* - `numTensors`: Number of unique tensors allocated.
* - `numDataBuffers`: Number of unique data buffers allocated
* (undisposed) at this time, which is ≤ the number of tensors
* (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same
* data buffer with `a`).
* - `unreliable`: True if the memory usage is unreliable. See `reasons` when
* `unreliable` is true.
* - `reasons`: `string[]`, reasons why the memory is unreliable, present if
* `unreliable` is true.
*
* WebGL Properties:
* - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at
* this time.
*/
/** @doc {heading: 'Performance', subheading: 'Memory'} */
function memory() {
return engine["a" /* ENGINE */].memory();
}
/**
* Executes the provided function `f()` and returns a promise that resolves
* with information about the function's memory use:
* - `newBytes`: the number of new bytes allocated
* - `newTensors`: the number of new tensors created
* - `peakBytes`: the peak number of bytes allocated
* - `kernels`: an array of objects for each kernel involved that reports
* their input and output shapes, number of bytes used, and number of new
* tensors created.
*
* ```js
* const profile = await tf.profile(() => {
* const x = tf.tensor1d([1, 2, 3]);
* let x2 = x.square();
* x2.dispose();
* x2 = x.square();
* x2.dispose();
* return x;
* });
*
* console.log(`newBytes: ${profile.newBytes}`);
* console.log(`newTensors: ${profile.newTensors}`);
* console.log(`byte usage over all kernels: ${profile.kernels.map(k =>
* k.totalBytesSnapshot)}`);
* ```
*
*/
/** @doc {heading: 'Performance', subheading: 'Profile'} */
function profile(f) {
return engine["a" /* ENGINE */].profile(f);
}
/**
* Executes the provided function `fn` and after it is executed, cleans up all
* intermediate tensors allocated by `fn` except those returned by `fn`.
* `fn` must not return a Promise (async functions not allowed). The returned
* result can be a complex object.
*
* Using this method helps avoid memory leaks. In general, wrap calls to
* operations in `tf.tidy` for automatic memory cleanup.
*
* NOTE: Variables do *not* get cleaned up when inside a tidy(). If you want to
* dispose variables, please use `tf.disposeVariables` or call dispose()
* directly on variables.
*
* ```js
* // y = 2 ^ 2 + 1
* const y = tf.tidy(() => {
* // a, b, and one will be cleaned up when the tidy ends.
* const one = tf.scalar(1);
* const a = tf.scalar(2);
* const b = a.square();
*
* console.log('numTensors (in tidy): ' + tf.memory().numTensors);
*
* // The value returned inside the tidy function will return
* // through the tidy, in this case to the variable y.
* return b.add(one);
* });
*
* console.log('numTensors (outside tidy): ' + tf.memory().numTensors);
* y.print();
* ```
*
* @param nameOrFn The name of the closure, or the function to execute.
* If a name is provided, the 2nd argument should be the function.
* If debug mode is on, the timing and the memory usage of the function
* will be tracked and displayed on the console using the provided name.
* @param fn The function to execute.
*/
/** @doc {heading: 'Performance', subheading: 'Memory'} */
function tidy(nameOrFn, fn) {
return engine["a" /* ENGINE */].tidy(nameOrFn, fn);
}
/**
* Disposes any `tf.Tensor`s found within the provided object.
*
* @param container an object that may be a `tf.Tensor` or may directly
* contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If
* the object is not a `tf.Tensor` or does not contain `Tensors`, nothing
* happens. In general it is safe to pass any object here, except that
* `Promise`s are not supported.
*/
/** @doc {heading: 'Performance', subheading: 'Memory'} */
function dispose(container) {
const tensors = Object(tensor_util["getTensorsInContainer"])(container);
tensors.forEach((tensor) => tensor.dispose());
}
/**
* Keeps a `tf.Tensor` generated inside a `tf.tidy` from being disposed
* automatically.
*
* ```js
* let b;
* const y = tf.tidy(() => {
* const one = tf.scalar(1);
* const a = tf.scalar(2);
*
* // b will not be cleaned up by the tidy. a and one will be cleaned up
* // when the tidy ends.
* b = tf.keep(a.square());
*
* console.log('numTensors (in tidy): ' + tf.memory().numTensors);
*
* // The value returned inside the tidy function will return
* // through the tidy, in this case to the variable y.
* return b.add(one);
* });
*
* console.log('numTensors (outside tidy): ' + tf.memory().numTensors);
* console.log('y:');
* y.print();
* console.log('b:');
* b.print();
* ```
*
* @param result The tensor to keep from being disposed.
*/
/** @doc {heading: 'Performance', subheading: 'Memory'} */
function keep(result) {
return engine["a" /* ENGINE */].keep(result);
}
/**
* Executes `f()` and returns a promise that resolves with timing
* information.
*
* The result is an object with the following properties:
*
* - `wallMs`: Wall execution time.
* - `kernelMs`: Kernel execution time, ignoring data transfer. If using the
* WebGL backend and the query timer extension is not available, this will
* return an error object.
* - On `WebGL` The following additional properties exist:
* - `uploadWaitMs`: CPU blocking time on texture uploads.
* - `downloadWaitMs`: CPU blocking time on texture downloads (readPixels).
*
* ```js
* const x = tf.randomNormal([20, 20]);
* const time = await tf.time(() => x.matMul(x));
*
* console.log(`kernelMs: ${time.kernelMs}, wallTimeMs: ${time.wallMs}`);
* ```
*
* @param f The function to execute and time.
*/
/** @doc {heading: 'Performance', subheading: 'Timing'} */
function time(f) {
return engine["a" /* ENGINE */].time(f);
}
/**
* Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and
* executing operations on those tensors. Returns a promise that resolves
* to a boolean if the backend initialization was successful.
*
* Note this disposes the current backend, if any, as well as any tensors
* associated with it. A new backend is initialized, even if it is of the
* same type as the previous one.
*
* @param backendName The name of the backend. Currently supports
* `'webgl'|'cpu'` in the browser, `'tensorflow'` under node.js
* (requires tfjs-node), and `'wasm'` (requires tfjs-backend-wasm).
*/
/** @doc {heading: 'Backends'} */
function setBackend(backendName) {
return engine["a" /* ENGINE */].setBackend(backendName);
}
/**
* Returns a promise that resolves when the currently selected backend (or the
* highest priority one) has initialized. Await this promise when you are using
* a backend that has async initialization.
*/
/** @doc {heading: 'Backends'} */
function ready() {
return engine["a" /* ENGINE */].ready();
}
/**
* Returns the current backend name (cpu, webgl, etc). The backend is
* responsible for creating tensors and executing operations on those tensors.
*/
/** @doc {heading: 'Backends'} */
function getBackend() {
return engine["a" /* ENGINE */].backendName;
}
/**
* Removes a backend and the registered factory.
*/
/** @doc {heading: 'Backends'} */
function removeBackend(name) {
engine["a" /* ENGINE */].removeBackend(name);
}
/**
* Finds the backend registered under the provided name. Returns null if the
* name is not in the registry, or the registration hasn't finished yet.
*/
function findBackend(name) {
return engine["a" /* ENGINE */].findBackend(name);
}
/**
* Finds the backend factory registered under the provided name. Returns a
* function that produces a new backend when called. Returns null if the name
* is not in the registry.
*/
function findBackendFactory(name) {
return engine["a" /* ENGINE */].findBackendFactory(name);
}
/**
* Registers a global backend. The registration should happen when importing
* a module file (e.g. when importing `backend_webgl.ts`), and is used for
* modular builds (e.g. custom tfjs bundle with only webgl support).
*
* @param factory The backend factory function. When called, it should
* return a backend instance, or a promise of an instance.
* @param priority The priority of the backend (higher = more important).
* In case multiple backends are registered, the priority is used to find
* the best backend. Defaults to 1.
* @return False if there is already a registered backend under this name, true
* if not.
*/
/** @doc {heading: 'Backends'} */
function registerBackend(name, factory, priority = 1) {
return engine["a" /* ENGINE */].registerBackend(name, factory, priority);
}
/**
* Gets the current backend. If no backends have been initialized, this will
* attempt to initialize the best backend. Will throw an error if the highest
* priority backend has async initialization, in which case, you should call
* 'await tf.ready()' before running other code.
*/
/** @doc {heading: 'Backends'} */
function globals_backend() {
return engine["a" /* ENGINE */].backend;
}
/**
* Sets the global platform.
*
* @param platformName The name of this platform.
* @param platform A platform implementation.
*/
function setPlatform(platformName, platform) {
Object(environment["c" /* env */])().setPlatform(platformName, platform);
}
//# sourceMappingURL=globals.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/add_n.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
*
* tf.addN([a, b, c]).print();
* ```
* @param tensors A list of tensors with the same shape and dtype.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function addN_(tensors) {
util["assert"](
Array.isArray(tensors),
() => "The argument passed to tf.addN() must be a list of tensors"
);
util["assert"](
tensors.length >= 1,
() => `Must pass at least one tensor to tf.addN(), but got ` + `${tensors.length}`
);
const $tensors = tensors.map((t, i) =>
Object(tensor_util_env["a" /* convertToTensor */])(t, `tensors${i}`, "addN")
);
const firstTensor = $tensors[0];
$tensors.forEach((t) => {
if (t.dtype !== firstTensor.dtype) {
throw new Error("All tensors passed to tf.addN() must have the same dtype");
}
});
$tensors.forEach((t) => {
if (!util["arraysEqual"](t.shape, firstTensor.shape)) {
throw new Error("All tensors passed to tf.addN() must have the same shape");
}
});
const forward = (backend, save) => {
const res = backend.addN($tensors);
save($tensors);
return res;
};
const inputs = $tensors;
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["b" /* AddN */]
);
}
const addN = Object(operation["a" /* op */])({ addN_ });
//# sourceMappingURL=add_n.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/atan2.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);
* const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);
*
* tf.atan2(a, b).print()
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same dtype as `a`.
*
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function atan2_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "atan2");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "atan2");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
const forward = (backend, save) => {
const res = backend.atan2($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["c" /* Atan2 */]
);
}
const atan2 = Object(operation["a" /* op */])({ atan2_ });
//# sourceMappingURL=atan2.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/avg_pool.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D average pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
function avgPool_(x, filterSize, strides, pad, dimRoundingMode) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "avgPool", "float32");
const dilations = 1;
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in avgPool: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
util["assert"](
x4D.rank === 4,
() => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in avgPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend, save) => {
const convInfo = computePool2DInfo(
x4D.shape,
filterSize,
strides,
1 /* dilations */,
pad,
dimRoundingMode
);
save([x4D]);
if (
convInfo.filterWidth === 1 &&
convInfo.filterHeight === 1 &&
util["arraysEqual"](convInfo.inShape, convInfo.outShape)
) {
return x4D.clone();
}
return backend.avgPool(x4D, convInfo);
};
const inputs = { x: x4D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
let res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["d" /* AvgPool */],
attrs
);
res = cast(res, $x.dtype);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
}
return res;
}
const avgPool = Object(operation["a" /* op */])({ avgPool_ });
//# sourceMappingURL=avg_pool.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/avg_pool_3d.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 3D average pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.avgPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations Deprecated, this field will be gone in v3.0.0.
* The dilation rates:
* `[dilationDepth, dilationHeight, dilationWidth]`
* in which we sample input values across the depth, height and width
* dimensions in dilated pooling.
* Defaults to `[1, 1, 1]`. If `dilations` is a single number,
* then `dilationDepth == dilationHeight == dilationWidth`.
* If it is greater than 1, then all values of `strides` must be 1.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function avgPool3d_(
x,
filterSize,
strides,
pad,
dimRoundingMode,
dataFormat = "NDHWC",
dilations
) {
if (dilations == null) {
dilations = [1, 1, 1];
} else {
deprecationWarn("dilations is deprecated, this field will be gone in " + "v3.0.0.");
}
const $x = Object(tensor_util_env["a" /* convertToTensor */])(
x,
"x",
"avgPool3d",
"float32"
);
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
util["assert"](
x5D.rank === 5,
() => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`
);
util["assert"](
dataFormat === "NDHWC",
() =>
`Error in avgPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in avgPool3d: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in avgPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend, save) => {
if (dilations == null) {
dilations = [1, 1, 1];
}
const convInfo = computePool3DInfo(
x5D.shape,
filterSize,
strides,
dilations,
pad,
dimRoundingMode,
dataFormat
);
save([x5D]);
return backend.avgPool3d(x5D, convInfo);
};
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat, dilations };
let res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["e" /* AvgPool3D */],
attrs
);
res = cast(res, x5D.dtype);
if (reshapedTo5D) {
return res.as4D(res.shape[1], res.shape[2], res.shape[3], res.shape[4]);
}
return res;
}
const avgPool3d = Object(operation["a" /* op */])({ avgPool3d_ });
//# sourceMappingURL=avg_pool_3d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batchnorm_util.js
function xAs4D(x) {
let x4D;
if (x.rank === 0 || x.rank === 1) {
x4D = x.as4D(1, 1, 1, x.size);
} else if (x.rank === 2) {
x4D = x.as4D(1, 1, x.shape[0], x.shape[1]);
} else if (x.rank === 3) {
x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
} else {
x4D = x;
}
return x4D;
}
//# sourceMappingURL=batchnorm_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batchnorm.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Batch normalization.
*
* As described in
* [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).
*
* Mean, variance, scale, and offset can be of two shapes:
* - The same shape as the input.
* - In the common case, the depth dimension is the last dimension of x, so
* the values would be an `tf.Tensor1D` of shape [depth].
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that parameters passed are of given rank
* - `tf.batchNorm2d`
* - `tf.batchNorm3d`
* - `tf.batchNorm4d`
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
/** @doc {heading: 'Operations', subheading: 'Normalization'} */
function batchNorm_(x, mean, variance, offset, scale, varianceEpsilon) {
if (varianceEpsilon == null) {
varianceEpsilon = 0.001;
}
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "batchNorm");
const $mean = Object(tensor_util_env["a" /* convertToTensor */])(mean, "mean", "batchNorm");
const $variance = Object(tensor_util_env["a" /* convertToTensor */])(
variance,
"variance",
"batchNorm"
);
let $scale;
if (scale != null) {
$scale = Object(tensor_util_env["a" /* convertToTensor */])(scale, "scale", "batchNorm");
}
let $offset;
if (offset != null) {
$offset = Object(tensor_util_env["a" /* convertToTensor */])(
offset,
"offset",
"batchNorm"
);
}
util["assert"](
$mean.rank === $variance.rank,
() => "Batch normalization gradient requires mean and variance to have " + "equal ranks."
);
util["assert"](
$offset == null || $mean.rank === $offset.rank,
() => "Batch normalization gradient requires mean and offset to have " + "equal ranks."
);
util["assert"](
$scale == null || $mean.rank === $scale.rank,
() => "Batch normalization gradient requires mean and scale to have " + "equal ranks."
);
const x4D = xAs4D($x);
const forward = (backend, save) => {
save([x4D, $mean, $variance, $scale]);
return backend.batchNorm(
x4D,
as1DOr4D($mean),
as1DOr4D($variance),
as1DOr4D($offset),
as1DOr4D($scale),
varianceEpsilon
);
};
const inputs = {
x: x4D,
scale: $scale,
offset: $offset,
mean: $mean,
variance: $variance,
};
const attrs = { varianceEpsilon };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["F" /* FusedBatchNorm */],
attrs
);
return reshape(res, $x.shape);
}
function as1DOr4D(x) {
if (x == null) {
return null;
}
if (x.rank === 0) {
return x.as1D();
} else if (x.rank === 1) {
return x;
} else if (x.rank === 2) {
return x.as4D(1, 1, x.shape[0], x.shape[1]);
} else if (x.rank === 3) {
return x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
}
return x;
}
const batchNorm = Object(operation["a" /* op */])({ batchNorm_ });
//# sourceMappingURL=batchnorm.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batchnorm2d.js
/**
* Batch normalization, strictly for 2D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm2d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "batchNorm");
const $mean = Object(tensor_util_env["a" /* convertToTensor */])(mean, "mean", "batchNorm");
const $variance = Object(tensor_util_env["a" /* convertToTensor */])(
variance,
"variance",
"batchNorm"
);
let $scale;
if (scale != null) {
$scale = Object(tensor_util_env["a" /* convertToTensor */])(scale, "scale", "batchNorm");
}
let $offset;
if (offset != null) {
$offset = Object(tensor_util_env["a" /* convertToTensor */])(
offset,
"offset",
"batchNorm"
);
}
util["assert"](
$x.rank === 2,
() => `Error in batchNorm3D: x must be rank 3 but got rank ` + `${$x.rank}.`
);
util["assert"](
$mean.rank === 2 || $mean.rank === 1,
() =>
`Error in batchNorm2D: mean must be rank 2 or rank 1 but ` + `got rank ${$mean.rank}.`
);
util["assert"](
$variance.rank === 2 || $variance.rank === 1,
() =>
`Error in batchNorm2D: variance must be rank 2 or rank 1 ` +
`but got rank ${$variance.rank}.`
);
if ($scale != null) {
util["assert"](
$scale.rank === 2 || $scale.rank === 1,
() =>
`Error in batchNorm2D: scale must be rank 2 or rank 1 ` +
`but got rank ${$scale.rank}.`
);
}
if ($offset != null) {
util["assert"](
$offset.rank === 2 || $offset.rank === 1,
() =>
`Error in batchNorm2D: offset must be rank 2 or rank 1 ` +
`but got rank ${$offset.rank}.`
);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm2d = Object(operation["a" /* op */])({ batchNorm2d_ });
//# sourceMappingURL=batchnorm2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batchnorm3d.js
/**
* Batch normalization, strictly for 3D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm3d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "batchNorm");
const $mean = Object(tensor_util_env["a" /* convertToTensor */])(mean, "mean", "batchNorm");
const $variance = Object(tensor_util_env["a" /* convertToTensor */])(
variance,
"variance",
"batchNorm"
);
let $scale;
if (scale != null) {
$scale = Object(tensor_util_env["a" /* convertToTensor */])(scale, "scale", "batchNorm");
}
let $offset;
if (offset != null) {
$offset = Object(tensor_util_env["a" /* convertToTensor */])(
offset,
"offset",
"batchNorm"
);
}
util["assert"](
$x.rank === 3,
() => `Error in batchNorm3D: x must be rank 3 but got rank ` + `${$x.rank}.`
);
util["assert"](
$mean.rank === 3 || $mean.rank === 1,
() =>
`Error in batchNorm3D: mean must be rank 3 or rank 1 but ` + `got rank ${$mean.rank}.`
);
util["assert"](
$variance.rank === 3 || $variance.rank === 1,
() =>
`Error in batchNorm3D: variance must be rank 3 or rank 1 ` +
`but got rank ${$variance.rank}.`
);
if ($scale != null) {
util["assert"](
$scale.rank === 3 || $scale.rank === 1,
() =>
`Error in batchNorm3D: scale must be rank 3 or rank 1 ` +
`but got rank ${$scale.rank}.`
);
}
if ($offset != null) {
util["assert"](
$offset.rank === 3 || $offset.rank === 1,
() =>
`Error in batchNorm3D: offset must be rank 3 or rank 1 ` +
`but got rank ${$offset.rank}.`
);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm3d = Object(operation["a" /* op */])({ batchNorm3d_ });
//# sourceMappingURL=batchnorm3d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batchnorm4d.js
/**
* Batch normalization, strictly for 4D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm4d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "batchNorm");
const $mean = Object(tensor_util_env["a" /* convertToTensor */])(mean, "mean", "batchNorm");
const $variance = Object(tensor_util_env["a" /* convertToTensor */])(
variance,
"variance",
"batchNorm"
);
let $scale;
if (scale != null) {
$scale = Object(tensor_util_env["a" /* convertToTensor */])(scale, "scale", "batchNorm");
}
let $offset;
if (offset != null) {
$offset = Object(tensor_util_env["a" /* convertToTensor */])(
offset,
"offset",
"batchNorm"
);
}
util["assert"](
$x.rank === 4,
() => `Error in batchNorm4D: x must be rank 4 but got rank ` + `${$x.rank}.`
);
util["assert"](
$mean.rank === 4 || $mean.rank === 1,
() =>
`Error in batchNorm4D: mean must be rank 4 or rank 1 but ` + `got rank ${$mean.rank}.`
);
util["assert"](
$variance.rank === 4 || $variance.rank === 1,
() =>
`Error in batchNorm4D: variance must be rank 4 or rank 1 ` +
`but got rank ${$variance.rank}.`
);
if ($scale != null) {
util["assert"](
$scale.rank === 4 || $scale.rank === 1,
() =>
`Error in batchNorm4D: scale must be rank 4 or rank 1 ` +
`but got rank ${$scale.rank}.`
);
}
if ($offset != null) {
util["assert"](
$offset.rank === 4 || $offset.rank === 1,
() =>
`Error in batchNorm4D: offset must be rank 4 or rank 1 ` +
`but got rank ${$offset.rank}.`
);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm4d = Object(operation["a" /* op */])({ batchNorm4d_ });
//# sourceMappingURL=batchnorm4d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/clone.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a new tensor with the same values and shape as the specified
* tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
*
* x.clone().print();
* ```
*
* @param x The tensor to clone.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function clone_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "clone", null);
const forward = () =>
engine["a" /* ENGINE */].makeTensorFromDataId($x.dataId, $x.shape, $x.dtype);
// Note this op is called tf.identity in python. Hence the kernel name used
// here.
return engine["a" /* ENGINE */].runKernelFunc(
forward,
{ x: $x },
null /* grad */,
kernel_names["J" /* Identity */]
);
}
const clone = Object(operation["a" /* op */])({ clone_ });
//# sourceMappingURL=clone.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/broadcast_to.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Broadcast an array to a compatible shape NumPy-style.
*
* The tensor's shape is compared to the broadcast shape from end to beginning.
* Ones are prepended to the tensor's shape until is has the same length as
* the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is
* already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then
* the input tensor is tiled N times along that axis (using tf.tile).
*
* @param input The tensor that is to be broadcasted.
* @param shape The input is to be broadcast to this shape.
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function broadcastTo_(x, shape) {
let input = Object(tensor_util_env["a" /* convertToTensor */])(x, "broadcastTo", "x");
const xShape = input.shape;
if (shape.some((d) => !(d > 0) || d % 1 !== 0)) {
throw new Error(`broadcastTo(): Invalid broadcast shape [${shape}].`);
}
if (shape.length < input.rank) {
throw new Error(
`broadcastTo(): shape.length=${shape.length} < input.rank=${input.rank}.`
);
}
if (shape.length > input.rank) {
const newShape = input.shape.slice();
while (newShape.length < shape.length) {
newShape.unshift(1);
}
input = reshape(input, newShape);
}
const inputShape = input.shape;
const reps = Array.from(shape);
for (let i = shape.length - 1; i >= 0; i--) {
if (inputShape[i] === shape[i]) {
reps[i] = 1;
} else if (input.shape[i] !== 1) {
throw new Error(`broadcastTo(): [${xShape}] cannot be broadcast to [${shape}].`);
}
}
const axes = reps.map((n, i) => (n > 1 ? i : -1)).filter((i) => i >= 0);
if (axes.length === 0) {
return clone(input);
}
const forward = (backend) => backend.tile(input, reps);
const inputs = { x: input };
const attrs = { shape, inputShape };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["j" /* BroadcastTo */],
attrs
);
}
const broadcastTo = Object(operation["a" /* op */])({ broadcastTo_ });
//# sourceMappingURL=broadcast_to.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/complex.js
var complex = __webpack_require__(18);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/concat_1d.js
/**
* Concatenates a list of`tf.Tensor1D`s along an axis. See `concat` for details.
*
* For example, if:
* A: shape(3) = |r1, g1, b1|
* B: shape(2) = |r2, g2|
* C = tf.concat1d([A, B]) == |r1, g1, b1, r2, g2|
*
* @param tensors A list of`tf.Tensor`s to concatenate.
* @return The concatenated array.
*/
function concat1d_(tensors) {
return concat(tensors, 0 /* axis */);
}
const concat1d = Object(operation["a" /* op */])({ concat1d_ });
//# sourceMappingURL=concat_1d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/concat_2d.js
/**
* Concatenates a list of`tf.Tensor2D`s along an axis. See `concat` for details.
*
* For example, if:
* A: shape(2, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
*
* B: shape(2, 3) = | r3, g3, b3 |
* | r4, g4, b4 |
*
* C = tf.concat2d([A, B], axis)
*
* if axis = 0:
* C: shape(4, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
* | r3, g3, b3 |
* | r4, g4, b4 |
*
* if axis = 1:
* C = shape(2, 6) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
*
* @param tensors A list of `tf.Tensor`s to concatenate.
* @param axis The axis to concatenate along.
* @return The concatenated array.
*/
function concat2d_(tensors, axis) {
return concat(tensors, axis);
}
const concat2d = Object(operation["a" /* op */])({ concat2d_ });
//# sourceMappingURL=concat_2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/concat_3d.js
/**
* Concatenates a list of `tf.Tensor3D`s along an axis.
* See `concat` for details.
*
* For example, if:
* A: shape(2, 1, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
*
* B: shape(2, 1, 3) = | r3, g3, b3 |
* | r4, g4, b4 |
*
* C = tf.concat3d([A, B], axis)
*
* if axis = 0:
* C: shape(4, 1, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
* | r3, g3, b3 |
* | r4, g4, b4 |
*
* if axis = 1:
* C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
* if axis = 2:
* C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
* @param tensors A list of`tf.Tensor`s to concatenate.
* @param axis The axis to concate along.
* @return The concatenated array.
*/
function concat3d_(tensors, axis) {
return concat(tensors, axis);
}
const concat3d = Object(operation["a" /* op */])({ concat3d_ });
//# sourceMappingURL=concat_3d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/concat_4d.js
/**
* Concatenates a list of `tf.Tensor4D`s along an axis.
* See `concat` for details.
*
* @param tensors A list of `tf.Tensor`s to concatenate.
* @param axis The axis to concate along.
* @return The concatenated array.
*/
function concat4d_(tensors, axis) {
return concat(tensors, axis);
}
const concat4d = Object(operation["a" /* op */])({ concat4d_ });
//# sourceMappingURL=concat_4d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv1d.js
/**
* Computes a 1D convolution over the input x.
*
* @param x The input tensor, of rank 3 or rank 2, of shape
* `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.
* @param filter The filter, rank 3, of shape
* `[filterWidth, inDepth, outDepth]`.
* @param stride The number of entries by which the filter is moved right at
* each step.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat An optional string from "NWC", "NCW". Defaults to "NWC",
* the data is stored in the order of [batch, in_width, in_channels]. Only
* "NWC" is currently supported.
* @param dilation The dilation rate in which we sample input values in
* atrous convolution. Defaults to `1`. If it is greater than 1, then
* stride must be `1`.
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function conv1d_(x, filter, stride, pad, dataFormat = "NWC", dilation = 1, dimRoundingMode) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "conv1d");
const $filter = Object(tensor_util_env["a" /* convertToTensor */])(
filter,
"filter",
"conv1d"
);
let x3D = $x;
let reshapedTo3D = false;
if ($x.rank === 2) {
reshapedTo3D = true;
x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);
}
util["assert"](
x3D.rank === 3,
() => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`
);
util["assert"](
$filter.rank === 3,
() => `Error in conv1d: filter must be rank 3, but got rank ` + `${$filter.rank}.`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in conv1d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
util["assert"](
x3D.shape[2] === $filter.shape[1],
() =>
`Error in conv1d: depth of input (${x3D.shape[2]}) must match ` +
`input depth for filter ${$filter.shape[1]}.`
);
util["assert"](
eitherStridesOrDilationsAreOne(stride, dilation),
() =>
"Error in conv1D: Either stride or dilation must be 1. " +
`Got stride ${stride} and dilation '${dilation}'`
);
util["assert"](
dataFormat === "NWC",
() =>
`Error in conv1d: got dataFormat of ${dataFormat} but only NWC is currently supported.`
);
const filter4D = reshape($filter, [
1,
$filter.shape[0],
$filter.shape[1],
$filter.shape[2],
]);
const input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);
const strides = [1, stride];
const dilations = [1, dilation];
const conv2dDataFormat = "NHWC";
const res = conv2d(
input4D,
filter4D,
strides,
pad,
conv2dDataFormat,
dilations,
dimRoundingMode
);
if (reshapedTo3D) {
return reshape(res, [res.shape[2], res.shape[3]]);
}
return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]);
}
const conv1d = Object(operation["a" /* op */])({ conv1d_ });
//# sourceMappingURL=conv1d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv2d_transpose.js
/**
* Computes the transposed 2D convolution of an image, also known as a
* deconvolution.
*
* @param x The input image, of rank 4 or rank 3, of shape
* `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 4 or rank 3:
* `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.
* @param strides The strides of the original convolution:
* `[strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function conv2dTranspose_(x, filter, outputShape, strides, pad, dimRoundingMode) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "conv2dTranspose");
const $filter = Object(tensor_util_env["a" /* convertToTensor */])(
filter,
"filter",
"conv2dTranspose"
);
return conv2DBackpropInput(outputShape, $x, $filter, strides, pad, "NHWC", dimRoundingMode);
}
const conv2dTranspose = Object(operation["a" /* op */])({ conv2dTranspose_ });
//# sourceMappingURL=conv2d_transpose.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv3d.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes a 3D convolution over the input x.
*
* @param x The input tensor, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, channels]`. If rank 4,
* batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.
* inChannels must match between input and filter.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat: An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations The dilation rates: `[dilationDepth, dilationHeight,
* dilationWidth]` in which we sample input values across the height
* and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.
* If `dilations` is a single number, then
* `dilationDepth == dilationHeight == dilationWidth`. If it is greater
* than 1, then all values of `strides` must be 1.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function conv3d_(x, filter, strides, pad, dataFormat = "NDHWC", dilations = [1, 1, 1]) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "conv3d");
const $filter = Object(tensor_util_env["a" /* convertToTensor */])(
filter,
"filter",
"conv3d"
);
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
util["assert"](
x5D.rank === 5,
() => `Error in conv3d: input must be rank 5, but got rank ${x5D.rank}.`
);
util["assert"](
$filter.rank === 5,
() => `Error in conv3d: filter must be rank 5, but got rank ` + `${$filter.rank}.`
);
util["assert"](
x5D.shape[4] === $filter.shape[3],
() =>
`Error in conv3d: depth of input (${x5D.shape[4]}) must match ` +
`input depth for filter ${$filter.shape[3]}.`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in conv3D: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
util["assert"](
dataFormat === "NDHWC",
() =>
`Error in conv3d: got dataFormat of ${dataFormat} but only NDHWC is currently supported.`
);
const forward = (backend, save) => {
const convInfo = computeConv3DInfo(x5D.shape, $filter.shape, strides, dilations, pad);
const res = backend.conv3d(x5D, $filter, convInfo);
save([x5D, $filter]);
return res;
};
const inputs = { x: x5D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["p" /* Conv3D */],
attrs
);
if (reshapedTo5D) {
return res.as4D(res.shape[1], res.shape[2], res.shape[3], res.shape[4]);
}
return res;
}
const conv3d = Object(operation["a" /* op */])({ conv3d_ });
//# sourceMappingURL=conv3d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv3d_transpose.js
/**
* Computes the transposed 3D convolution of a volume, also known as a
* deconvolution.
*
* @param x The input image, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, inDepth]`. If rank 4, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[depth, filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 5 or rank 4:
* `[batch, depth, height, width, outDepth]`. If rank 3, batch of 1 is
* assumed.
* @param strides The strides of the original convolution:
* `[strideDepth, strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function conv3dTranspose_(x, filter, outputShape, strides, pad) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "conv3dTranspose");
const $filter = Object(tensor_util_env["a" /* convertToTensor */])(
filter,
"filter",
"conv3dTranspose"
);
return conv3DBackpropInput(outputShape, $x, $filter, strides, pad);
}
const conv3dTranspose = Object(operation["a" /* op */])({ conv3dTranspose_ });
//# sourceMappingURL=conv3d_transpose.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/depth_to_space.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Rearranges data from depth into blocks of spatial data. More specifically,
* this op outputs a copy of the input tensor where values from the `depth`
* dimension are moved in spatial blocks to the `height` and `width` dimensions.
* The attr `blockSize` indicates the input block size and how the data is
* moved.
*
* - Chunks of data of size `blockSize * blockSize` from depth are rearranged
* into non-overlapping blocks of size `blockSize x blockSize`
*
* - The width the output tensor is `inputWidth * blockSize`, whereas the
* height is `inputHeight * blockSize`
*
* - The Y, X coordinates within each block of the output image are determined
* by the high order component of the input channel index
*
* - The depth of the input tensor must be divisible by `blockSize *
* blockSize`
*
* The `dataFormat` attr specifies the layout of the input and output tensors
* with the following options: "NHWC": [ `batch, height, width, channels` ]
* "NCHW": [ `batch, channels, height, width` ]
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);
* const blockSize = 2;
* const dataFormat = "NHWC";
*
* tf.depthToSpace(x, blockSize, dataFormat).print();
* ```
*
* @param x The input tensor of rank 4
* @param blockSIze An `int` that is `>= 2`. The size of the spatial block
* @param dataFormat An optional string from: "NHWC", "NCHW". Defaults to "NHWC"
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function depthToSpace_(x, blockSize, dataFormat = "NHWC") {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "depthToSpace");
const inputHeight = dataFormat === "NHWC" ? $x.shape[1] : $x.shape[2];
const inputWidth = dataFormat === "NHWC" ? $x.shape[2] : $x.shape[3];
const inputDepth = dataFormat === "NHWC" ? $x.shape[3] : $x.shape[1];
util["assert"](
inputHeight * blockSize >= 0,
() => `Negative dimension size caused by overflow when multiplying
${inputHeight} and ${blockSize} for depthToSpace with input shape
${$x.shape}`
);
util["assert"](
inputWidth * blockSize >= 0,
() => `Negative dimension size caused by overflow when multiplying
${inputWidth} and ${blockSize} for depthToSpace with input shape
${$x.shape}`
);
util["assert"](
inputDepth % (blockSize * blockSize) === 0,
() =>
`Dimension size must be evenly divisible by ${
blockSize * blockSize
} but is ${inputDepth} for depthToSpace with input shape ${$x.shape}`
);
const forward = (backend) => backend.depthToSpace($x, blockSize, dataFormat);
const inputs = { x: $x };
const attrs = { blockSize, dataFormat };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["t" /* DepthToSpace */],
attrs
);
}
const depthToSpace = Object(operation["a" /* op */])({ depthToSpace_ });
//# sourceMappingURL=depth_to_space.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/depthwise_conv2d.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Depthwise 2D convolution.
*
* Given a 4D `input` array and a `filter` array of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing
* `inChannels` convolutional filters of depth 1, this op applies a
* different filter to each input channel (expanding from 1 channel to
* `channelMultiplier` channels for each), then concatenates the results
* together. The output has `inChannels * channelMultiplier` channels.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function depthwiseConv2d_(
x,
filter,
strides,
pad,
dataFormat = "NHWC",
dilations = [1, 1],
dimRoundingMode
) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "depthwiseConv2d");
const $filter = Object(tensor_util_env["a" /* convertToTensor */])(
filter,
"filter",
"depthwiseConv2d"
);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
util["assert"](
x4D.rank === 4,
() => `Error in depthwiseConv2d: input must be rank 4, but got ` + `rank ${x4D.rank}.`
);
util["assert"](
$filter.rank === 4,
() =>
`Error in depthwiseConv2d: filter must be rank 4, but got rank ` + `${$filter.rank}.`
);
util["assert"](
x4D.shape[3] === $filter.shape[2],
() =>
`Error in depthwiseConv2d: number of input channels ` +
`(${x4D.shape[3]}) must match the inChannels dimension in ` +
`filter ${$filter.shape[2]}.`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in depthwiseConv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend, save) => {
if (dilations == null) {
dilations = [1, 1];
}
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in depthwiseConv2d: Either strides or dilations must be " +
`1. Got strides ${strides} and dilations '${dilations}'`
);
const convInfo = computeConv2DInfo(
x4D.shape,
$filter.shape,
strides,
dilations,
pad,
dimRoundingMode,
true /* depthwise */
);
const res = backend.depthwiseConv2D(x4D, $filter, convInfo);
save([x4D, $filter]);
return res;
};
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations, dimRoundingMode };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["u" /* DepthwiseConv2dNative */],
attrs
);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const depthwiseConv2d = Object(operation["a" /* op */])({ depthwiseConv2d_ });
//# sourceMappingURL=depthwise_conv2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/diag.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns a diagonal tensor with a given diagonal values.
*
* Given a diagonal, this operation returns a tensor with the diagonal and
* everything else padded with zeros.
*
* Assume the input has dimensions `[D1,..., Dk]`, then the output is a tensor
* of rank 2k with dimensions `[D1,..., Dk, D1,..., Dk]`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* tf.diag(x).print()
* ```
* ```js
* const x = tf.tensor1d([1, 2, 3, 4, 5, 6, 6, 8], [4, 2])
*
* tf.diag(x).print()
* ```
* @param x The input tensor.
*/
function diag_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "diag").flatten();
const forward = (backend) => {
const result = backend.diag($x);
const outShape = [...x.shape, ...x.shape];
return reshape(result, outShape);
};
const inputs = { x: $x };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["x" /* Diag */]
);
}
const diag = Object(operation["a" /* op */])({ diag_ });
//# sourceMappingURL=diag.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/div_no_nan.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting. Return 0
* if denominator is 0.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
* const c = tf.tensor1d([0, 0, 0, 0]);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
* const c = tf.scalar(0);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function divNoNan_(a, b) {
// TODO: Make this into its own kernel.
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "div");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "div");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
const divResult = div($a, $b);
const zeros = Object(tensor_ops["o" /* zerosLike */])(divResult);
const bEqualsZero = $b.equal(zeros);
return where(bEqualsZero, zeros, divResult);
}
const divNoNan = Object(operation["a" /* op */])({ divNoNan_ });
//# sourceMappingURL=div_no_nan.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/dot.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the dot product of two matrices and/or vectors, `t1` and `t2`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor2d([[1, 2], [3, 4]]);
* const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
*
* a.dot(b).print(); // or tf.dot(a, b)
* b.dot(a).print();
* b.dot(c).print();
* ```
* @param t1 The first tensor in the dot operation.
* @param t2 The second tensor in the dot operation.
*/
/** @doc {heading: 'Operations', subheading: 'Matrices'} */
function dot_(t1, t2) {
const $t1 = Object(tensor_util_env["a" /* convertToTensor */])(t1, "t1", "dot");
const $t2 = Object(tensor_util_env["a" /* convertToTensor */])(t2, "t2", "dot");
util["assert"](
($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2),
() =>
`Error in dot: inputs must all be rank 1 or 2, but got ranks ` +
`${$t1.rank} and ${$t2.rank}.`
);
const t1Inner = $t1.rank === 1 ? $t1.size : $t1.shape[1];
const t2Inner = $t2.rank === 1 ? $t2.size : $t2.shape[0];
util["assert"](
t1Inner === t2Inner,
() =>
`Error in dot: inner dimensions of inputs must match, but got ` +
`${t1Inner} and ${t2Inner}.`
);
if ($t1.rank === 1 && $t2.rank === 1) {
const t12D = reshape($t1, [1, -1]);
const t22D = reshape($t2, [-1, 1]);
const t1t2 = matMul(t12D, t22D);
return reshape(t1t2, []);
} else if ($t1.rank === 1 && $t2.rank === 2) {
const t12D = reshape($t1, [1, -1]);
const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
const t1t2 = matMul(t12D, t22D);
return reshape(t1t2, [t1t2.size]);
} else if ($t1.rank === 2 && $t2.rank === 1) {
const t22D = reshape($t2, [-1, 1]);
const t1t2 = matMul($t1, t22D);
return reshape(t1t2, [t1t2.size]);
} else {
const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
const t1t2 = matMul($t1, t22D);
return t1t2;
}
}
const dot = Object(operation["a" /* op */])({ dot_ });
//# sourceMappingURL=dot.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/elu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes exponential linear element-wise: `x > 0 ? e ^ x - 1 : 0`.
*
* ```js
* const x = tf.tensor1d([-1, 1, -3, 2]);
*
* x.elu().print(); // or tf.elu(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function elu_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "elu");
const forward = (backend, save) => {
const y = backend.elu($x);
save([y]);
return y;
};
const inputs = { x: $x };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["z" /* Elu */]
);
}
const elu = Object(operation["a" /* op */])({ elu_ });
//# sourceMappingURL=elu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/equal.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a == b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.equal(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function equal_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "equal");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "equal");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend) => backend.equal($a, $b);
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null,
kernel_names["B" /* Equal */]
);
}
const equal = Object(operation["a" /* op */])({ equal_ });
//# sourceMappingURL=equal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/eye.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Create an identity matrix.
*
* @param numRows Number of rows.
* @param numColumns Number of columns. Defaults to `numRows`.
* @param batchShape If provided, will add the batch shape to the beginning
* of the shape of the returned `tf.Tensor` by repeating the identity
* matrix.
* @param dtype Data type.
* @returns Identity matrix of the specified size and data type, possibly
* with batch repetition if `batchShape` is specified.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function eye_(numRows, numColumns, batchShape, dtype = "float32") {
if (numColumns == null) {
numColumns = numRows;
}
const buff = array_ops_buffer([numRows, numColumns], dtype);
const n = numRows <= numColumns ? numRows : numColumns;
for (let i = 0; i < n; ++i) {
buff.set(1, i, i);
}
const out = buff.toTensor().as2D(numRows, numColumns);
if (batchShape == null) {
return out;
} else {
if (batchShape.length === 1) {
return tile(expandDims(out, 0), [batchShape[0], 1, 1]);
} else if (batchShape.length === 2) {
return tile(expandDims(expandDims(out, 0), 0), [batchShape[0], batchShape[1], 1, 1]);
} else if (batchShape.length === 3) {
return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [
batchShape[0],
batchShape[1],
batchShape[2],
1,
1,
]);
} else {
throw new Error(
`eye() currently supports only 1D and 2D ` +
// tslint:disable-next-line:no-any
`batchShapes, but received ${batchShape.length}D.`
);
}
}
}
const eye = Object(operation["a" /* op */])({ eye_ });
//# sourceMappingURL=eye.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/fill.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` filled with a scalar value.
*
* ```js
* tf.fill([2, 2], 4).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param value The scalar value to fill the tensor with.
* @param dtype The type of an element in the resulting tensor. Defaults to
* 'float'.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function fill(shape, value, dtype) {
const attrs = { shape, value, dtype };
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.fill(shape, value, dtype),
{},
null,
kernel_names["C" /* Fill */],
attrs
);
}
//# sourceMappingURL=fill.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/imag.js
var imag = __webpack_require__(25);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/maximum.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the max of a and b (`a > b ? a : b`) element-wise.
* Supports broadcasting.
*
* We also expose `tf.maximumStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.maximum(b).print(); // or tf.maximum(a, b)
* ```
*
* ```js
* // Broadcast maximum a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.maximum(b).print(); // or tf.maximum(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function maximum_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "maximum");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "maximum");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
if ($a.dtype === "bool") {
$a = cast($a, "int32");
$b = cast($b, "int32");
}
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend, save) => {
const res = backend.maximum($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["V" /* Maximum */]
);
}
const maximum = Object(operation["a" /* op */])({ maximum_ });
//# sourceMappingURL=maximum.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/leaky_relu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes leaky rectified linear element-wise.
*
* See
* [http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf](
* http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf)
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.leakyRelu(0.1).print(); // or tf.leakyRelu(x, 0.1)
* ```
* @param x The input tensor.
* @param alpha The scaling factor for negative values, defaults to 0.2.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function leakyRelu_(x, alpha = 0.2) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "leakyRelu");
return maximum(mul(Object(tensor_ops["e" /* scalar */])(alpha), $x), $x);
}
const leakyRelu = Object(operation["a" /* op */])({ leakyRelu_ });
//# sourceMappingURL=leaky_relu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/local_response_normalization.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Normalizes the activation of a local neighborhood across or within
* channels.
*
* @param x The input tensor. The 4-D input tensor is treated as a 3-D array
* of 1D vectors (along the last dimension), and each vector is
* normalized independently.
* @param depthRadius The number of adjacent channels in the 1D normalization
* window.
* @param bias A constant bias term for the basis.
* @param alpha A scale factor, usually positive.
* @param beta An exponent.
*/
/** @doc {heading: 'Operations', subheading: 'Normalization'} */
function localResponseNormalization_(x, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(
x,
"x",
"localResponseNormalization"
);
util["assert"](
$x.rank === 4 || $x.rank === 3,
() => `Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${$x.rank}.`
);
util["assert"](
util["isInt"](depthRadius),
() =>
`Error in localResponseNormalization: depthRadius must be an ` +
`integer but got depthRadius ${depthRadius}.`
);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
const forward = (backend, save) => {
const y = backend.localResponseNormalization4D(x4D, depthRadius, bias, alpha, beta);
save([x4D, y]);
return y;
};
const inputs = { x: x4D };
const attrs = { depthRadius, bias, alpha, beta };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["L" /* LRN */],
attrs
);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
} else {
return res;
}
}
const localResponseNormalization = Object(operation["a" /* op */])({
localResponseNormalization_,
});
//# sourceMappingURL=local_response_normalization.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the maximum of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.max().print(); // or tf.max(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.max(axis).print(); // or tf.max(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*/
/** @doc {heading: 'Operations', subheading: 'Reduction'} */
function max_(x, axis = null, keepDims = false) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "max");
const forward = (backend, save) => {
const origAxes = util["parseAxisParam"](axis, $x.shape);
let axes = origAxes;
const permutedAxes = getAxesPermutation(axes, $x.rank);
let maxInput = $x;
if (permutedAxes != null) {
maxInput = transpose($x, permutedAxes);
axes = getInnerMostAxes(axes.length, maxInput.rank);
}
const y = backend.max(maxInput, axes);
save([$x, y]);
if (permutedAxes != null) {
backend.disposeData(maxInput.dataId);
}
return y;
};
const inputs = { x: $x };
const attrs = { reductionIndices: axis, keepDims };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["P" /* Max */],
attrs
);
if (keepDims) {
return reshape(
res,
expandShapeToKeepDim(res.shape, util["parseAxisParam"](axis, $x.shape))
);
}
return res;
}
const max_max = Object(operation["a" /* op */])({ max_ });
//# sourceMappingURL=max.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max_pool.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D max pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
function maxPool_(x, filterSize, strides, pad, dimRoundingMode) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "maxPool");
const dilations = 1;
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
util["assert"](
x4D.rank === 4,
() => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in maxPool: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in maxPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend, save) => {
const convInfo = computePool2DInfo(
x4D.shape,
filterSize,
strides,
1 /* dilations */,
pad,
dimRoundingMode
);
let y;
if (
convInfo.filterWidth === 1 &&
convInfo.filterHeight === 1 &&
util["arraysEqual"](convInfo.inShape, convInfo.outShape)
) {
y = x4D.clone();
} else {
y = backend.maxPool(x4D, convInfo);
}
save([x4D, y]);
return y;
};
const inputs = { x: x4D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["Q" /* MaxPool */],
attrs
);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const maxPool = Object(operation["a" /* op */])({ maxPool_ });
//# sourceMappingURL=max_pool.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max_pool_3d.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 3D max pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.maxPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations Deprecated, this field will be gone in v3.0.0.
* The dilation rates: `[dilationDepth, dilationHeight, dilationWidth]`
* in which we sample input values across the depth, height and width
* dimensions in dilated pooling.
* Defaults to `[1, 1, 1]`. If `dilations` is a single number,
* then `dilationDepth == dilationHeight == dilationWidth`.
* If it is greater than 1, then all values of `strides` must be 1.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function maxPool3d_(
x,
filterSize = [1, 1, 1],
strides,
pad,
dimRoundingMode,
dataFormat = "NDHWC",
dilations
) {
if (dilations == null) {
dilations = [1, 1, 1];
} else {
deprecationWarn("dilations is deprecated, this field will be gone in " + "v3.0.0.");
}
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "maxPool3d");
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = $x.as5D(1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]);
}
util["assert"](
x5D.rank === 5,
() => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`
);
util["assert"](
dataFormat === "NDHWC",
() =>
`Error in maxPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in maxPool3d: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in maxPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const forward = (backend, save) => {
if (dilations == null) {
dilations = [1, 1, 1];
}
const convInfo = computePool3DInfo(
x5D.shape,
filterSize,
strides,
dilations,
pad,
dimRoundingMode,
dataFormat
);
const y = backend.maxPool3d(x5D, convInfo);
save([x5D, y]);
return y;
};
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat, dilations };
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["R" /* MaxPool3D */],
attrs
);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const maxPool3d = Object(operation["a" /* op */])({ maxPool3d_ });
//# sourceMappingURL=max_pool_3d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max_pool_with_argmax.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D max pooling of an image with Argmax index.
* The indices in argmax are flattened, so that a maximum value at position `[b,
* y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if
* include_batch_in_index is False; `((b * height + y) * width + x) * channels
* +c` if include_batch_in_index is True.
*
* The indices returned are always in `[0, height) x [0, width)` before
* flattening.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param includeBatchIndex Defaults to False. Whether to include batch
* dimension in flattened index of argmax.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function maxPoolWithArgmax_(x, filterSize, strides, pad, includeBatchInIndex = false) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "maxPoolWithArgmax");
const inputs = { x: $x };
const attrs = { filterSize, strides, pad, includeBatchInIndex };
const result = engine["a" /* ENGINE */].runKernel(
kernel_names["U" /* MaxPoolWithArgmax */],
inputs,
attrs
);
return { result: result[0], indexes: result[1] };
}
const maxPoolWithArgmax = Object(operation["a" /* op */])({ maxPoolWithArgmax_ });
//# sourceMappingURL=max_pool_with_argmax.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/minimum.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the min of a and b (`a < b ? a : b`) element-wise.
* Supports broadcasting.
*
* We also expose `minimumStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.minimum(b).print(); // or tf.minimum(a, b)
* ```
*
* ```js
* // Broadcast minimum a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.minimum(b).print(); // or tf.minimum(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function minimum_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "minimum");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "minimum");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
if ($a.dtype === "bool") {
$a = cast($a, "int32");
$b = cast($b, "int32");
}
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend, save) => {
const res = backend.minimum($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["W" /* Minimum */]
);
}
const minimum = Object(operation["a" /* op */])({ minimum_ });
//# sourceMappingURL=minimum.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/mod.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the mod of a and b element-wise.
* `floor(x / y) * y + mod(x, y) = x`
* Supports broadcasting.
*
* We also expose `tf.modStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.mod(b).print(); // or tf.mod(a, b)
* ```
*
* ```js
* // Broadcast a mod b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.mod(b).print(); // or tf.mod(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function mod_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "mod");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "mod");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
const forward = (backend, save) => {
const res = backend.mod($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["X" /* Mod */]
);
}
const mod = Object(operation["a" /* op */])({ mod_ });
//# sourceMappingURL=mod.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/multinomial.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values drawn from a multinomial distribution.
*
* ```js
* const probs = tf.tensor([.75, .25]);
* tf.multinomial(probs, 3).print();
* ```
*
* @param logits 1D array with unnormalized log-probabilities, or
* 2D array of shape `[batchSize, numOutcomes]`. See the `normalized`
* parameter.
* @param numSamples Number of samples to draw for each row slice.
* @param seed The seed number.
* @param normalized Whether the provided `logits` are normalized true
* probabilities (sum to 1). Defaults to false.
* @return 1D array of shape `[numSamples]`, or 2D array of shape
* `[batchSize, numSamples]`, depending on the rank of the input.
*/
/** @doc {heading: 'Tensors', subheading: 'Random'} */
function multinomial_(logits, numSamples, seed, normalized = false) {
const $logits = Object(tensor_util_env["a" /* convertToTensor */])(
logits,
"logits",
"multinomial"
);
const numOutcomes = $logits.size;
const origRank = $logits.rank;
if (numOutcomes < 2) {
throw new Error(
`Error in multinomial: you need at least 2 outcomes, but got ` + `${numOutcomes}.`
);
}
if (origRank > 2) {
throw new Error(`Rank of probabilities must be 1 or 2, but is ${origRank}`);
}
seed = seed || Math.random();
const logits2D = origRank === 1 ? $logits.as2D(1, -1) : $logits;
const res = engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.multinomial(logits2D, normalized, numSamples, seed),
{ logits2D }
);
return origRank === 1 ? res.as1D() : res;
}
const multinomial = Object(operation["a" /* op */])({ multinomial_ });
//# sourceMappingURL=multinomial.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/not_equal.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a != b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([0, 2, 3]);
*
* a.notEqual(b).print();
* ```
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Logical'} */
function notEqual_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "notEqual");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "notEqual");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend) => backend.notEqual($a, $b);
const inputs = { a: $a, b: $b };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["bb" /* NotEqual */]
);
}
const notEqual = Object(operation["a" /* op */])({ notEqual_ });
//# sourceMappingURL=not_equal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/outer_product.js
/**
* Computes the outer product of two vectors, `v1` and `v2`.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([3, 4, 5]);
*
* tf.outerProduct(a, b).print();
* ```
* @param v1 The first vector in the outer product operation.
* @param v2 The second vector in the outer product operation.
*/
/** @doc {heading: 'Operations', subheading: 'Matrices'} */
function outerProduct_(v1, v2) {
const $v1 = Object(tensor_util_env["a" /* convertToTensor */])(v1, "v1", "outerProduct");
const $v2 = Object(tensor_util_env["a" /* convertToTensor */])(v2, "v2", "outerProduct");
util["assert"](
$v1.rank === 1 && $v2.rank === 1,
() =>
`Error in outerProduct: inputs must be rank 1, but got ranks ` +
`${$v1.rank} and ${$v2.rank}.`
);
const v12D = reshape($v1, [-1, 1]);
const v22D = reshape($v2, [1, -1]);
return matMul(v12D, v22D);
}
const outerProduct = Object(operation["a" /* op */])({ outerProduct_ });
//# sourceMappingURL=outer_product.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pad1d.js
/**
* Pads a `tf.Tensor1D` with a given value and paddings. See `pad` for details.
*/
function pad1d_(x, paddings, constantValue = 0) {
Object(util["assert"])(
paddings.length === 2,
() => "Invalid number of paddings. Must be length of 2."
);
return pad_pad(x, [paddings], constantValue);
}
const pad1d = Object(operation["a" /* op */])({ pad1d_ });
//# sourceMappingURL=pad1d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pad2d.js
/**
* Pads a `tf.Tensor2D` with a given value and paddings. See `pad` for details.
*/
function pad2d_(x, paddings, constantValue = 0) {
Object(util["assert"])(
paddings.length === 2 && paddings[0].length === 2 && paddings[1].length === 2,
() => "Invalid number of paddings. Must be length of 2 each."
);
return pad_pad(x, paddings, constantValue);
}
const pad2d = Object(operation["a" /* op */])({ pad2d_ });
//# sourceMappingURL=pad2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pad3d.js
/**
* Pads a `tf.Tensor3D` with a given value and paddings. See `pad` for details.
*/
function pad3d_(x, paddings, constantValue = 0) {
Object(util["assert"])(
paddings.length === 3 &&
paddings[0].length === 2 &&
paddings[1].length === 2 &&
paddings[2].length === 2,
() => "Invalid number of paddings. Must be length of 2 each."
);
return pad_pad(x, paddings, constantValue);
}
const pad3d = Object(operation["a" /* op */])({ pad3d_ });
//# sourceMappingURL=pad3d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pad4d.js
/**
* Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details.
*/
function pad4d_(x, paddings, constantValue = 0) {
Object(util["assert"])(
paddings.length === 4 &&
paddings[0].length === 2 &&
paddings[1].length === 2 &&
paddings[2].length === 2 &&
paddings[3].length === 2,
() => "Invalid number of paddings. Must be length of 2 each."
);
return pad_pad(x, paddings, constantValue);
}
const pad4d = Object(operation["a" /* op */])({ pad4d_ });
//# sourceMappingURL=pad4d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pool.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Performs an N-D pooling operation
*
* @param input The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param windowShape The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param poolingType The type of pooling, either 'max' or 'avg'.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function pool_(input, windowShape, poolingType, pad, dilations, strides) {
if (dilations == null) {
dilations = [1, 1];
}
if (strides == null) {
strides = 1;
}
if (pad === 0) {
pad = "valid";
}
const $x = Object(tensor_util_env["a" /* convertToTensor */])(input, "x", "maxPool");
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in pool: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
const convInfo = computePool2DInfo(x4D.shape, windowShape, strides, dilations, pad);
const dilation = [convInfo.dilationHeight, convInfo.dilationWidth];
// The following implementation does batchToSpace(pool(spaceToBatch(x)))
// whenever dilation > 1 since the TF kernels do not support dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037
let basePadding;
if (pad === "same") {
basePadding = withSpaceToBatchBasePaddings(
[convInfo.filterHeight, convInfo.filterWidth],
dilation
);
} else {
basePadding = [
[0, 0],
[0, 0],
];
}
const isDilationOne = dilation[0] === 1 && dilation[1] === 1;
const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings(
[convInfo.inHeight, convInfo.inWidth],
dilation,
basePadding
);
const convertedPad = isDilationOne ? pad : "valid";
const convertedX = isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);
const forwardOp =
poolingType === "avg"
? () => avgPool(convertedX, windowShape, strides, convertedPad)
: () => maxPool(convertedX, windowShape, strides, convertedPad);
const y = forwardOp();
const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
// Helper function to compute crops and paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184
function requiredSpaceToBatchPaddings(inputShape, blockShape, basePadding) {
const padStart = basePadding.map((b) => b[0]);
const origPadEnd = basePadding.map((b) => b[1]);
const fullInputShape = inputShape.concat(padStart, origPadEnd);
const padEndExtra = blockShape.map((b, i) => (b - (fullInputShape[i] % b)) % b);
const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);
const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);
const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);
return [paddings, crops];
}
// Helper function to compute base paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524
function withSpaceToBatchBasePaddings(filterShape, dilation) {
// Spatial dimensions of the filters and the upsampled filters in which we
// introduce (rate - 1) zeros between consecutive filter values.
const dilatedFilterShape = filterShape.map((s, i) => {
return s + (s - 1) * (dilation[i] - 1);
});
const padExtraShape = dilatedFilterShape.map((s) => s - 1);
// When padding is odd, we pad more at end, following the same
// convention as conv2d.
const padExtraStart = padExtraShape.map((s) => Math.floor(s / 2));
const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);
return padExtraShape.map((_, i) => {
return [padExtraStart[i], padExtraEnd[i]];
});
}
const pool = Object(operation["a" /* op */])({ pool_ });
//# sourceMappingURL=pool.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/prelu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes leaky rectified linear element-wise with parametric alphas.
*
* `x < 0 ? alpha * x : f(x) = x`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
* const alpha = tf.scalar(0.1);
*
* x.prelu(alpha).print(); // or tf.prelu(x, alpha)
* ```
* @param x The input tensor.
* @param alpha Scaling factor for negative values.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function prelu_(x, alpha) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "prelu");
const $alpha = Object(tensor_util_env["a" /* convertToTensor */])(alpha, "alpha", "prelu");
const forward = (backend, save) => {
const res = backend.prelu($x, $alpha);
save([$x, $alpha]);
return res;
};
const inputs = { x: $x, alpha: $alpha };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["gb" /* Prelu */]
);
}
const prelu = Object(operation["a" /* op */])({ prelu_ });
//# sourceMappingURL=prelu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/rand.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a random number generator
* function defined by the user.
*
* @param shape An array of integers defining the output tensor shape.
* @param randFunction A random number generator function which is called
* for each element in the output tensor.
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*/
function rand_(shape, randFunction, dtype) {
const size = Object(util["sizeFromShape"])(shape);
let values = null;
if (dtype == null || dtype === "float32") {
values = new Float32Array(size);
} else if (dtype === "int32") {
values = new Int32Array(size);
} else if (dtype === "bool") {
values = new Uint8Array(size);
} else {
throw new Error(`Unknown data type ${dtype}`);
}
for (let i = 0; i < size; i++) {
values[i] = randFunction();
}
return engine["a" /* ENGINE */].makeTensor(values, shape, dtype);
}
const rand = Object(operation["a" /* op */])({ rand_ });
//# sourceMappingURL=rand.js.map
// EXTERNAL MODULE: ./node_modules/seedrandom/index.js
var seedrandom = __webpack_require__(20);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/rand_util.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// https://en.wikipedia.org/wiki/Marsaglia_polar_method
class rand_util_MPRandGauss {
constructor(mean, stdDeviation, dtype, truncated, seed) {
this.mean = mean;
this.stdDev = stdDeviation;
this.dtype = dtype;
this.nextVal = NaN;
this.truncated = truncated;
if (this.truncated) {
this.upper = this.mean + this.stdDev * 2;
this.lower = this.mean - this.stdDev * 2;
}
const seedValue = seed ? seed : Math.random();
this.random = seedrandom["alea"](seedValue.toString());
}
/** Returns next sample from a Gaussian distribution. */
nextValue() {
if (!isNaN(this.nextVal)) {
const value = this.nextVal;
this.nextVal = NaN;
return value;
}
let resultX, resultY;
let isValid = false;
while (!isValid) {
let v1, v2, s;
do {
v1 = 2 * this.random() - 1;
v2 = 2 * this.random() - 1;
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s === 0);
const mul = Math.sqrt((-2.0 * Math.log(s)) / s);
resultX = this.mean + this.stdDev * v1 * mul;
resultY = this.mean + this.stdDev * v2 * mul;
if (!this.truncated || this.isValidTruncated(resultX)) {
isValid = true;
}
}
if (!this.truncated || this.isValidTruncated(resultY)) {
this.nextVal = this.convertValue(resultY);
}
return this.convertValue(resultX);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(value) {
if (this.dtype == null || this.dtype === "float32") {
return value;
}
return Math.round(value);
}
/** Returns true if less than 2-standard-deviations from the mean. */
isValidTruncated(value) {
return value <= this.upper && value >= this.lower;
}
}
// Marsaglia, George, and Wai Wan Tsang. 2000. "A Simple Method for Generating
// Gamma Variables."
class rand_util_RandGamma {
constructor(alpha, beta, dtype, seed) {
this.alpha = alpha;
this.beta = 1 / beta; // convert rate to scale parameter
this.dtype = dtype;
const seedValue = seed ? seed : Math.random();
this.randu = seedrandom["alea"](seedValue.toString());
this.randn = new rand_util_MPRandGauss(0, 1, dtype, false, this.randu());
if (alpha < 1) {
this.d = alpha + 2 / 3;
} else {
this.d = alpha - 1 / 3;
}
this.c = 1 / Math.sqrt(9 * this.d);
}
/** Returns next sample from a gamma distribution. */
nextValue() {
let x2, v0, v1, x, u, v;
while (true) {
do {
x = this.randn.nextValue();
v = 1 + this.c * x;
} while (v <= 0);
v *= v * v;
x2 = x * x;
v0 = 1 - 0.331 * x2 * x2;
v1 = 0.5 * x2 + this.d * (1 - v + Math.log(v));
u = this.randu();
if (u < v0 || Math.log(u) < v1) {
break;
}
}
v = (1 / this.beta) * this.d * v;
if (this.alpha < 1) {
v *= Math.pow(this.randu(), 1 / this.alpha);
}
return this.convertValue(v);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(value) {
if (this.dtype === "float32") {
return value;
}
return Math.round(value);
}
}
class rand_util_UniformRandom {
constructor(min = 0, max = 1, dtype, seed) {
/** Handles proper rounding for non floating point numbers. */
this.canReturnFloat = () => this.dtype == null || this.dtype === "float32";
this.min = min;
this.range = max - min;
this.dtype = dtype;
if (seed == null) {
seed = Math.random();
}
if (typeof seed === "number") {
seed = seed.toString();
}
if (!this.canReturnFloat() && this.range <= 1) {
throw new Error(`The difference between ${min} - ${max} <= 1 and dtype is not float`);
}
this.random = seedrandom["alea"](seed);
}
convertValue(value) {
if (this.canReturnFloat()) {
return value;
}
return Math.round(value);
}
nextValue() {
return this.convertValue(this.min + this.range * this.random());
}
}
function jarqueBeraNormalityTest(values) {
// https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test
const n = values.length;
const s = skewness(values);
const k = kurtosis(values);
const jb = (n / 6) * (Math.pow(s, 2) + 0.25 * Math.pow(k - 3, 2));
// JB test requires 2-degress of freedom from Chi-Square @ 0.95:
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm
const CHI_SQUARE_2DEG = 5.991;
if (jb > CHI_SQUARE_2DEG) {
throw new Error(`Invalid p-value for JB: ${jb}`);
}
}
function expectArrayInMeanStdRange(actual, expectedMean, expectedStdDev, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
const actualMean = rand_util_mean(actual);
expectNumbersClose(actualMean, expectedMean, epsilon);
expectNumbersClose(standardDeviation(actual, actualMean), expectedStdDev, epsilon);
}
function rand_util_mean(values) {
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
}
return sum / values.length;
}
function standardDeviation(values, mean) {
let squareDiffSum = 0;
for (let i = 0; i < values.length; i++) {
const diff = values[i] - mean;
squareDiffSum += diff * diff;
}
return Math.sqrt(squareDiffSum / values.length);
}
function kurtosis(values) {
// https://en.wikipedia.org/wiki/Kurtosis
const valuesMean = rand_util_mean(values);
const n = values.length;
let sum2 = 0;
let sum4 = 0;
for (let i = 0; i < n; i++) {
const v = values[i] - valuesMean;
sum2 += Math.pow(v, 2);
sum4 += Math.pow(v, 4);
}
return ((1 / n) * sum4) / Math.pow((1 / n) * sum2, 2);
}
function skewness(values) {
// https://en.wikipedia.org/wiki/Skewness
const valuesMean = rand_util_mean(values);
const n = values.length;
let sum2 = 0;
let sum3 = 0;
for (let i = 0; i < n; i++) {
const v = values[i] - valuesMean;
sum2 += Math.pow(v, 2);
sum3 += Math.pow(v, 3);
}
return ((1 / n) * sum3) / Math.pow((1 / (n - 1)) * sum2, 3 / 2);
}
//# sourceMappingURL=rand_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/random_gamma.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a gamma distribution.
*
* ```js
* tf.randomGamma([2, 2], 1).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param alpha The shape parameter of the gamma distribution.
* @param beta The inverse scale parameter of the gamma distribution. Defaults
* to 1.
* @param dtype The data type of the output. Defaults to float32.
* @param seed The seed for the random number generator.
*/
/** @doc {heading: 'Tensors', subheading: 'Random'} */
function randomGamma_(shape, alpha, beta = 1, dtype = "float32", seed) {
if (beta == null) {
beta = 1;
}
if (dtype == null) {
dtype = "float32";
}
if (dtype !== "float32" && dtype !== "int32") {
throw new Error(`Unsupported data type ${dtype}`);
}
const rgamma = new rand_util_RandGamma(alpha, beta, dtype, seed);
const res = array_ops_buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = rgamma.nextValue();
}
return res.toTensor();
}
const randomGamma = Object(operation["a" /* op */])({ randomGamma_ });
//# sourceMappingURL=random_gamma.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/random_normal.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a normal distribution.
*
* ```js
* tf.randomNormal([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param mean The mean of the normal distribution.
* @param stdDev The standard deviation of the normal distribution.
* @param dtype The data type of the output.
* @param seed The seed for the random number generator.
*/
/** @doc {heading: 'Tensors', subheading: 'Random'} */
function randomNormal_(shape, mean = 0, stdDev = 1, dtype, seed) {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss = new rand_util_MPRandGauss(
mean,
stdDev,
dtype,
false /* truncated */,
seed
);
const res = array_ops_buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = randGauss.nextValue();
}
return res.toTensor();
}
const randomNormal = Object(operation["a" /* op */])({ randomNormal_ });
//# sourceMappingURL=random_normal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/random_uniform.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a uniform distribution.
*
* The generated values follow a uniform distribution in the range [minval,
* maxval). The lower bound minval is included in the range, while the upper
* bound maxval is excluded.
*
* ```js
* tf.randomUniform([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param minval The lower bound on the range of random values to generate.
* Defaults to 0.
* @param maxval The upper bound on the range of random values to generate.
* Defaults to 1.
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*/
/** @doc {heading: 'Tensors', subheading: 'Random'} */
function randomUniform_(shape, minval = 0, maxval = 1, dtype = "float32", seed) {
const res = array_ops_buffer(shape, dtype);
const random = new rand_util_UniformRandom(minval, maxval, null, seed);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = random.nextValue();
}
return res.toTensor();
}
const randomUniform = Object(operation["a" /* op */])({ randomUniform_ });
//# sourceMappingURL=random_uniform.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/real.js
var real = __webpack_require__(22);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/relu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes rectified linear element-wise: `max(x, 0)`.
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.relu().print(); // or tf.relu(x)
* ```
* @param x The input tensor. If the dtype is `bool`, the output dtype will be
* `int32'.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function relu_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "relu");
const forward = (backend, save) => {
save([$x]);
if ($x.dtype === "bool") {
return $x.toInt();
}
return backend.relu($x);
};
const inputs = { x: $x };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["ib" /* Relu */]
);
}
const relu = Object(operation["a" /* op */])({ relu_ });
//# sourceMappingURL=relu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/relu6.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes rectified linear 6 element-wise: `min(max(x, 0), 6)`.
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 8]);
*
* x.relu6().print(); // or tf.relu6(x)
* ```
* @param x The input tensor. If the dtype is `bool`, the output dtype will be
* `int32'.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function relu6_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "relu6");
const forward = (backend, save) => {
save([$x]);
if ($x.dtype === "bool") {
return cast($x, "int32");
}
return backend.relu6($x);
};
const inputs = { x: $x };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["jb" /* Relu6 */]
);
}
const relu6 = Object(operation["a" /* op */])({ relu6_ });
//# sourceMappingURL=relu6.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/selu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes scaled exponential linear element-wise.
*
* `x < 0 ? scale * alpha * (exp(x) - 1) : x`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.selu().print(); // or tf.selu(x)
* ```
* @param x The input tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Basic math'} */
function selu_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "selu");
const forward = (backend, save) => {
const res = backend.selu($x);
save([$x]);
return res;
};
const inputs = { x: $x };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["lb" /* Selu */]
);
}
const selu = Object(operation["a" /* op */])({ selu_ });
//# sourceMappingURL=selu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/separable_conv2d.js
/**
* 2-D convolution with separable filters.
*
* Performs a depthwise convolution that acts separately on channels followed
* by a pointwise convolution that mixes channels. Note that this is
* separability between dimensions [1, 2] and 3, not spatial separability
* between dimensions 1 and 2.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param depthwiseFilter The depthwise filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`. This is
* the filter used in the first step.
* @param pointwiseFilter The pointwise filter tensor, rank 4, of shape
* `[1, 1, inChannels * channelMultiplier, outChannels]`. This is
* the filter used in the second step.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function separableConv2d_(
x,
depthwiseFilter,
pointwiseFilter,
strides,
pad,
dilation = [1, 1],
dataFormat = "NHWC"
) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "separableConv2d");
const $depthwiseFilter = Object(tensor_util_env["a" /* convertToTensor */])(
depthwiseFilter,
"depthwiseFilter",
"separableConv2d"
);
const $pointwiseFilter = Object(tensor_util_env["a" /* convertToTensor */])(
pointwiseFilter,
"pointwiseFilter",
"separableConv2d"
);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = $x.as4D(1, $x.shape[0], $x.shape[1], $x.shape[2]);
}
if (dataFormat === "NCHW") {
throw new Error(
"separableConv2d currently does not support dataFormat NCHW; only " +
"NHWC is supported"
);
}
util["assert"](
x4D.rank === 4,
() => `Error in separableConv2d: input must be rank 4, but got ` + `rank ${x4D.rank}.`
);
util["assert"](
$depthwiseFilter.rank === 4,
() =>
`Error in separableConv2d: depthwise filter must be rank 4, but ` +
`got rank ${$depthwiseFilter.rank}.`
);
util["assert"](
$pointwiseFilter.rank === 4,
() =>
`Error in separableConv2d: pointwise filter must be rank 4, but ` +
`got rank ${$depthwiseFilter.rank}.`
);
util["assert"](
$pointwiseFilter.shape[0] === 1,
() =>
`Error in separableConv2d: the first dimension of pointwise filter ` +
` must be 1, but got ${$pointwiseFilter.shape[0]}.`
);
util["assert"](
$pointwiseFilter.shape[1] === 1,
() =>
`Error in separableConv2d: the second dimension of pointwise ` +
`filter must be 1, but got ${$pointwiseFilter.shape[1]}.`
);
const inChannels = $depthwiseFilter.shape[2];
const channelMultiplier = $depthwiseFilter.shape[3];
util["assert"](
$pointwiseFilter.shape[2] === inChannels * channelMultiplier,
() =>
`Error in separableConv2d: the third dimension of pointwise filter ` +
`must be ${inChannels * channelMultiplier}, ` +
`but got ${$pointwiseFilter.shape[2]}.`
);
const depthwise = depthwiseConv2d(
x4D,
$depthwiseFilter,
strides,
pad,
dataFormat,
dilation
);
const pointwiseStride = 1;
const res = conv2d(depthwise, $pointwiseFilter, pointwiseStride, "valid", dataFormat);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
}
return res;
}
const separableConv2d = Object(operation["a" /* op */])({ separableConv2d_ });
//# sourceMappingURL=separable_conv2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/squared_difference.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns (a - b) * (a - b) element-wise.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)
* ```
*
* ```js
* // Broadcast squared difference a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*/
/** @doc {heading: 'Operations', subheading: 'Arithmetic'} */
function squaredDifference_(a, b) {
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "squaredDifference");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "squaredDifference");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const forward = (backend, save) => {
const res = backend.squaredDifference($a, $b);
save([$a, $b]);
return res;
};
const inputs = { a: $a, b: $b };
const attrs = {};
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* grad */,
kernel_names["pb" /* SquaredDifference */],
attrs
);
}
const squaredDifference = Object(operation["a" /* op */])({ squaredDifference_ });
//# sourceMappingURL=squared_difference.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/truncated_normal.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a truncated normal
* distribution.
*
* ```js
* tf.truncatedNormal([2, 2]).print();
* ```
*
* The generated values follow a normal distribution with specified mean and
* standard deviation, except that values whose magnitude is more than 2
* standard deviations from the mean are dropped and re-picked.
*
* @param shape An array of integers defining the output tensor shape.
* @param mean The mean of the normal distribution.
* @param stdDev The standard deviation of the normal distribution.
* @param dtype The data type of the output tensor.
* @param seed The seed for the random number generator.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function truncatedNormal_(shape, mean = 0, stdDev = 1, dtype, seed) {
if (dtype != null && dtype === "bool") {
throw new Error(`Unsupported data type $ { dtype }`);
}
const randGauss = new rand_util_MPRandGauss(
mean,
stdDev,
dtype,
true /* truncated */,
seed
);
const res = array_ops_buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = randGauss.nextValue();
}
return res.toTensor();
}
const truncatedNormal = Object(operation["a" /* op */])({ truncatedNormal_ });
//# sourceMappingURL=truncated_normal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/reduce_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Inputs of size above this threshold will be parallelized by calling multiple
* shader programs.
*/
const PARALLELIZE_THRESHOLD = 30;
function computeOptimalWindowSize(inSize) {
if (inSize <= PARALLELIZE_THRESHOLD) {
return inSize;
}
return Object(util["nearestDivisor"])(inSize, Math.floor(Math.sqrt(inSize)));
}
//# sourceMappingURL=reduce_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/segment_util.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function segOpComputeOptimalWindowSize(inSize, numSegments) {
let done = false;
let res;
if (inSize <= PARALLELIZE_THRESHOLD) {
res = inSize;
done = true;
} else {
res = Object(util["nearestDivisor"])(inSize, Math.floor(Math.sqrt(inSize)));
}
while (!done) {
if (res > numSegments || res === inSize) {
done = true;
} else {
res = Object(util["nearestDivisor"])(inSize, res + 1);
}
}
return res;
}
function segment_util_computeOutShape(aShape, axis, numSegments) {
const outShape = [];
const rank = aShape.length;
for (let dim = 0; dim < rank; dim++) {
if (dim !== axis) {
outShape.push(aShape[dim]);
} else {
outShape.push(numSegments);
}
}
return outShape;
}
function collectGatherOpShapeInfo(x, indices, axis) {
const dimSize = x.shape[axis];
const outputShape = [];
let batchSize = 1;
let sliceSize = 1;
for (let i = 0; i < axis; i++) {
outputShape.push(x.shape[i]);
batchSize *= x.shape[i];
}
for (let i = 0; i < indices.rank; i++) {
outputShape.push(indices.shape[i]);
}
for (let i = axis + 1; i < x.rank; i++) {
outputShape.push(x.shape[i]);
sliceSize *= x.shape[i];
}
return { batchSize, sliceSize, dimSize, outputShape };
}
//# sourceMappingURL=segment_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/segment_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the sum along segments of a `tf.Tensor`.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const segmentIds = tf.tensor1d([1, 2, 0, 1], 'int32');
* const numSegments = 3;
*
* x.unsortedSegmentSum(segmentIds, numSegments).print()
* //or tf.unsortedSegmentSum(x, segmentIds, numSegments)
* ```
* @param x The `tf.Tensor` that will be summed along its segments.
* @param segmentIds A `tf.Tensor1D` whose rank is equal to the rank of `x`'s
* dimension along the `axis`. Maps each element of `x` to a segment.
* @param numSegments The number of distinct `segmentIds`.
*/
/** @doc {heading: 'Operations', subheading: 'Segment'} */
function unsortedSegmentSum_(x, segmentIds, numSegments) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "unsortedSegmentSum");
const $segmentIds = Object(tensor_util_env["a" /* convertToTensor */])(
segmentIds,
"segmentIds",
"unsortedSegmentSum",
"int32"
);
Object(util["assert"])(
Object(util["isInt"])(numSegments),
() => "numSegments must be of dtype int"
);
const gradFunc = (dy, saved) => {
const [$segmentIds] = saved;
const derX = () => {
return gatherDropNegatives(dy, $segmentIds);
};
return { $x: derX };
};
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.unsortedSegmentSum($x, $segmentIds, numSegments);
save([$segmentIds]);
return res;
},
{ $x },
gradFunc
);
}
/**
* Gather slices from tensor `x`'s axis `axis` according to `indices`.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const indices = tf.tensor1d([1, 3, 3], 'int32');
*
* x.gather(indices).print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const indices = tf.tensor1d([1, 1, 0], 'int32');
*
* x.gather(indices).print();
* ```
* @param x The input tensor whose slices to be gathered.
* @param indices The indices of the values to extract.
* @param axis The axis over which to select values. Defaults to 0.
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
function gather_(x, indices, axis = 0) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "gather");
const $indices = Object(tensor_util_env["a" /* convertToTensor */])(
indices,
"indices",
"gather",
"int32"
);
axis = Object(util["parseAxisParam"])(axis, $x.shape)[0];
const shapeInfo = collectGatherOpShapeInfo($x, $indices, axis);
const grad = (dy, saved) => {
const [$indices] = saved;
const derX = () => {
const paramsShape = $x.shape;
const indicesSize = $indices.size;
const outerShape = paramsShape.slice(0, axis);
const outerDims = outerShape.length;
const innerShape = paramsShape.slice(axis, paramsShape.length).slice(1);
const innerDims = innerShape.length;
const outerAxesIndices = arrayRange(0, outerDims);
const innerAxesIndices = arrayRange(outerDims + 1, outerDims + 1 + innerDims);
const valuesShape = arrayConcat([outerShape, [indicesSize], innerShape]);
const values = dy.reshape(valuesShape);
const reshapedIndices = $indices.reshape([indicesSize]);
const transposeDims = arrayConcat([[outerDims], outerAxesIndices, innerAxesIndices]);
const valuesTranspose = values.transpose(transposeDims);
let paramsGrad = unsortedSegmentSum(valuesTranspose, reshapedIndices, $x.shape[axis]);
const invertTransposeDims = getUndoAxesPermutation(transposeDims);
paramsGrad = paramsGrad.transpose(invertTransposeDims);
return paramsGrad;
};
return { x: derX, indices: () => $indices };
};
return engine["a" /* ENGINE */]
.runKernelFunc(
(backend, save) => {
const res = backend.gather($x, $indices.flatten(), axis);
save([$indices]);
return res;
},
{ x: $x, indices: $indices },
grad,
"Gather",
{ axis }
)
.reshape(shapeInfo.outputShape);
}
function arrayRange(start, stop) {
const result = [];
for (let i = start; i < stop; ++i) {
result.push(i);
}
return result;
}
function arrayConcat(arrays) {
const result = [];
for (let i = 0; i < arrays.length; ++i) {
for (let j = 0; j < arrays[i].length; ++j) {
result.push(arrays[i][j]);
}
}
return result;
}
function gatherDropNegatives(x, indices) {
// Helper function for unsorted segment ops. Gathers params for
// positive segment ids and gathers 0 for inputs with negative segment id.
// Mirrors _GatherDropNegatives from tensorflow/python/ops/math_grad.py
const zeroClippedIndices = maximum(
indices,
Object(tensor_ops["o" /* zerosLike */])(indices)
);
const gathered = gather(x, zeroClippedIndices);
let isPositive = greaterEqual(indices, Object(tensor_ops["e" /* scalar */])(0, "int32"));
const numIters = gathered.rank - isPositive.rank;
for (let i = 0; i < numIters; ++i) {
isPositive = expandDims(isPositive, i + 1);
}
isPositive = logicalAnd(
isPositive,
Object(tensor_ops["b" /* ones */])(gathered.shape, "bool")
);
const zeroSlice = Object(tensor_ops["o" /* zerosLike */])(gathered);
return where(isPositive, gathered, zeroSlice);
}
const gather = Object(operation["a" /* op */])({ gather_ });
const unsortedSegmentSum = Object(operation["a" /* op */])({ unsortedSegmentSum_ });
//# sourceMappingURL=segment_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/boolean_mask.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Apply boolean mask to tensor.
*
* ```js
* const tensor = tf.tensor2d([1, 2, 3, 4, 5, 6], [3, 2]);
* const mask = tf.tensor1d([1, 0, 1], 'bool');
* const result = await tf.booleanMaskAsync(tensor, mask);
* result.print();
* ```
*
* @param tensor N-D tensor.
* @param mask K-D boolean tensor, K <= N and K must be known statically.
* @param axis A 0-D int Tensor representing the axis in tensor to mask from.
* By default, axis is 0 which will mask from the first dimension.
* Otherwise K + axis <= N.
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
async function booleanMaskAsync_(tensor, mask, axis) {
const $tensor = Object(tensor_util_env["a" /* convertToTensor */])(
tensor,
"tensor",
"boolMask"
);
const $mask = Object(tensor_util_env["a" /* convertToTensor */])(
mask,
"mask",
"boolMask",
"bool"
);
const axisFrom = axis == null ? 0 : axis;
const maskDim = $mask.rank;
const tensorShape = $tensor.shape;
util["assert"](maskDim > 0, () => "mask cannot be scalar");
util["assertShapesMatch"](
tensorShape.slice(axisFrom, axisFrom + maskDim),
$mask.shape,
`mask's shape must match the first K dimensions of tensor's shape,`
);
let leadingSize = 1;
for (let i = axisFrom; i < axisFrom + maskDim; i++) {
leadingSize *= tensorShape[i];
}
const targetTensorShape = tensorShape
.slice(0, axisFrom)
.concat([leadingSize], tensorShape.slice(axisFrom + maskDim));
const reshapedTensor = $tensor.reshape(targetTensorShape);
const reshapedMask = $mask.reshape([-1]);
const positivePositions = await whereAsync(reshapedMask);
const indices = positivePositions.squeeze([1]);
const res = gather(reshapedTensor, indices, axisFrom);
// Ensure no memory leak.
if (tensor !== $tensor) {
$tensor.dispose();
}
if (mask !== $mask) {
$mask.dispose();
}
indices.dispose();
reshapedTensor.dispose();
reshapedMask.dispose();
positivePositions.dispose();
return res;
}
const booleanMaskAsync = booleanMaskAsync_;
//# sourceMappingURL=boolean_mask.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/reverse.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor1D`.
*
* @param x The input tensor.
*/
function reverse1d_(x) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "reverse");
util["assert"](
$x.rank === 1,
() => `Error in reverse1D: x must be rank 1 but got rank ${$x.rank}.`
);
return reverse_reverse($x, 0);
}
/**
* Reverses a `tf.Tensor2D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse2d_(x, axis) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "reverse");
util["assert"](
$x.rank === 2,
() => `Error in reverse2D: x must be rank 2 but got rank ${$x.rank}.`
);
return reverse_reverse($x, axis);
}
/**
* Reverses a `tf.Tensor3D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse3d_(x, axis) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "reverse");
util["assert"](
$x.rank === 3,
() => `Error in reverse3D: x must be rank 3 but got rank ${$x.rank}.`
);
return reverse_reverse($x, axis);
}
/**
* Reverses a `tf.Tensor4D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse4d_(x, axis) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "reverse");
util["assert"](
$x.rank === 4,
() => `Error in reverse4D: x must be rank 4 but got rank ${$x.rank}.`
);
return reverse_reverse($x, axis);
}
/**
* Reverses a `tf.Tensor` along a specified axis.
*
* Also available are stricter rank-specific methods that assert that `x` is
* of the given rank:
* - `tf.reverse1d`
* - `tf.reverse2d`
* - `tf.reverse3d`
* - `tf.reverse4d`
*
* Except `tf.reverse1d` (which does not have axis param), all methods have
* same signature as this method.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.reverse().print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.reverse(axis).print();
* ```
* @param x The input tensor to be reversed.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
/** @doc {heading: 'Tensors', subheading: 'Slicing and Joining'} */
function reverse_(x, axis) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "reverse");
if ($x.rank === 0) {
return $x.clone();
}
const axes = util["parseAxisParam"](axis, $x.shape);
const grad = (dy) => {
return { $x: () => dy.reverse(axes) };
};
const res = engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.reverse($x, axes),
{ $x },
grad
);
return res.reshapeAs($x);
}
const reverse_reverse = Object(operation["a" /* op */])({ reverse_ });
const reverse1d = Object(operation["a" /* op */])({ reverse1d_ });
const reverse2d = Object(operation["a" /* op */])({ reverse2d_ });
const reverse3d = Object(operation["a" /* op */])({ reverse3d_ });
const reverse4d = Object(operation["a" /* op */])({ reverse4d_ });
//# sourceMappingURL=reverse.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/compare.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @deprecated
* Strict version of `tf.notEqual` that forces `a` and `b` to be of the same
* shape.
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same shape and dtype as
* `a`.
*/
function notEqualStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "notEqualStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "notEqualStrict");
Object(util["assertShapesMatch"])($a.shape, $b.shape, "Error in notEqualStrict: ");
return $a.notEqual($b);
}
/**
* @deprecated
* Strict version of `tf.less` that forces `a` and `b` to be of the same
* shape.
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same shape and dtype as
* `a`.
*/
function lessStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "lessStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "lessStrict");
Object(util["assertShapesMatch"])($a.shape, $b.shape, "Error in lessStrict: ");
return $a.less($b);
}
function equalStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "equalStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "equalStrict");
Object(util["assertShapesMatch"])($a.shape, $b.shape, "Error in equalStrict: ");
return $a.equal($b);
}
function lessEqualStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "lessEqualStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "lessEqualStrict");
Object(util["assertShapesMatch"])($a.shape, $b.shape, "Error in lessEqualStrict: ");
return $a.lessEqual($b);
}
function greaterStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "greaterStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "greaterStrict");
Object(util["assertShapesMatch"])($a.shape, $b.shape, "Error in greaterStrict: ");
return $a.greater($b);
}
function greaterEqualStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "greaterEqualStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "greaterEqualStrict");
Object(util["assertShapesMatch"])($a.shape, $b.shape, "Error in greaterEqualStrict: ");
return $a.greaterEqual($b);
}
const equalStrict = Object(operation["a" /* op */])({ equalStrict_ });
const greaterEqualStrict = Object(operation["a" /* op */])({ greaterEqualStrict_ });
const greaterStrict = Object(operation["a" /* op */])({ greaterStrict_ });
const lessEqualStrict = Object(operation["a" /* op */])({ lessEqualStrict_ });
const lessStrict = Object(operation["a" /* op */])({ lessStrict_ });
const notEqualStrict = Object(operation["a" /* op */])({ notEqualStrict_ });
//# sourceMappingURL=compare.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/binary_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @deprecated
* Adds two `tf.Tensor`s element-wise, A + B.
*
* Inputs must be the same shape. For broadcasting support, use add() instead.
*
* @param a The first Tensor to add element-wise.
* @param b The second Tensor to add element-wise.
*/
function addStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "addStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "addStrict");
util["assertShapesMatch"]($a.shape, $b.shape, "Error in addStrict: ");
return $a.add($b);
}
/**
* @deprecated
* Subtracts two `tf.Tensor`s element-wise, A - B. Inputs must
* be the same shape.
*
* For broadcasting support, use `tf.sub` instead.
*
* @param a The first Tensor to subtract element-wise.
* @param b The second Tensor to subtract element-wise.
*/
function subStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "subStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "subStrict");
util["assertShapesMatch"]($a.shape, $b.shape, "Error in subStrict: ");
return $a.sub($b);
}
/**
* @deprecated
* Computes the power of one `tf.Tensor` to another. Inputs must
* be the same shape.
*
* For broadcasting support, use `tf.pow` instead.
*
* @param base The base tensor to pow element-wise.
* @param exp The exponent tensor to pow element-wise.
*/
function powStrict_(base, exp) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
util["assertShapesMatch"](base.shape, exp.shape, "Error in powStrict: ");
return base.pow(exp);
}
/**
* @deprecated
* Multiplies two `tf.Tensor`s element-wise, A * B.
*
* Inputs must be the same shape. For broadcasting support, use `tf.mul`.
*
* @param a The first tensor to multiply.
* @param b The first tensor to multiply. Must have the same
* dtype as `a`.
*/
function mulStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "mul");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "mul");
util["assertShapesMatch"]($a.shape, $b.shape, "Error in multiplyStrict: ");
return $a.mul($b);
}
/**
* @deprecated
* Divides two `tf.Tensor`s element-wise, A / B. Inputs must
* be the same shape.
*
* @param a The first tensor as the numerator for element-wise division.
* @param b The second tensor as the denominator for element-wise division.
*/
function divStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "div");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "div");
util["assertShapesMatch"]($a.shape, $b.shape, "Error in divideStrict: ");
return $a.div($b);
}
/**
* @deprecated
* Returns the mod of a and b (`a < b ? a : b`) element-wise. Inputs must
* be the same shape. For broadcasting support, use mod().
*
* @param a The first tensor.
* @param b The second tensor. Must have the same dtype as `a`.
*/
function modStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "modStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "modStrict");
util["assertShapesMatch"]($a.shape, $b.shape, "Error in modStrict: ");
return $a.mod($b);
}
/**
* @deprecated
* Returns the min of a and b (`a < b ? a : b`) element-wise. Inputs must
* be the same shape. For broadcasting support, use minimum().
*
* @param a The first tensor.
* @param b The second tensor. Must have the same dtype as `a`.
*/
function minimumStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "minimumStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "minimumStrict");
util["assertShapesMatch"]($a.shape, $b.shape, "Error in minimumStrict: ");
return $a.minimum($b);
}
/**
* @deprecated
* Returns the max of a and b (`a > b ? a : b`) element-wise. Inputs must
* be the same shape. For broadcasting support, use maximum().
*
* @param a The first tensor.
* @param b The second tensor. Must have the same dtype as `a`.
*/
function maximumStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "maximumStrict");
const $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "maximumStrict");
util["assertShapesMatch"]($a.shape, $b.shape, "Error in maximumStrict: ");
return $a.maximum($b);
}
/**
* @deprecated
* Returns (a - b) * (a - b) element-wise.
*
* Inputs must be the same shape. For broadcasting support, use
* `tf.squaredDifference` instead.
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*/
function squaredDifferenceStrict_(a, b) {
deprecationWarn(
"strict variants of ops have been deprecated " + "and will be removed in future"
);
const $a = Object(tensor_util_env["a" /* convertToTensor */])(
a,
"a",
"squaredDifferenceStrict"
);
const $b = Object(tensor_util_env["a" /* convertToTensor */])(
b,
"b",
"squaredDifferenceStrict"
);
util["assertShapesMatch"]($a.shape, $b.shape, "Error in squaredDifferenceStrict: ");
return $a.squaredDifference($b);
}
const addStrict = Object(operation["a" /* op */])({ addStrict_ });
const divStrict = Object(operation["a" /* op */])({ divStrict_ });
const maximumStrict = Object(operation["a" /* op */])({ maximumStrict_ });
const minimumStrict = Object(operation["a" /* op */])({ minimumStrict_ });
const modStrict = Object(operation["a" /* op */])({ modStrict_ });
const mulStrict = Object(operation["a" /* op */])({ mulStrict_ });
const powStrict = Object(operation["a" /* op */])({ powStrict_ });
const squaredDifferenceStrict = Object(operation["a" /* op */])({ squaredDifferenceStrict_ });
const subStrict = Object(operation["a" /* op */])({ subStrict_ });
//# sourceMappingURL=binary_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/softmax.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the softmax normalized vector given the logits.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
*
* a.softmax().print(); // or tf.softmax(a)
* ```
*
* ```js
* const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);
*
* a.softmax().print(); // or tf.softmax(a)
* ```
*
* @param logits The logits array.
* @param dim The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*/
/** @doc {heading: 'Operations', subheading: 'Normalization'} */
function softmax_(logits, dim = -1) {
const $logits = Object(tensor_util_env["a" /* convertToTensor */])(
logits,
"logits",
"softmax",
"float32"
);
if (dim === -1) {
dim = $logits.rank - 1;
}
if (dim !== $logits.rank - 1) {
throw Error(
"Softmax along a non-last dimension is not yet supported. " +
`Logits was rank ${$logits.rank} and dim was ${dim}`
);
}
const inputsToSave = [];
const outputsToSave = [true];
return engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const y = backend.softmax($logits, dim);
save([y]);
return y;
},
{ logits: $logits },
(dy, saved) => {
const [y] = saved;
const dyTimesY = dy.mul(y);
const keepDims = true;
return {
logits: () => dyTimesY.sub(dyTimesY.sum([dim], keepDims).mul(y)),
};
},
"Softmax",
{ dim },
inputsToSave,
outputsToSave
);
}
/**
* Computes the log softmax.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
*
* a.logSoftmax().print(); // or tf.logSoftmax(a)
* ```
*
* ```js
* const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);
*
* a.logSoftmax().print(); // or tf.logSoftmax(a)
* ```
*
* @param logits The logits array.
* @param axis The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*/
/** @doc {heading: 'Operations', subheading: 'Normalization'} */
function logSoftmax_(logits, axis = -1) {
const $logits = Object(tensor_util_env["a" /* convertToTensor */])(
logits,
"logits",
"logSoftmax"
);
if (axis === -1) {
axis = $logits.rank - 1;
}
if (axis !== $logits.rank - 1) {
throw Error(
"Log Softmax along a non-last dimension is not yet supported. " +
`Logits was rank ${$logits.rank} and axis was ${axis}`
);
}
const customOp = customGrad((logits, save) => {
const keepDims = true;
const xMax = logits.max(axis, true);
const shifted = logits.sub(xMax);
const value = shifted.toFloat().sub(shifted.exp().sum(axis, keepDims).log());
save([value]);
const gradFunc = (dy, saved) => {
const [value] = saved;
const softmax = value.exp();
return dy.sub(dy.sum(axis, keepDims).mul(softmax));
};
return { value, gradFunc };
});
return customOp($logits);
}
const softmax = Object(operation["a" /* op */])({ softmax_ });
const logSoftmax = Object(operation["a" /* op */])({ logSoftmax_ });
//# sourceMappingURL=softmax.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/norm.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the norm of scalar, vectors, and matrices.
* This function can compute several different vector norms (the 1-norm, the
* Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0)
* and matrix norms (Frobenius, 1-norm, and inf-norm).
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.norm().print(); // or tf.norm(x)
* ```
*
* @param x The input array.
* @param ord Optional. Order of the norm. Supported norm types are
* following:
*
* | ord | norm for matrices | norm for vectors
* |------------|---------------------------|---------------------
* |'euclidean' |Frobenius norm |2-norm
* |'fro' |Frobenius norm |
* |Infinity |max(sum(abs(x), axis=1)) |max(abs(x))
* |-Infinity |min(sum(abs(x), axis=1)) |min(abs(x))
* |1 |max(sum(abs(x), axis=0)) |sum(abs(x))
* |2 | |sum(abs(x)^2)^1/2*
*
* @param axis Optional. If axis is null (the default), the input is
* considered a vector and a single vector norm is computed over the entire
* set of values in the Tensor, i.e. norm(x, ord) is equivalent
* to norm(x.reshape([-1]), ord). If axis is a integer, the input
* is considered a batch of vectors, and axis determines the axis in x
* over which to compute vector norms. If axis is a 2-tuple of integer it is
* considered a batch of matrices and axis determines the axes in NDArray
* over which to compute a matrix norm.
* @param keepDims Optional. If true, the norm have the same dimensionality
* as the input.
*/
/** @doc {heading: 'Operations', subheading: 'Matrices'} */
function norm_(x, ord = "euclidean", axis = null, keepDims = false) {
x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "norm");
const norm = normImpl(x, ord, axis);
let keepDimsShape = norm.shape;
if (keepDims) {
const axes = Object(util["parseAxisParam"])(axis, x.shape);
keepDimsShape = expandShapeToKeepDim(norm.shape, axes);
}
return norm.reshape(keepDimsShape);
}
function normImpl(x, p, axis = null) {
if (x.rank === 0) {
return x.abs();
}
// consider vector when no axis is specified
if (x.rank !== 1 && axis === null) {
return normImpl(x.reshape([-1]), p, axis);
}
// vector
if (
x.rank === 1 ||
typeof axis === "number" ||
(Array.isArray(axis) && axis.length === 1)
) {
if (p === 1) {
return x.abs().sum(axis);
}
if (p === Infinity) {
return x.abs().max(axis);
}
if (p === -Infinity) {
return x.abs().min(axis);
}
if (p === "euclidean" || p === 2) {
// norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2
return x.abs().pow(Object(tensor_ops["e" /* scalar */])(2, "int32")).sum(axis).sqrt();
}
throw new Error(`Error in norm: invalid ord value: ${p}`);
}
// matrix (assumption axis[0] < axis[1])
if (Array.isArray(axis) && axis.length === 2) {
if (p === 1) {
return x
.abs()
.sum(axis[0])
.max(axis[1] - 1);
}
if (p === Infinity) {
return x.abs().sum(axis[1]).max(axis[0]);
}
if (p === -Infinity) {
return x.abs().sum(axis[1]).min(axis[0]);
}
if (p === "fro" || p === "euclidean") {
// norm(x) = sqrt(sum(pow(x, 2)))
return x.square().sum(axis).sqrt();
}
throw new Error(`Error in norm: invalid ord value: ${p}`);
}
throw new Error(`Error in norm: invalid axis: ${axis}`);
}
const norm_norm = Object(operation["a" /* op */])({ norm_ });
//# sourceMappingURL=norm.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/lstm.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the next states and outputs of a stack of LSTMCells.
*
* Each cell output is used as input to the next cell.
*
* Returns `[cellState, cellOutput]`.
*
* Derived from tf.contrib.rn.MultiRNNCell.
*
* @param lstmCells Array of LSTMCell functions.
* @param data The input to the cell.
* @param c Array of previous cell states.
* @param h Array of previous cell outputs.
*/
/** @doc {heading: 'Operations', subheading: 'RNN'} */
function multiRNNCell_(lstmCells, data, c, h) {
const $data = Object(tensor_util_env["a" /* convertToTensor */])(
data,
"data",
"multiRNNCell"
);
const $c = Object(tensor_util_env["b" /* convertToTensorArray */])(c, "c", "multiRNNCell");
const $h = Object(tensor_util_env["b" /* convertToTensorArray */])(h, "h", "multiRNNCell");
let input = $data;
const newStates = [];
for (let i = 0; i < lstmCells.length; i++) {
const output = lstmCells[i](input, $c[i], $h[i]);
newStates.push(output[0]);
newStates.push(output[1]);
input = output[1];
}
const newC = [];
const newH = [];
for (let i = 0; i < newStates.length; i += 2) {
newC.push(newStates[i]);
newH.push(newStates[i + 1]);
}
return [newC, newH];
}
/**
* Computes the next state and output of a BasicLSTMCell.
*
* Returns `[newC, newH]`.
*
* Derived from tf.contrib.rnn.BasicLSTMCell.
*
* @param forgetBias Forget bias for the cell.
* @param lstmKernel The weights for the cell.
* @param lstmBias The bias for the cell.
* @param data The input to the cell.
* @param c Previous cell state.
* @param h Previous cell output.
*/
/** @doc {heading: 'Operations', subheading: 'RNN'} */
function basicLSTMCell_(forgetBias, lstmKernel, lstmBias, data, c, h) {
const $forgetBias = Object(tensor_util_env["a" /* convertToTensor */])(
forgetBias,
"forgetBias",
"basicLSTMCell"
);
const $lstmKernel = Object(tensor_util_env["a" /* convertToTensor */])(
lstmKernel,
"lstmKernel",
"basicLSTMCell"
);
const $lstmBias = Object(tensor_util_env["a" /* convertToTensor */])(
lstmBias,
"lstmBias",
"basicLSTMCell"
);
const $data = Object(tensor_util_env["a" /* convertToTensor */])(
data,
"data",
"basicLSTMCell"
);
const $c = Object(tensor_util_env["a" /* convertToTensor */])(c, "c", "basicLSTMCell");
const $h = Object(tensor_util_env["a" /* convertToTensor */])(h, "h", "basicLSTMCell");
const combined = $data.concat($h, 1);
const weighted = combined.matMul($lstmKernel);
const res = weighted.add($lstmBias);
// i = input_gate, j = new_input, f = forget_gate, o = output_gate
const batchSize = res.shape[0];
const sliceCols = res.shape[1] / 4;
const sliceSize = [batchSize, sliceCols];
const i = res.slice([0, 0], sliceSize);
const j = res.slice([0, sliceCols], sliceSize);
const f = res.slice([0, sliceCols * 2], sliceSize);
const o = res.slice([0, sliceCols * 3], sliceSize);
const newC = i
.sigmoid()
.mul(j.tanh())
.add($c.mul($forgetBias.add(f).sigmoid()));
const newH = newC.tanh().mul(o.sigmoid());
return [newC, newH];
}
const basicLSTMCell = Object(operation["a" /* op */])({ basicLSTMCell_ });
const multiRNNCell = Object(operation["a" /* op */])({ multiRNNCell_ });
//# sourceMappingURL=lstm.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/moving_average.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Compute the moving average of a variable.
*
* Without zeroDebias, the moving average operation is defined by:
* `v += delta`
* where
* `delta = (1 - decay) * (x - v)`
*
* With zeroDebias (default), the `delta` term is scaled to debias the
* effect of the (assumed) zero-initialization of `v`.
* `delta /= (1 - decay ^ step)`
*
* For more details on the zero-debiasing algorithm, see:
* https://arxiv.org/abs/1412.6980
*
* Note that this function is completely stateless and does not keep track of
* step count. The step count needs to be maintained by the caller and passed
* in as `step`.
*
* @param v The current moving average value.
* @param x New input value, must have the same shape and dtype as `v`.
* @param decay The decay factor. Typical values are 0.95 and 0.99.
* @param step Step count.
* @param zeroDebias: Whether zeroDebias is to be performed (default: `true`).
* @returns The new moving average value.
*/
/** @doc {heading: 'Operations', subheading: 'Moving Average'} */
function movingAverage_(v, x, decay, step, zeroDebias = true) {
const $v = Object(tensor_util_env["a" /* convertToTensor */])(v, "v", "movingAverage");
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "movingAverage");
const $decay = Object(tensor_util_env["a" /* convertToTensor */])(
decay,
"decay",
"movingAverage"
);
Object(tensor_util["assertTypesMatch"])($v, $x);
util["assert"](util["arraysEqual"]($v.shape, $x.shape), () => "Shape mismatch in v and x");
const one = Object(tensor_ops["e" /* scalar */])(1);
const oneMinusDecay = one.sub($decay);
let update = $x.sub($v).mul(oneMinusDecay);
if (zeroDebias) {
util["assert"](step != null, () => "When using zeroDebias: true, step is required.");
const $step = Object(tensor_util_env["a" /* convertToTensor */])(
step,
"step",
"movingAverage"
);
update = update.div(one.sub(pow($decay, $step)));
}
return $v.add(update);
}
const movingAverage = Object(operation["a" /* op */])({ movingAverage_ });
//# sourceMappingURL=moving_average.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/strided_slice.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a strided slice of a tensor.
*
* Roughly speaking, this op extracts a slice of size (end-begin)/stride from
* the given input tensor (x). Starting at the location specified by begin the
* slice continues by adding stride to the index until all dimensions are not
* less than end. Note that a stride can be negative, which causes a reverse
* slice.
*
* ```js
* const t = tf.tensor3d([1, 1, 1 ,2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],
* [3, 2, 3]);
* t.stridedSlice([1, 0, 0], [2, 1, 3], [1, 1, 1]).print() // [[[3, 3, 3]]]
* t.stridedSlice([1, 0, 0], [2, 2, 3], [1, 1, 1]).print() // [[[3, 3, 3],
* // [4, 4, 4]]]
* t.stridedSlice([1, -1, 0], [2, -3, 3], [1, -1, 1]).print() // [[[4, 4, 4],
* // [3, 3, 3]]]
* ```
*
* @param x The tensor to stride slice.
* @param begin The coordinates to start the slice from.
* @param end: The coordinates to end the slice at.
* @param strides: The size of the slice.
* @param beginMask: If the ith bit of beginMask is set, begin[i] is ignored
* and the fullest possible range in that dimension is used instead.
* @param endMask: If the ith bit of endMask is set, end[i] is ignored
* and the fullest possible range in that dimension is used instead.
* @param shrinkAxisMask: a bitmask where bit i implies that
* the ith specification should shrink the dimensionality. begin and end must
* imply a slice of size 1 in the dimension.
*/
/** @doc {heading: 'Operations', subheading: 'Slicing and Joining'} */
function stridedSlice_(
x,
begin,
end,
strides,
beginMask = 0,
endMask = 0,
ellipsisMask = 0,
newAxisMask = 0,
shrinkAxisMask = 0
) {
if (strides == null) {
strides = new Array(begin.length);
}
const ellipsisAxes = maskToAxes(ellipsisMask);
if (ellipsisAxes.length > 1) {
throw new Error("Multiple ellipses in slice is not allowed.");
}
if (ellipsisMask !== 0 && newAxisMask !== 0) {
throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");
}
if (ellipsisMask !== 0 && shrinkAxisMask !== 0) {
throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");
}
let $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "stridedSlice");
const numInterpolatedAxes = $x.rank - begin.length;
// Expand the dims of x based on the newAxisMask.
const expandAxes = maskToAxes(newAxisMask);
const newShape = $x.shape.slice();
expandAxes.forEach((axis) => {
begin[axis] = 0;
end[axis] = 1;
newShape.splice(axis, 0, 1);
});
$x = $x.reshape(newShape);
// Normalize the start, end and strides.
for (let axis = 0; axis < $x.rank; axis++) {
begin[axis] = startForAxis(beginMask, begin, strides, $x.shape, axis, ellipsisMask);
end[axis] = stopForAxis(endMask, end, strides, $x.shape, axis, ellipsisMask);
strides[axis] = stridesForAxis(strides, axis, ellipsisMask);
}
if (ellipsisAxes.length && numInterpolatedAxes > 0) {
const fullIndex = ellipsisAxes[0];
// The ellipsis applies to the masked index as well as any dimensions that
// were interpolated as full selection.
const numElidedAxes = numInterpolatedAxes + 1;
begin = startIndicesWithElidedDims(begin, fullIndex, numElidedAxes);
end = stopIndicesWithElidedDims(end, fullIndex, numElidedAxes, $x.shape);
strides = stridesWithElidedDims(strides, fullIndex, numElidedAxes);
}
const shrinkAxes = maskToAxes(shrinkAxisMask);
// Adjust the ends based on the shrink mask.
shrinkAxes.forEach((axis) => {
end[axis] = begin[axis] + 1;
strides[axis] = 1;
});
// Figure out the output shape.
const size = slice_util_computeOutShape(begin, end, strides);
// Remove the axes based on shrinkMask.
const outShape = size.filter((_, axis) => shrinkAxes.indexOf(axis) === -1);
const nonStrided = strides.every((v) => v === 1);
if (nonStrided) {
return slice($x, begin, size).reshape(outShape);
}
const res = engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.stridedSlice($x, begin, end, strides),
{ $x }
);
return res.reshape(outShape);
}
const stridedSlice = Object(operation["a" /* op */])({ stridedSlice_ });
//# sourceMappingURL=strided_slice.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/topk.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Finds the values and indices of the `k` largest entries along the last
* dimension.
*
* If the input is a vector (rank=1), finds the k largest entries in the vector
* and outputs their values and indices as vectors. Thus values[j] is the j-th
* largest entry in input, and its index is indices[j].
* For higher rank inputs, computes the top k entries along the last dimension.
*
* If two elements are equal, the lower-index element appears first.
*
* ```js
* const a = tf.tensor2d([[1, 5], [4, 3]]);
* const {values, indices} = tf.topk(a);
* values.print();
* indices.print();
* ```
* @param x 1-D or higher `tf.Tensor` with last dimension being at least `k`.
* @param k Number of top elements to look for along the last dimension.
* @param sorted If true, the resulting `k` elements will be sorted by the
* values in descending order.
*/
/** @doc {heading: 'Operations', subheading: 'Evaluation'} */
function topk_(x, k = 1, sorted = true) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "topk");
if ($x.rank === 0) {
throw new Error("topk() expects the input to be of rank 1 or higher");
}
const lastDim = $x.shape[$x.shape.length - 1];
if (k > lastDim) {
throw new Error(
`'k' passed to topk() must be <= the last dimension (${lastDim}) ` + `but got ${k}`
);
}
const [values, indices] = engine["a" /* ENGINE */].runKernelFunc(
(b) => b.topk($x, k, sorted),
{ $x }
);
return { values, indices };
}
const topk = Object(operation["a" /* op */])({ topk_ });
//# sourceMappingURL=topk.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/scatter_nd.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a new tensor by applying sparse updates to individual
* values or slices within a zero tensor of the given shape tensor according to
* indices. This operator is the inverse of the `tf.gatherND` operator which
* extracts values or slices from a given tensor.
*
* ```js
* const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');
* const updates = tf.tensor1d([9, 10, 11, 12]);
* const shape = [8];
* tf.scatterND(indices, updates, shape).print() //[0, 11, 0, 10, 9, 0, 0, 12]
* ```
*
* @param indices The tensor contains the indices into the output tensor.
* @param updates The tensor contains the value for the indices.
* @param shape: The shape of the output tensor.
*/
/** @doc {heading: 'Operations', subheading: 'Slicing and Joining'} */
function scatterND_(indices, updates, shape) {
const $indices = Object(tensor_util_env["a" /* convertToTensor */])(
indices,
"indices",
"scatterND",
"int32"
);
const $updates = Object(tensor_util_env["a" /* convertToTensor */])(
updates,
"updates",
"scatterND"
);
validateInput($updates, $indices, shape);
return engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.scatterND($indices, $updates, shape),
{ indices: $indices, updates: $updates },
null /* backward */,
"ScatterNd",
{ shape }
);
}
const scatterND = Object(operation["a" /* op */])({ scatterND_ });
//# sourceMappingURL=scatter_nd.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/spectral_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Fast Fourier transform.
*
* Computes the 1-dimensional discrete Fourier transform over the inner-most
* dimension of input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([1, 2, 3]);
* const x = tf.complex(real, imag);
*
* x.fft().print(); // tf.spectral.fft(x).print();
* ```
* @param input The complex input to compute an fft over.
*/
/**
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function fft_(input) {
Object(util["assert"])(
input.dtype === "complex64",
() => `The dtype for tf.spectral.fft() must be complex64 ` + `but got ${input.dtype}.`
);
// Collapse all outer dimensions to a single batch dimension.
const innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
const input2D = input.as2D(batch, innerDimensionSize);
const ret = engine["a" /* ENGINE */].runKernelFunc((backend) => backend.fft(input2D), {
input,
});
return ret.reshape(input.shape);
}
/**
* Inverse fast Fourier transform.
*
* Computes the inverse 1-dimensional discrete Fourier transform over the
* inner-most dimension of input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([1, 2, 3]);
* const x = tf.complex(real, imag);
*
* x.ifft().print(); // tf.spectral.ifft(x).print();
* ```
* @param input The complex input to compute an ifft over.
*/
/**
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function ifft_(input) {
Object(util["assert"])(
input.dtype === "complex64",
() => `The dtype for tf.spectral.ifft() must be complex64 ` + `but got ${input.dtype}.`
);
// Collapse all outer dimensions to a single batch dimension.
const innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
const input2D = input.as2D(batch, innerDimensionSize);
const ret = engine["a" /* ENGINE */].runKernelFunc((backend) => backend.ifft(input2D), {
input,
});
return ret.reshape(input.shape);
}
/**
* Real value input fast Fourier transform.
*
* Computes the 1-dimensional discrete Fourier transform over the
* inner-most dimension of the real input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
*
* real.rfft().print();
* ```
* @param input The real value input to compute an rfft over.
*/
/**
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function rfft_(input, fftLength) {
Object(util["assert"])(
input.dtype === "float32",
() => `The dtype for rfft() must be real value but got ${input.dtype}`
);
let innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
let adjustedInput;
if (fftLength != null && fftLength < innerDimensionSize) {
// Need to crop
const begin = input.shape.map((v) => 0);
const size = input.shape.map((v) => v);
size[input.shape.length - 1] = fftLength;
adjustedInput = input.slice(begin, size);
innerDimensionSize = fftLength;
} else if (fftLength != null && fftLength > innerDimensionSize) {
// Need to pad with zeros
const zerosShape = input.shape.map((v) => v);
zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;
adjustedInput = input.concat(
Object(tensor_ops["n" /* zeros */])(zerosShape),
input.shape.length - 1
);
innerDimensionSize = fftLength;
} else {
adjustedInput = input;
}
// Complement the input with zero imaginary numbers.
const zerosInput = adjustedInput.zerosLike();
const complexInput = Object(complex["a" /* complex */])(adjustedInput, zerosInput).as2D(
batch,
innerDimensionSize
);
const ret = fft(complexInput);
// Exclude complex conjugations. These conjugations are put symmetrically.
const half = Math.floor(innerDimensionSize / 2) + 1;
const realValues = Object(real["a" /* real */])(ret);
const imagValues = Object(imag["a" /* imag */])(ret);
const realComplexConjugate = realValues.split(
[half, innerDimensionSize - half],
realValues.shape.length - 1
);
const imagComplexConjugate = imagValues.split(
[half, innerDimensionSize - half],
imagValues.shape.length - 1
);
const outputShape = adjustedInput.shape.slice();
outputShape[adjustedInput.shape.length - 1] = half;
return Object(complex["a" /* complex */])(
realComplexConjugate[0],
imagComplexConjugate[0]
).reshape(outputShape);
}
/**
* Inversed real value input fast Fourier transform.
*
* Computes the 1-dimensional inversed discrete Fourier transform over the
* inner-most dimension of the real input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([0, 0, 0]);
* const x = tf.complex(real, imag);
*
* x.irfft().print();
* ```
* @param input The real value input to compute an irfft over.
*/
/**
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function irfft_(input) {
const innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
if (innerDimensionSize <= 2) {
const complexInput = input.as2D(batch, innerDimensionSize);
const ret = ifft(complexInput);
return Object(real["a" /* real */])(ret);
} else {
// The length of unique components of the DFT of a real-valued signal
// is 2 * (input_len - 1)
const outputShape = [batch, 2 * (innerDimensionSize - 1)];
const realInput = Object(real["a" /* real */])(input).as2D(batch, innerDimensionSize);
const imagInput = Object(imag["a" /* imag */])(input).as2D(batch, innerDimensionSize);
const realConjugate = realInput.slice([0, 1], [batch, innerDimensionSize - 2]).reverse(1);
const imagConjugate = imagInput
.slice([0, 1], [batch, innerDimensionSize - 2])
.reverse(1)
.mul(Object(tensor_ops["e" /* scalar */])(-1));
const r = realInput.concat(realConjugate, 1);
const i = imagInput.concat(imagConjugate, 1);
const complexInput = Object(complex["a" /* complex */])(r, i).as2D(
outputShape[0],
outputShape[1]
);
const ret = ifft(complexInput);
return Object(real["a" /* real */])(ret);
}
}
const fft = Object(operation["a" /* op */])({ fft_ });
const ifft = Object(operation["a" /* op */])({ ifft_ });
const rfft = Object(operation["a" /* op */])({ rfft_ });
const irfft = Object(operation["a" /* op */])({ irfft_ });
//# sourceMappingURL=spectral_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sparse_to_dense_util.js
/**
* Validate sparseToDense inputs.
*
* @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.
* sparseIndices[i] contains the complete index where sparseValues[i] will be
* placed.
* @param sparseValues A 0-D or 1-D Tensor. Values
* corresponding to each row of sparseIndices, or a scalar value to be used for
* all sparse indices.
* @param outputShape number[]. Shape of the dense output tensor.
* @param validateIndices boolean. indice validation is not supported, error
* will be thrown if it is set.
*/
function sparse_to_dense_util_validateInput(
sparseIndices,
sparseValues,
outputShape,
defaultValues
) {
if (sparseIndices.dtype !== "int32") {
throw new Error(
"tf.sparseToDense() expects the indices to be int32 type," +
` but the dtype was ${sparseIndices.dtype}.`
);
}
if (sparseIndices.rank > 2) {
throw new Error(
"sparseIndices should be a scalar, vector, or matrix," +
` but got shape ${sparseIndices.shape}.`
);
}
const numElems = sparseIndices.rank > 0 ? sparseIndices.shape[0] : 1;
const numDims = sparseIndices.rank > 1 ? sparseIndices.shape[1] : 1;
if (outputShape.length !== numDims) {
throw new Error(
"outputShape has incorrect number of elements:," +
` ${outputShape.length}, should be: ${numDims}.`
);
}
const numValues = sparseValues.size;
if (!(sparseValues.rank === 0 || (sparseValues.rank === 1 && numValues === numElems))) {
throw new Error(
"sparseValues has incorrect shape " +
`${sparseValues.shape}, should be [] or [${numElems}]`
);
}
if (sparseValues.dtype !== defaultValues.dtype) {
throw new Error("sparseValues.dtype must match defaultValues.dtype");
}
}
//# sourceMappingURL=sparse_to_dense_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sparse_to_dense.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts a sparse representation into a dense tensor.
*
* Builds an array dense with shape outputShape such that:
*
* // If sparseIndices is scalar
* dense[i] = (i == sparseIndices ? sparseValues : defaultValue)
*
* // If sparseIndices is a vector, then for each i
* dense[sparseIndices[i]] = sparseValues[i]
*
* // If sparseIndices is an n by d matrix, then for each i in [0, n)
* dense[sparseIndices[i][0], ..., sparseIndices[i][d-1]] = sparseValues[i]
* All other values in dense are set to defaultValue. If sparseValues is a
* scalar, all sparse indices are set to this single value.
*
* If indices are repeated the final value is summed over all values for those
* indices.
*
* ```js
* const indices = tf.tensor1d([4, 5, 6, 1, 2, 3], 'int32');
* const values = tf.tensor1d([10, 11, 12, 13, 14, 15], 'float32');
* const shape = [8];
* tf.sparseToDense(indices, values, shape).print();
* ```
*
* @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.
* sparseIndices[i] contains the complete index where sparseValues[i] will be
* placed.
* @param sparseValues A 0-D or 1-D Tensor. Values
* corresponding to each row of sparseIndices, or a scalar value to be used for
* all sparse indices.
* @param outputShape Shape of the dense output tensor. the type is inferred.
* @param defaultValue Scalar. Value to set for indices not specified in
* sparseIndices. Defaults to zero.
*/
/** @doc {heading: 'Operations', subheading: 'Normalization'} */
function sparseToDense_(sparseIndices, sparseValues, outputShape, defaultValue = 0) {
const $sparseIndices = Object(tensor_util_env["a" /* convertToTensor */])(
sparseIndices,
"sparseIndices",
"sparseToDense",
"int32"
);
const $sparseValues = Object(tensor_util_env["a" /* convertToTensor */])(
sparseValues,
"sparseValues",
"sparseToDense"
);
const $defaultValue = Object(tensor_util_env["a" /* convertToTensor */])(
defaultValue,
"defaultValue",
"sparseToDense",
$sparseValues.dtype
);
sparse_to_dense_util_validateInput(
$sparseIndices,
$sparseValues,
outputShape,
$defaultValue
);
return engine["a" /* ENGINE */].runKernelFunc(
(backend) =>
backend.sparseToDense($sparseIndices, $sparseValues, outputShape, $defaultValue),
{ $sparseIndices, $sparseValues, $defaultValue }
);
}
const sparseToDense = Object(operation["a" /* op */])({ sparseToDense_ });
//# sourceMappingURL=sparse_to_dense.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/gather_nd.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gather slices from input tensor into a Tensor with shape specified by
* `indices`.
*
* `indices` is an K-dimensional integer tensor, best thought of as a
* (K-1)-dimensional tensor of indices into input, where each element defines a
* slice of input:
* output[\\(i_0, ..., i_{K-2}\\)] = input[indices[\\(i_0, ..., i_{K-2}\\)]]
*
* Whereas in `tf.gather`, `indices` defines slices into the first dimension of
* input, in `tf.gatherND`, `indices` defines slices into the first N dimensions
* of input, where N = indices.shape[-1].
*
* The last dimension of indices can be at most the rank of input:
* indices.shape[-1] <= input.rank
*
* The last dimension of `indices` corresponds to elements
* (if indices.shape[-1] == input.rank) or slices
* (if indices.shape[-1] < input.rank) along dimension indices.shape[-1] of
* input.
* The output tensor has shape
* indices.shape[:-1] + input.shape[indices.shape[-1]:]
*
* Note that on CPU, if an out of bound index is found, an error is returned. On
* GPU, if an out of bound index is found, a 0 is stored in the corresponding
* output value.
*
* ```js
* const indices = tf.tensor2d([0, 1, 1, 0], [2,2], 'int32');
* const input = tf.tensor2d([9, 10, 11, 12], [2, 2]);
* tf.gatherND(input, indices).print() // [10, 11]
* ```
*
* @param x The tensor from which to gather values.
* @param indices Index tensor, must be of type int32.
*/
/** @doc {heading: 'Operations', subheading: 'Slicing and Joining'} */
function gatherND_(x, indices) {
const $indices = Object(tensor_util_env["a" /* convertToTensor */])(
indices,
"indices",
"gatherND",
"int32"
);
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "gatherND");
const forward = (backend) => {
return backend.gatherND($x, $indices);
};
const inputs = { params: $x, indices: $indices };
return engine["a" /* ENGINE */].runKernelFunc(
forward,
inputs,
null /* gradient */,
kernel_names["G" /* GatherNd */]
);
}
const gatherND = Object(operation["a" /* op */])({ gatherND_ });
//# sourceMappingURL=gather_nd.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/dropout_util.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Normalize noise shape based on provided tensor and noise shape.
*
* @param x Tensor.
* @param noiseShape The shape for the randomly generated keep/drop flags, as
* an array of numbers. Optional.
* @returns Normalized noise shape.
*/
function getNoiseShape(x, noiseShape) {
if (noiseShape == null) {
return x.shape.slice();
}
if (util["arraysEqual"](x.shape, noiseShape)) {
return noiseShape;
}
if (x.shape.length === noiseShape.length) {
const newDimension = [];
for (let i = 0; i < x.shape.length; i++) {
if (noiseShape[i] == null && x.shape[i] != null) {
newDimension.push(x.shape[i]);
} else {
newDimension.push(noiseShape[i]);
}
}
return newDimension;
}
return noiseShape;
}
//# sourceMappingURL=dropout_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/dropout.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes dropout.
*
* ```js
* const x = tf.tensor1d([1, 2, 2, 1]);
* const rate = 0.75;
* const output = tf.dropout(x, rate);
* output.print();
* ```
*
* @param x A floating point Tensor or TensorLike.
* @param rate A float in the range [0, 1). The probability that each element
* of x is discarded.
* @param noiseShape An array of numbers of type int32, representing the
* shape for randomly generated keep/drop flags. If the noiseShape has null
* value, it will be automatically replaced with the x's relative dimension
* size. Optional.
* @param seed Used to create random seeds. Optional.
* @returns A Tensor of the same shape of x.
*/
/** @doc {heading: 'Operations', subheading: 'Dropout'} */
function dropout_(x, rate, noiseShape, seed) {
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "dropout");
util["assert"](
$x.dtype === "float32",
() =>
`x has to be a floating point tensor since it's going to be ` +
`scaled, but got a ${$x.dtype} tensor instead.`
);
util["assert"](
rate >= 0 && rate < 1,
() => `rate must be a float in the range [0, 1), but got ${rate}.`
);
if (rate === 0) {
return x instanceof dist_tensor["a" /* Tensor */] ? $x.clone() : $x;
}
const $noiseShape = getNoiseShape($x, noiseShape);
const keepProb = 1 - rate;
const multiplier = randomUniform($noiseShape, 0, 1, "float32", seed)
.add(keepProb)
.floor()
.div(keepProb);
return $x.mul(multiplier);
}
const dropout = Object(operation["a" /* op */])({ dropout_ });
//# sourceMappingURL=dropout.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/signal_ops.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.
* =============================================================================
*/
/**
* Generate a Hann window.
*
* See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
*
* ```js
* tf.signal.hannWindow(10).print();
* ```
* @param The length of window
*/
/**
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function hannWindow_(windowLength) {
return cosineWindow(windowLength, 0.5, 0.5);
}
/**
* Generate a hamming window.
*
* See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
*
* ```js
* tf.signal.hammingWindow(10).print();
* ```
* @param The length of window
*/
/**
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function hammingWindow_(windowLength) {
return cosineWindow(windowLength, 0.54, 0.46);
}
/**
* Expands input into frames of frameLength.
* Slides a window size with frameStep.
*
* ```js
* tf.signal.frame([1, 2, 3], 2, 1).print();
* ```
* @param signal The input tensor to be expanded
* @param frameLength Length of each frame
* @param frameStep The frame hop size in samples.
* @param padEnd Whether to pad the end of signal with padValue.
* @param padValue An number to use where the input signal does
* not exist when padEnd is True.
*/
/**
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function frame_(signal, frameLength, frameStep, padEnd = false, padValue = 0) {
let start = 0;
const output = [];
while (start + frameLength <= signal.size) {
output.push(slice(signal, start, frameLength));
start += frameStep;
}
if (padEnd) {
while (start < signal.size) {
const padLen = start + frameLength - signal.size;
const pad = concat([
slice(signal, start, frameLength - padLen),
fill([padLen], padValue),
]);
output.push(pad);
start += frameStep;
}
}
if (output.length === 0) {
return Object(tensor_ops["h" /* tensor2d */])([], [0, frameLength]);
}
return concat(output).as2D(output.length, frameLength);
}
/**
* Computes the Short-time Fourier Transform of signals
* See: https://en.wikipedia.org/wiki/Short-time_Fourier_transform
*
* ```js
* const input = tf.tensor1d([1, 1, 1, 1, 1])
* tf.signal.stft(input, 3, 1).print();
* ```
* @param signal 1-dimensional real value tensor.
* @param frameLength The window length of samples.
* @param frameStep The number of samples to step.
* @param fftLength The size of the FFT to apply.
* @param windowFn A callable that takes a window length and returns 1-d tensor.
*/
/**
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function stft_(signal, frameLength, frameStep, fftLength, windowFn = hannWindow) {
if (fftLength == null) {
fftLength = enclosingPowerOfTwo(frameLength);
}
const framedSignal = signal_ops_frame(signal, frameLength, frameStep);
const windowedSignal = mul(framedSignal, windowFn(frameLength));
const output = [];
for (let i = 0; i < framedSignal.shape[0]; i++) {
output.push(rfft(windowedSignal.slice([i, 0], [1, frameLength]), fftLength));
}
return concat(output);
}
function enclosingPowerOfTwo(value) {
// Return 2**N for integer N such that 2**N >= value.
return Math.floor(Math.pow(2, Math.ceil(Math.log(value) / Math.log(2.0))));
}
function cosineWindow(windowLength, a, b) {
const even = 1 - (windowLength % 2);
const newValues = new Float32Array(windowLength);
for (let i = 0; i < windowLength; ++i) {
const cosArg = (2.0 * Math.PI * i) / (windowLength + even - 1);
newValues[i] = a - b * Math.cos(cosArg);
}
return Object(tensor_ops["g" /* tensor1d */])(newValues, "float32");
}
const hannWindow = Object(operation["a" /* op */])({ hannWindow_ });
const hammingWindow = Object(operation["a" /* op */])({ hammingWindow_ });
const signal_ops_frame = Object(operation["a" /* op */])({ frame_ });
const stft = Object(operation["a" /* op */])({ stft_ });
//# sourceMappingURL=signal_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/in_top_k.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.
* =============================================================================
*/
/**
* Returns whether the targets are in the top K predictions.
*
* ```js
* const predictions = tf.tensor2d([[20, 10, 40, 30], [30, 50, -20, 10]]);
* const targets = tf.tensor1d([2, 0]);
* const precision = await tf.inTopKAsync(predictions, targets);
* precision.print();
* ```
* @param predictions 2-D or higher `tf.Tensor` with last dimension being
* at least `k`.
* @param targets 1-D or higher `tf.Tensor`.
* @param k Optional Number of top elements to look at for computing precision,
* default to 1.
*/
/** @doc {heading: 'Operations', subheading: 'Evaluation'} */
async function inTopKAsync_(predictions, targets, k = 1) {
const $predictions = Object(tensor_util_env["a" /* convertToTensor */])(
predictions,
"predictions",
"inTopK"
);
const $targets = Object(tensor_util_env["a" /* convertToTensor */])(
targets,
"targets",
"inTopK"
);
Object(util["assert"])(
$predictions.rank > 1,
() =>
"inTopK() expects the predictions to be of rank 2 or higher, " +
`but got ${$predictions.rank}`
);
Object(util["assert"])(
$predictions.rank - 1 === $targets.rank,
() =>
`predictions rank should be 1 larger than ` +
`targets rank, but got predictions rank ` +
`${$predictions.rank} and targets rank ${$targets.rank}`
);
Object(util["assertShapesMatch"])(
$predictions.shape.slice(0, $predictions.shape.length - 1),
$targets.shape,
`predictions's shape should be align with the targets' shape, ` +
"except the last dimension."
);
const lastDim = $predictions.shape[$predictions.shape.length - 1];
Object(util["assert"])(
k > 0 && k <= lastDim,
() =>
`'k' passed to inTopK() must be > 0 && <= the predictions last ` +
`dimension (${lastDim}), but got ${k}`
);
const predictionsVals = await $predictions.data();
const targetsVals = await $targets.data();
// Reshape predictionsVals into a 2d tensor [batch, lastDim]
// and look up topK along lastDim.
const [batch, size] = [predictionsVals.length / lastDim, lastDim];
const precision = Object(util["getTypedArrayFromDType"])("bool", batch);
for (let b = 0; b < batch; b++) {
const offset = b * size;
const vals = predictionsVals.subarray(offset, offset + size);
const valAndInd = [];
for (let i = 0; i < vals.length; i++) {
valAndInd.push({ value: vals[i], index: i });
}
valAndInd.sort((a, b) => b.value - a.value);
precision[b] = 0;
for (let i = 0; i < k; i++) {
if (valAndInd[i].index === targetsVals[b]) {
precision[b] = 1;
break;
}
}
}
if (predictions !== $predictions) {
$predictions.dispose();
}
if (targets !== $targets) {
$targets.dispose();
}
// Output precision has the same shape as targets.
return Object(tensor_ops["f" /* tensor */])(precision, $targets.shape, "bool");
}
const inTopKAsync = inTopKAsync_;
//# sourceMappingURL=in_top_k.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/loss_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var Reduction;
(function (Reduction) {
Reduction[(Reduction["NONE"] = 0)] = "NONE";
Reduction[(Reduction["MEAN"] = 1)] = "MEAN";
Reduction[(Reduction["SUM"] = 2)] = "SUM";
Reduction[(Reduction["SUM_BY_NONZERO_WEIGHTS"] = 3)] = "SUM_BY_NONZERO_WEIGHTS";
})(Reduction || (Reduction = {}));
/**
* Computes the weighted loss between two tensors.
*
* @param losses Tensor of shape `[batch_size, d1, ... dN]`.
* @param weights Tensor whose rank is either 0, or the same rank as
* `losses`, and must be broadcastable to `losses` (i.e., all
* dimensions must be either `1`, or the same as the corresponding
* `losses` dimension).
*/
/** @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'} */
function computeWeightedLoss_(losses, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $losses = Object(tensor_util_env["a" /* convertToTensor */])(
losses,
"losses",
"computeWeightedLoss"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"computeWeightedLoss"
);
}
const weightedLoss = $weights == null ? $losses : $losses.mul($weights);
if (reduction === Reduction.NONE) {
return weightedLoss;
}
if (reduction === Reduction.SUM) {
return weightedLoss.sum();
}
if (reduction === Reduction.MEAN) {
if ($weights == null) {
return weightedLoss.mean();
} else {
const broadcastFactor = $losses.size / $weights.size;
const result = weightedLoss.sum().div($weights.sum());
return broadcastFactor > 1
? result.div(Object(tensor_ops["e" /* scalar */])(broadcastFactor))
: result;
}
}
if (reduction === Reduction.SUM_BY_NONZERO_WEIGHTS) {
if ($weights == null) {
return weightedLoss.sum().div(Object(tensor_ops["e" /* scalar */])($losses.size));
} else {
const broadcastedWeights = $weights.mul(
Object(tensor_ops["b" /* ones */])($losses.shape)
);
const numNonZeros = broadcastedWeights
.notEqual(Object(tensor_ops["e" /* scalar */])(0))
.sum()
.toFloat();
return weightedLoss.sum().div(numNonZeros);
}
}
throw Error(`Unknown reduction: ${reduction}`);
}
/**
* Computes the absolute difference loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*/
/** @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'} */
function absoluteDifference_(
labels,
predictions,
weights,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS
) {
const $labels = Object(tensor_util_env["a" /* convertToTensor */])(
labels,
"labels",
"absoluteDifference"
);
const $predictions = Object(tensor_util_env["a" /* convertToTensor */])(
predictions,
"predictions",
"absoluteDifference"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"absoluteDifference"
);
}
Object(util["assertShapesMatch"])(
$labels.shape,
$predictions.shape,
"Error in absoluteDifference: "
);
const losses = $labels.sub($predictions).abs();
return computeWeightedLoss(losses, $weights, reduction);
}
/**
* Computes the mean squared error between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*/
/** @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'} */
function meanSquaredError_(
labels,
predictions,
weights,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS
) {
const $labels = Object(tensor_util_env["a" /* convertToTensor */])(
labels,
"labels",
"meanSquaredError"
);
const $predictions = Object(tensor_util_env["a" /* convertToTensor */])(
predictions,
"predictions",
"meanSquaredError"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"meanSquaredError"
);
}
Object(util["assertShapesMatch"])(
$labels.shape,
$predictions.shape,
"Error in meanSquaredError: "
);
const losses = $labels.squaredDifference($predictions);
return computeWeightedLoss(losses, $weights, reduction);
}
/**
* Computes the cosine distance loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param axis The dimension along which the cosine distance is computed.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*/
/** @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'} */
function cosineDistance_(
labels,
predictions,
axis,
weights,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS
) {
const $labels = Object(tensor_util_env["a" /* convertToTensor */])(
labels,
"labels",
"cosineDistance"
);
const $predictions = Object(tensor_util_env["a" /* convertToTensor */])(
predictions,
"predictions",
"cosineDistance"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"cosineDistance"
);
}
Object(util["assertShapesMatch"])(
$labels.shape,
$predictions.shape,
"Error in cosineDistance: "
);
const one = Object(tensor_ops["e" /* scalar */])(1);
const losses = one.sub($labels.mul($predictions).sum(axis, true));
return computeWeightedLoss(losses, $weights, reduction);
}
/**
* Computes the Hinge loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*/
/** @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'} */
function hingeLoss_(
labels,
predictions,
weights,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS
) {
let $labels = Object(tensor_util_env["a" /* convertToTensor */])(
labels,
"labels",
"hingeLoss"
);
const $predictions = Object(tensor_util_env["a" /* convertToTensor */])(
predictions,
"predictions",
"hingeLoss"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"hingeLoss"
);
}
Object(util["assertShapesMatch"])(
$labels.shape,
$predictions.shape,
"Error in hingeLoss: "
);
const one = Object(tensor_ops["e" /* scalar */])(1);
// Convert binary labels to (-1, 1)
$labels = Object(tensor_ops["e" /* scalar */])(2).mul($labels).sub(one);
const losses = one.sub($labels.mul($predictions)).relu();
return computeWeightedLoss(losses, $weights, reduction);
}
/**
* Computes the log loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param epsilon A small increment to avoid taking log of zero
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*/
/** @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'} */
function logLoss_(
labels,
predictions,
weights,
epsilon = 1e-7,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS
) {
const $labels = Object(tensor_util_env["a" /* convertToTensor */])(
labels,
"labels",
"logLoss"
);
const $predictions = Object(tensor_util_env["a" /* convertToTensor */])(
predictions,
"predictions",
"logLoss"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"logLoss"
);
}
Object(util["assertShapesMatch"])($labels.shape, $predictions.shape, "Error in logLoss: ");
const one = Object(tensor_ops["e" /* scalar */])(1);
const epsilonScalar = Object(tensor_ops["e" /* scalar */])(epsilon);
const losses = $labels
.mul($predictions.add(epsilonScalar).log())
.neg()
.sub(one.sub($labels).mul(one.sub($predictions).add(epsilonScalar).log()));
return computeWeightedLoss(losses, $weights, reduction);
}
function sigmoidCrossEntropyWithLogits_(labels, logits) {
const $labels = Object(tensor_util_env["a" /* convertToTensor */])(
labels,
"labels",
"sigmoidCrossEntropyWithLogits"
);
const $logits = Object(tensor_util_env["a" /* convertToTensor */])(
logits,
"logits",
"sigmoidCrossEntropyWithLogits"
);
Object(util["assertShapesMatch"])(
$labels.shape,
$logits.shape,
"Error in sigmoidCrossEntropyWithLogits: "
);
/**
* Implementation Details:
*
* For brevity, let `x = logits`, `z = labels`. The logistic loss is
* z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
* = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))
* = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
* = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
* = (1 - z) * x + log(1 + exp(-x))
* = x - x * z + log(1 + exp(-x))
*
* For x < 0, to avoid overflow in exp(-x), we reformulate the above
* x - x * z + log(1 + exp(-x))
* = log(exp(x)) - x * z + log(1 + exp(-x))
* = - x * z + log(1 + exp(x))
*
* Hence, to ensure stability and avoid overflow, the implementation uses
* this equivalent formulation:
* max(x, 0) - x * z + log(1 + exp(-abs(x)))
*/
const maxOutput = $logits.relu();
const outputXTarget = $logits.mul($labels);
const sigmoidOutput = $logits.abs().neg().exp().log1p();
return maxOutput.sub(outputXTarget).add(sigmoidOutput);
}
/**
* Computes the sigmoid cross entropy loss between two tensors.
*
* If labelSmoothing is nonzero, smooth the labels towards 1/2:
*
* newMulticlassLabels = multiclassLabels * (1 - labelSmoothing)
* + 0.5 * labelSmoothing
*
* @param multiClassLabels The ground truth output tensor of shape
* [batch_size, num_classes], same dimensions as 'predictions'.
* @param logits The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param labelSmoothing If greater than 0, then smooth the labels.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*/
/** @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' } */
function sigmoidCrossEntropy_(
multiClassLabels,
logits,
weights,
labelSmoothing = 0,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS
) {
let $multiClassLabels = Object(tensor_util_env["a" /* convertToTensor */])(
multiClassLabels,
"multiClassLabels",
"sigmoidCrossEntropy"
);
const $logits = Object(tensor_util_env["a" /* convertToTensor */])(
logits,
"logits",
"sigmoidCrossEntropy"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"sigmoidCrossEntropy"
);
}
Object(util["assertShapesMatch"])(
$multiClassLabels.shape,
$logits.shape,
"Error in sigmoidCrossEntropy: "
);
if (labelSmoothing > 0) {
const labelSmoothingScalar = Object(tensor_ops["e" /* scalar */])(labelSmoothing);
const one = Object(tensor_ops["e" /* scalar */])(1);
const half = Object(tensor_ops["e" /* scalar */])(0.5);
$multiClassLabels = $multiClassLabels
.mul(one.sub(labelSmoothingScalar))
.add(half.mul(labelSmoothingScalar));
}
const losses = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);
return computeWeightedLoss(losses, $weights, reduction);
}
/**
* Computes the huber loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param delta Point where huber loss changes from quadratic to linear.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`.
*/
/** @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'} */
function huberLoss_(
labels,
predictions,
weights,
delta = 1.0,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS
) {
const $labels = Object(tensor_util_env["a" /* convertToTensor */])(
labels,
"labels",
"huberLoss"
);
const $predictions = Object(tensor_util_env["a" /* convertToTensor */])(
predictions,
"predictions",
"huberLoss"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"huberLoss"
);
}
Object(util["assertShapesMatch"])(
$labels.shape,
$predictions.shape,
"Error in huberLoss: "
);
const deltaScalar = Object(tensor_ops["e" /* scalar */])(delta);
const error = $predictions.sub($labels).abs();
const quadratic = minimum(error, deltaScalar);
const linear = error.sub(quadratic);
const losses = Object(tensor_ops["e" /* scalar */])(0.5)
.mul(quadratic.square())
.add(deltaScalar.mul(linear));
return computeWeightedLoss(losses, $weights, reduction);
}
/**
* Computes softmax cross entropy between logits and labels.
*
* Measures the probability error in discrete classification tasks in which
* the classes are mutually exclusive (each entry is in exactly one class).
* For example, each CIFAR-10 image is labeled with one and only one label: an
* image can be a dog or a truck, but not both.
*
* `NOTE`: While the classes are mutually exclusive, their probabilities need
* not be. All that is required is that each row of labels is a valid
* probability distribution. If they are not, the computation of the gradient
* will be incorrect.
*
* `WARNING`: This op expects unscaled logits, since it performs a softmax on
* logits internally for efficiency. Do not call this op with the output of
* softmax, as it will produce incorrect results.
*
* logits and labels must have the same shape, e.g. [batch_size, num_classes]
* and the same dtype.
* @param labels The labels array.
* @param logits The logits array.
* @param dim The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*/
function softmaxCrossEntropyWithLogits_(labels, logits, dim = -1) {
if (dim === -1) {
dim = logits.rank - 1;
}
if (dim !== logits.rank - 1) {
throw Error(
`Softmax cross entropy along a non-last dimension is not yet ` +
`supported. Labels / logits was rank ${logits.rank} ` +
`and dim was ${dim}`
);
}
// Use a custom gradient for numerical stability.
const customOp = customGrad((labels, logits, save) => {
// Reference:
// 1. http://cs231n.github.io/linear-classify/#softmax
// 2. https://blog.feedly.com/tricks-of-the-trade-logsumexp/
const keepDims = true;
const lse = logits.logSumExp([dim], keepDims);
const logResult = logits.toFloat().sub(lse);
save([labels, logResult]);
const costVector = logResult.mul(labels).neg();
const value = costVector.sum([dim]);
const gradFunc = (dy, saved) => {
const [labels, logResult] = saved;
const dyShape = expandShapeToKeepDim(dy.shape, [dim]);
return [
dy.reshape(dyShape).mul(labels.toFloat().sub(logResult.exp())),
dy.reshape(dyShape).mul(logResult.exp().sub(labels.toFloat())),
];
};
return { value, gradFunc };
});
return customOp(labels, logits);
}
/**
* Computes the softmax cross entropy loss between two tensors.
*
* If labelSmoothing is nonzero, smooth the labels towards 1/2:
*
* newOnehotLabels = onehotLabels * (1 - labelSmoothing)
* + labelSmoothing / numClasses
*
* @param onehotLabels One hot encoded labels
* [batch_size, num_classes], same dimensions as 'predictions'.
* @param logits The predicted outputs.
* @param weights Tensor whose rank is either 0, or 1, and must be
* broadcastable to `loss` of shape [batch_size]
* @param labelSmoothing If greater than 0, then smooth the labels.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*/
/** @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' } */
function softmaxCrossEntropy_(
onehotLabels,
logits,
weights,
labelSmoothing = 0,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS
) {
let $onehotLabels = Object(tensor_util_env["a" /* convertToTensor */])(
onehotLabels,
"onehotLabels",
"softmaxCrossEntropy"
);
const $logits = Object(tensor_util_env["a" /* convertToTensor */])(
logits,
"logits",
"softmaxCrossEntropy"
);
let $weights = null;
if (weights != null) {
$weights = Object(tensor_util_env["a" /* convertToTensor */])(
weights,
"weights",
"softmaxCrossEntropy"
);
}
Object(util["assertShapesMatch"])(
$onehotLabels.shape,
$logits.shape,
"Error in softmaxCrossEntropy: "
);
if (labelSmoothing > 0) {
const labelSmoothingScalar = Object(tensor_ops["e" /* scalar */])(labelSmoothing);
const one = Object(tensor_ops["e" /* scalar */])(1);
const numClasses = Object(tensor_ops["e" /* scalar */])($onehotLabels.shape[1]);
$onehotLabels = $onehotLabels
.mul(one.sub(labelSmoothingScalar))
.add(labelSmoothingScalar.div(numClasses));
}
const losses = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);
return computeWeightedLoss(losses, $weights, reduction);
}
const absoluteDifference = Object(operation["a" /* op */])({ absoluteDifference_ });
const computeWeightedLoss = Object(operation["a" /* op */])({ computeWeightedLoss_ });
const cosineDistance = Object(operation["a" /* op */])({ cosineDistance_ });
const hingeLoss = Object(operation["a" /* op */])({ hingeLoss_ });
const huberLoss = Object(operation["a" /* op */])({ huberLoss_ });
const logLoss = Object(operation["a" /* op */])({ logLoss_ });
const meanSquaredError = Object(operation["a" /* op */])({ meanSquaredError_ });
const sigmoidCrossEntropy = Object(operation["a" /* op */])({ sigmoidCrossEntropy_ });
const softmaxCrossEntropy = Object(operation["a" /* op */])({ softmaxCrossEntropy_ });
//# sourceMappingURL=loss_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/linalg_ops.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Linear algebra ops.
*/
/**
* Copy a tensor setting everything outside a central band in each innermost
* matrix to zero.
*
* The band part is computed as follows: Assume input has `k` dimensions
* `[I, J, K, ..., M, N]`, then the output is a tensor with the same shape where
* `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.
* The indicator function
* `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower))`
* `&& (num_upper < 0 || (n-m) <= num_upper)`
*
* ```js
* const x = tf.tensor2d([[ 0, 1, 2, 3],
* [-1, 0, 1, 2],
* [-2, -1, 0, 1],
* [-3, -2, -1, 0]]);
* let y = tf.linalg.bandPart(x, 1, -1);
* y.print(); // [[ 0, 1, 2, 3],
* // [-1, 0, 1, 2],
* // [ 0, -1, 0, 1],
* // [ 0, 0 , -1, 0]]
* let z = tf.linalg.bandPart(x, 2, 1);
* z.print(); // [[ 0, 1, 0, 0],
* // [-1, 0, 1, 0],
* // [-2, -1, 0, 1],
* // [ 0, -2, -1, 0]]
* ```
*
* @param x Rank `k` tensor
* @param numLower Number of subdiagonals to keep.
* If negative, keep entire lower triangle.
* @param numUpper Number of subdiagonals to keep.
* If negative, keep entire upper triangle.
* @returns Rank `k` tensor of the same shape as input.
* The extracted banded tensor.
*/
/**
* @doc {heading:'Operations',
* subheading:'Linear Algebra',
* namespace:'linalg'}
*/
function bandPart_(a, numLower, numUpper) {
if (numLower % 1 !== 0) {
throw new Error(`bandPart(): numLower must be an integer, got ${numLower}.`);
}
if (numUpper % 1 !== 0) {
throw new Error(`bandPart(): numUpper must be an integer, got ${numUpper}.`);
}
const $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "bandPart");
if ($a.rank < 2) {
throw new Error(`bandPart(): Rank must be at least 2, got ${$a.rank}.`);
}
const shape = $a.shape,
[M, N] = $a.shape.slice(-2);
if (!(numLower <= M)) {
throw new Error(
`bandPart(): numLower (${numLower})` +
` must not be greater than the number of rows (${M}).`
);
}
if (!(numUpper <= N)) {
throw new Error(
`bandPart(): numUpper (${numUpper})` +
` must not be greater than the number of columns (${N}).`
);
}
if (numLower < 0) {
numLower = M;
}
if (numUpper < 0) {
numUpper = N;
}
const i = Object(tensor_ops["d" /* range */])(0, M, 1, "int32").reshape([-1, 1]),
j = Object(tensor_ops["d" /* range */])(0, N, 1, "int32"),
ij = sub(i, j);
const inBand = logicalAnd(
ij.lessEqual(Object(tensor_ops["e" /* scalar */])(+numLower, "int32")),
ij.greaterEqual(Object(tensor_ops["e" /* scalar */])(-numUpper, "int32"))
);
const zero = Object(tensor_ops["n" /* zeros */])([M, N], $a.dtype);
return stack(
unstack($a.reshape([-1, M, N])).map((mat) => where(inBand, mat, zero))
).reshape(shape);
}
/**
* Gram-Schmidt orthogonalization.
*
* ```js
* const x = tf.tensor2d([[1, 2], [3, 4]]);
* let y = tf.linalg.gramSchmidt(x);
* y.print();
* console.log('Othogonalized:');
* y.dot(y.transpose()).print(); // should be nearly the identity matrix.
* console.log('First row direction maintained:');
* const data = await y.array();
* console.log(data[0][1] / data[0][0]); // should be nearly 2.
* ```
*
* @param xs The vectors to be orthogonalized, in one of the two following
* formats:
* - An Array of `tf.Tensor1D`.
* - A `tf.Tensor2D`, i.e., a matrix, in which case the vectors are the rows
* of `xs`.
* In each case, all the vectors must have the same length and the length
* must be greater than or equal to the number of vectors.
* @returns The orthogonalized and normalized vectors or matrix.
* Orthogonalization means that the vectors or the rows of the matrix
* are orthogonal (zero inner products). Normalization means that each
* vector or each row of the matrix has an L2 norm that equals `1`.
*/
/**
* @doc {heading:'Operations',
* subheading:'Linear Algebra',
* namespace:'linalg'}
*/
function gramSchmidt_(xs) {
let inputIsTensor2D;
if (Array.isArray(xs)) {
inputIsTensor2D = false;
Object(util["assert"])(
xs != null && xs.length > 0,
() => "Gram-Schmidt process: input must not be null, undefined, or " + "empty"
);
const dim = xs[0].shape[0];
for (let i = 1; i < xs.length; ++i) {
Object(util["assert"])(
xs[i].shape[0] === dim,
() =>
"Gram-Schmidt: Non-unique lengths found in the input vectors: " +
`(${xs[i].shape[0]} vs. ${dim})`
);
}
} else {
inputIsTensor2D = true;
xs = split(xs, xs.shape[0], 0).map((x) => squeeze(x, [0]));
}
Object(util["assert"])(
xs.length <= xs[0].shape[0],
() =>
`Gram-Schmidt: Number of vectors (${xs.length}) exceeds ` +
`number of dimensions (${xs[0].shape[0]}).`
);
const ys = [];
const xs1d = xs;
for (let i = 0; i < xs.length; ++i) {
ys.push(
engine["a" /* ENGINE */].tidy(() => {
let x = xs1d[i];
if (i > 0) {
for (let j = 0; j < i; ++j) {
const proj = sum(ys[j].mul(x)).mul(ys[j]);
x = x.sub(proj);
}
}
return x.div(norm_norm(x, "euclidean"));
})
);
}
if (inputIsTensor2D) {
return stack(ys, 0);
} else {
return ys;
}
}
/**
* Compute QR decomposition of m-by-n matrix using Householder transformation.
*
* Implementation based on
* [http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf]
* (http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf)
*
* ```js
* const a = tf.tensor2d([[1, 2], [3, 4]]);
* let [q, r] = tf.linalg.qr(a);
* console.log('Q');
* q.print();
* console.log('R');
* r.print();
* console.log('Orthogonalized');
* q.dot(q.transpose()).print() // should be nearly the identity matrix.
* console.log('Reconstructed');
* q.dot(r).print(); // should be nearly [[1, 2], [3, 4]];
* ```
*
* @param x The `tf.Tensor` to be QR-decomposed. Must have rank >= 2. Suppose
* it has the shape `[..., M, N]`.
* @param fullMatrices An optional boolean parameter. Defaults to `false`.
* If `true`, compute full-sized `Q`. If `false` (the default),
* compute only the leading N columns of `Q` and `R`.
* @returns An `Array` of two `tf.Tensor`s: `[Q, R]`. `Q` is a unitary matrix,
* i.e., its columns all have unit norm and are mutually orthogonal.
* If `M >= N`,
* If `fullMatrices` is `false` (default),
* - `Q` has a shape of `[..., M, N]`,
* - `R` has a shape of `[..., N, N]`.
* If `fullMatrices` is `true` (default),
* - `Q` has a shape of `[..., M, M]`,
* - `R` has a shape of `[..., M, N]`.
* If `M < N`,
* - `Q` has a shape of `[..., M, M]`,
* - `R` has a shape of `[..., M, N]`.
* @throws If the rank of `x` is less than 2.
*/
/**
* @doc {heading:'Operations',
* subheading:'Linear Algebra',
* namespace:'linalg'}
*/
function qr_(x, fullMatrices = false) {
if (x.rank < 2) {
throw new Error(`qr() requires input tensor to have a rank >= 2, but got rank ${x.rank}`);
} else if (x.rank === 2) {
return qr2d(x, fullMatrices);
} else {
// Rank > 2.
// TODO(cais): Below we split the input into individual 2D tensors,
// perform QR decomposition on them and then stack the results back
// together. We should explore whether this can be parallelized.
const outerDimsProd = x.shape
.slice(0, x.shape.length - 2)
.reduce((value, prev) => value * prev);
const x2ds = unstack(
x.reshape([outerDimsProd, x.shape[x.shape.length - 2], x.shape[x.shape.length - 1]]),
0
);
const q2ds = [];
const r2ds = [];
x2ds.forEach((x2d) => {
const [q2d, r2d] = qr2d(x2d, fullMatrices);
q2ds.push(q2d);
r2ds.push(r2d);
});
const q = stack(q2ds, 0).reshape(x.shape);
const r = stack(r2ds, 0).reshape(x.shape);
return [q, r];
}
}
function qr2d(x, fullMatrices = false) {
return engine["a" /* ENGINE */].tidy(() => {
if (x.shape.length !== 2) {
throw new Error(`qr2d() requires a 2D Tensor, but got a ${x.shape.length}D Tensor.`);
}
const m = x.shape[0];
const n = x.shape[1];
let q = eye(m); // Orthogonal transform so far.
let r = x.clone(); // Transformed matrix so far.
const one2D = Object(tensor_ops["h" /* tensor2d */])([[1]], [1, 1]);
let w = one2D.clone();
const iters = m >= n ? n : m;
for (let j = 0; j < iters; ++j) {
// This tidy within the for-loop ensures we clean up temporary
// tensors as soon as they are no longer needed.
const rTemp = r;
const wTemp = w;
const qTemp = q;
[w, r, q] = engine["a" /* ENGINE */].tidy(() => {
// Find H = I - tau * w * w', to put zeros below R(j, j).
const rjEnd1 = r.slice([j, j], [m - j, 1]);
const normX = rjEnd1.norm();
const rjj = r.slice([j, j], [1, 1]);
// The sign() function returns 0 on 0, which causes division by zero.
const s = Object(tensor_ops["h" /* tensor2d */])([[-1]]).where(
rjj.greater(0),
Object(tensor_ops["h" /* tensor2d */])([[1]])
);
const u1 = rjj.sub(s.mul(normX));
const wPre = rjEnd1.div(u1);
if (wPre.shape[0] === 1) {
w = one2D.clone();
} else {
w = one2D.concat(wPre.slice([1, 0], [wPre.shape[0] - 1, wPre.shape[1]]), 0);
}
const tau = s.matMul(u1).div(normX).neg();
// -- R := HR, Q := QH.
const rjEndAll = r.slice([j, 0], [m - j, n]);
const tauTimesW = tau.mul(w);
const wT = w.transpose();
if (j === 0) {
r = rjEndAll.sub(tauTimesW.matMul(wT.matMul(rjEndAll)));
} else {
const rTimesTau = rjEndAll.sub(tauTimesW.matMul(wT.matMul(rjEndAll)));
r = r.slice([0, 0], [j, n]).concat(rTimesTau, 0);
}
const tawTimesWT = tauTimesW.transpose();
const qAllJEnd = q.slice([0, j], [m, q.shape[1] - j]);
if (j === 0) {
q = qAllJEnd.sub(qAllJEnd.matMul(w).matMul(tawTimesWT));
} else {
const qTimesTau = qAllJEnd.sub(qAllJEnd.matMul(w).matMul(tawTimesWT));
q = q.slice([0, 0], [m, j]).concat(qTimesTau, 1);
}
return [w, r, q];
});
dispose([rTemp, wTemp, qTemp]);
}
if (!fullMatrices && m > n) {
q = q.slice([0, 0], [m, n]);
r = r.slice([0, 0], [n, n]);
}
return [q, r];
});
}
const bandPart = Object(operation["a" /* op */])({ bandPart_ });
const gramSchmidt = Object(operation["a" /* op */])({ gramSchmidt_ });
const qr = Object(operation["a" /* op */])({ qr_ });
//# sourceMappingURL=linalg_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/array_util.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.
* =============================================================================
*/
/**
* Inserts a value into a sorted array. This method allows duplicate, meaning it
* allows inserting duplicate value, in which case, the element will be inserted
* at the lowest index of the value.
* @param arr The array to modify.
* @param element The element to insert.
* @param comparator Optional. If no comparator is specified, elements are
* compared using array_util.defaultComparator, which is suitable for Strings
* and Numbers in ascending arrays. If the array contains multiple instances of
* the target value, the left-most instance will be returned. To provide a
* comparator, it should take 2 arguments to compare and return a negative,
* zero, or a positive number.
*/
function binaryInsert(arr, element, comparator) {
const index = binarySearch(arr, element, comparator);
const insertionPoint = index < 0 ? -(index + 1) : index;
arr.splice(insertionPoint, 0, element);
}
/**
* Searches the array for the target using binary search, returns the index
* of the found element, or position to insert if element not found. If no
* comparator is specified, elements are compared using array_
* util.defaultComparator, which is suitable for Strings and Numbers in
* ascending arrays. If the array contains multiple instances of the target
* value, the left-most instance will be returned.
* @param arr The array to be searched in.
* @param target The target to be searched for.
* @param comparator Should take 2 arguments to compare and return a negative,
* zero, or a positive number.
* @return Lowest index of the target value if found, otherwise the insertion
* point where the target should be inserted, in the form of
* (-insertionPoint - 1).
*/
function binarySearch(arr, target, comparator) {
return binarySearch_(arr, target, comparator || defaultComparator);
}
/**
* Compares its two arguments for order.
* @param a The first element to be compared.
* @param b The second element to be compared.
* @return A negative number, zero, or a positive number as the first
* argument is less than, equal to, or greater than the second.
*/
function defaultComparator(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
}
function binarySearch_(arr, target, comparator) {
let left = 0;
let right = arr.length;
let middle = 0;
let found = false;
while (left < right) {
middle = left + ((right - left) >>> 1);
const compareResult = comparator(target, arr[middle]);
if (compareResult > 0) {
left = middle + 1;
} else {
right = middle;
// If compareResult is 0, the value is found. We record it is found,
// and then keep looking because there may be duplicate.
found = !compareResult;
}
}
return found ? left : -left - 1;
}
//# sourceMappingURL=array_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/non_max_suppression_impl.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Implementation of the NonMaxSuppression kernel shared between webgl and cpu.
*/
function nonMaxSuppressionV3(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
const dummySoftNmsSigma = 0.0;
const result = nonMaxSuppressionImpl_(
boxes,
scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
dummySoftNmsSigma
);
result.selectedScores.dispose();
result.numValidOutputs.dispose();
return result.selectedIndices;
}
function nonMaxSuppressionV5(
boxes,
scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma
) {
// For NonMaxSuppressionV5Op, we always return a second output holding
// corresponding scores.
const returnScoresTensor = true;
const result = nonMaxSuppressionImpl_(
boxes,
scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma,
returnScoresTensor
);
result.numValidOutputs.dispose();
return {
selectedIndices: result.selectedIndices,
selectedScores: result.selectedScores,
};
}
function nonMaxSuppressionImpl_(
boxes,
scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma,
returnScoresTensor = false,
padToMaxOutputSize = false
) {
// The list is sorted in ascending order, so that we can always pop the
// candidate with the largest score in O(1) time.
const candidates = [];
for (let i = 0; i < scores.length; i++) {
if (scores[i] > scoreThreshold) {
candidates.push({ score: scores[i], boxIndex: i, suppressBeginIndex: 0 });
}
}
candidates.sort(ascendingComparator);
// If softNmsSigma is 0, the outcome of this algorithm is exactly same as
// before.
const scale = softNmsSigma > 0 ? -0.5 / softNmsSigma : 0.0;
const selectedIndices = [];
const selectedScores = [];
while (selectedIndices.length < maxOutputSize && candidates.length > 0) {
const candidate = candidates.pop();
const { score: originalScore, boxIndex, suppressBeginIndex } = candidate;
if (originalScore < scoreThreshold) {
break;
}
// Overlapping boxes are likely to have similar scores, therefore we
// iterate through the previously selected boxes backwards in order to
// see if candidate's score should be suppressed. We use
// suppressBeginIndex to track and ensure a candidate can be suppressed
// by a selected box no more than once. Also, if the overlap exceeds
// iouThreshold, we simply ignore the candidate.
let ignoreCandidate = false;
for (let j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {
const iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);
if (iou >= iouThreshold) {
ignoreCandidate = true;
break;
}
candidate.score = candidate.score * suppressWeight(iouThreshold, scale, iou);
if (candidate.score <= scoreThreshold) {
break;
}
}
// At this point, if `candidate.score` has not dropped below
// `scoreThreshold`, then we know that we went through all of the
// previous selections and can safely update `suppressBeginIndex` to the
// end of the selected array. Then we can re-insert the candidate with
// the updated score and suppressBeginIndex back in the candidate list.
// If on the other hand, `candidate.score` has dropped below the score
// threshold, we will not add it back to the candidates list.
candidate.suppressBeginIndex = selectedIndices.length;
if (!ignoreCandidate) {
// Candidate has passed all the tests, and is not suppressed, so
// select the candidate.
if (candidate.score === originalScore) {
selectedIndices.push(boxIndex);
selectedScores.push(candidate.score);
} else if (candidate.score > scoreThreshold) {
// Candidate's score is suppressed but is still high enough to be
// considered, so add back to the candidates list.
binaryInsert(candidates, candidate, ascendingComparator);
}
}
}
// NonMaxSuppressionV4 feature: padding output to maxOutputSize.
const numValidOutputs = selectedIndices.length;
if (padToMaxOutputSize) {
selectedIndices.fill(0, numValidOutputs);
selectedScores.fill(0.0, numValidOutputs);
}
return {
selectedIndices: Object(tensor_ops["g" /* tensor1d */])(selectedIndices, "int32"),
selectedScores: Object(tensor_ops["g" /* tensor1d */])(selectedScores, "float32"),
numValidOutputs: Object(tensor_ops["e" /* scalar */])(numValidOutputs, "int32"),
};
}
function intersectionOverUnion(boxes, i, j) {
const iCoord = boxes.subarray(i * 4, i * 4 + 4);
const jCoord = boxes.subarray(j * 4, j * 4 + 4);
const yminI = Math.min(iCoord[0], iCoord[2]);
const xminI = Math.min(iCoord[1], iCoord[3]);
const ymaxI = Math.max(iCoord[0], iCoord[2]);
const xmaxI = Math.max(iCoord[1], iCoord[3]);
const yminJ = Math.min(jCoord[0], jCoord[2]);
const xminJ = Math.min(jCoord[1], jCoord[3]);
const ymaxJ = Math.max(jCoord[0], jCoord[2]);
const xmaxJ = Math.max(jCoord[1], jCoord[3]);
const areaI = (ymaxI - yminI) * (xmaxI - xminI);
const areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);
if (areaI <= 0 || areaJ <= 0) {
return 0.0;
}
const intersectionYmin = Math.max(yminI, yminJ);
const intersectionXmin = Math.max(xminI, xminJ);
const intersectionYmax = Math.min(ymaxI, ymaxJ);
const intersectionXmax = Math.min(xmaxI, xmaxJ);
const intersectionArea =
Math.max(intersectionYmax - intersectionYmin, 0.0) *
Math.max(intersectionXmax - intersectionXmin, 0.0);
return intersectionArea / (areaI + areaJ - intersectionArea);
}
// A Gaussian penalty function, this method always returns values in [0, 1].
// The weight is a function of similarity, the more overlap two boxes are, the
// smaller the weight is, meaning highly overlapping boxe will be significantly
// penalized. On the other hand, a non-overlapping box will not be penalized.
function suppressWeight(iouThreshold, scale, iou) {
const weight = Math.exp(scale * iou * iou);
return iou <= iouThreshold ? weight : 0.0;
}
function ascendingComparator(c1, c2) {
// For objects with same scores, we make the object with the larger index go
// first. In an array that pops from the end, this means that the object with
// the smaller index will be popped first. This ensures the same output as
// the TensorFlow python version.
return c1.score - c2.score || (c1.score === c2.score && c2.boxIndex - c1.boxIndex);
}
//# sourceMappingURL=non_max_suppression_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/nonmax_util.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nonMaxSuppSanityCheck(
boxes,
scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma
) {
if (iouThreshold == null) {
iouThreshold = 0.5;
}
if (scoreThreshold == null) {
scoreThreshold = Number.NEGATIVE_INFINITY;
}
if (softNmsSigma == null) {
softNmsSigma = 0.0;
}
const numBoxes = boxes.shape[0];
maxOutputSize = Math.min(maxOutputSize, numBoxes);
util["assert"](
0 <= iouThreshold && iouThreshold <= 1,
() => `iouThreshold must be in [0, 1], but was '${iouThreshold}'`
);
util["assert"](
boxes.rank === 2,
() => `boxes must be a 2D tensor, but was of rank '${boxes.rank}'`
);
util["assert"](
boxes.shape[1] === 4,
() => `boxes must have 4 columns, but 2nd dimension was ${boxes.shape[1]}`
);
util["assert"](scores.rank === 1, () => "scores must be a 1D tensor");
util["assert"](
scores.shape[0] === numBoxes,
() =>
`scores has incompatible shape with boxes. Expected ${numBoxes}, ` +
`but was ${scores.shape[0]}`
);
util["assert"](
0 <= softNmsSigma && softNmsSigma <= 1,
() => `softNmsSigma must be in [0, 1], but was '${softNmsSigma}'`
);
return { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
}
//# sourceMappingURL=nonmax_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/non_max_suppression.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nonMaxSuppression_(
boxes,
scores,
maxOutputSize,
iouThreshold = 0.5,
scoreThreshold = Number.NEGATIVE_INFINITY
) {
const $boxes = Object(tensor_util_env["a" /* convertToTensor */])(
boxes,
"boxes",
"nonMaxSuppression"
);
const $scores = Object(tensor_util_env["a" /* convertToTensor */])(
scores,
"scores",
"nonMaxSuppression"
);
const inputs = nonMaxSuppSanityCheck(
$boxes,
$scores,
maxOutputSize,
iouThreshold,
scoreThreshold
);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
const attrs = { maxOutputSize, iouThreshold, scoreThreshold };
return engine["a" /* ENGINE */].runKernelFunc(
(b) => b.nonMaxSuppression($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold),
{ boxes: $boxes, scores: $scores },
null /* grad */,
kernel_names["Z" /* NonMaxSuppressionV3 */],
attrs
);
}
const nonMaxSuppression = Object(operation["a" /* op */])({ nonMaxSuppression_ });
//# sourceMappingURL=non_max_suppression.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/image_ops.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Bilinear resize a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to False. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function resizeBilinear_(images, size, alignCorners = false) {
const $images = Object(tensor_util_env["a" /* convertToTensor */])(
images,
"images",
"resizeBilinear"
);
util["assert"](
$images.rank === 3 || $images.rank === 4,
() => `Error in resizeBilinear: x must be rank 3 or 4, but got ` + `rank ${$images.rank}.`
);
util["assert"](
size.length === 2,
() => `Error in resizeBilinear: new shape must 2D, but got shape ` + `${size}.`
);
let batchImages = $images;
let reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages = $images.as4D(1, $images.shape[0], $images.shape[1], $images.shape[2]);
}
const [newHeight, newWidth] = size;
const forward = (backend, save) => {
save([batchImages]);
return backend.resizeBilinear(batchImages, newHeight, newWidth, alignCorners);
};
const backward = (dy, saved) => {
return {
x: () =>
engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.resizeBilinearBackprop(dy, saved[0], alignCorners),
{}
),
};
};
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
{ x: batchImages },
backward,
"ResizeBilinear",
{ alignCorners, newHeight, newWidth }
);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
}
return res;
}
/**
* NearestNeighbor resize a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to False. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function resizeNearestNeighbor_(images, size, alignCorners = false) {
const $images = Object(tensor_util_env["a" /* convertToTensor */])(
images,
"images",
"resizeNearestNeighbor"
);
util["assert"](
$images.rank === 3 || $images.rank === 4,
() =>
`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got ` +
`rank ${$images.rank}.`
);
util["assert"](
size.length === 2,
() => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ` + `${size}.`
);
util["assert"](
$images.dtype === "float32" || $images.dtype === "int32",
() => "`images` must have `int32` or `float32` as dtype"
);
let batchImages = $images;
let reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages = $images.as4D(1, $images.shape[0], $images.shape[1], $images.shape[2]);
}
const [newHeight, newWidth] = size;
const forward = (backend, save) => {
save([batchImages]);
return backend.resizeNearestNeighbor(batchImages, newHeight, newWidth, alignCorners);
};
const backward = (dy, saved) => {
return {
batchImages: () =>
engine["a" /* ENGINE */].runKernelFunc(
(backend) => backend.resizeNearestNeighborBackprop(dy, saved[0], alignCorners),
{}
),
};
};
const res = engine["a" /* ENGINE */].runKernelFunc(forward, { batchImages }, backward);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
}
return res;
}
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @return A 1D tensor with the selected box indices.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
/** This is the async version of `nonMaxSuppression` */
async function nonMaxSuppressionAsync_(
boxes,
scores,
maxOutputSize,
iouThreshold = 0.5,
scoreThreshold = Number.NEGATIVE_INFINITY
) {
const $boxes = Object(tensor_util_env["a" /* convertToTensor */])(
boxes,
"boxes",
"nonMaxSuppressionAsync"
);
const $scores = Object(tensor_util_env["a" /* convertToTensor */])(
scores,
"scores",
"nonMaxSuppressionAsync"
);
const inputs = nonMaxSuppSanityCheck(
$boxes,
$scores,
maxOutputSize,
iouThreshold,
scoreThreshold
);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);
const boxesVals = boxesAndScores[0];
const scoresVals = boxesAndScores[1];
const res = nonMaxSuppressionV3(
boxesVals,
scoresVals,
maxOutputSize,
iouThreshold,
scoreThreshold
);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return res;
}
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* This op also supports a Soft-NMS mode (c.f.
* Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score
* of other overlapping boxes, therefore favoring different regions of the image
* with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`
* parameter to be larger than 0.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param softNmsSigma A float representing the sigma parameter for Soft NMS.
* When sigma is 0, it falls back to nonMaxSuppression.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - selectedScores: A 1D tensor with the corresponding scores for each
* selected box.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function nonMaxSuppressionWithScore_(
boxes,
scores,
maxOutputSize,
iouThreshold = 0.5,
scoreThreshold = Number.NEGATIVE_INFINITY,
softNmsSigma = 0.0
) {
const $boxes = Object(tensor_util_env["a" /* convertToTensor */])(
boxes,
"boxes",
"nonMaxSuppression"
);
const $scores = Object(tensor_util_env["a" /* convertToTensor */])(
scores,
"scores",
"nonMaxSuppression"
);
const inputs = nonMaxSuppSanityCheck(
$boxes,
$scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma
);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
softNmsSigma = inputs.softNmsSigma;
const attrs = { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
const result = engine["a" /* ENGINE */].runKernel(
"NonMaxSuppressionV5",
{ boxes: $boxes, scores: $scores },
attrs
);
return { selectedIndices: result[0], selectedScores: result[1] };
}
/** This is the async version of `nonMaxSuppressionWithScore` */
async function nonMaxSuppressionWithScoreAsync_(
boxes,
scores,
maxOutputSize,
iouThreshold = 0.5,
scoreThreshold = Number.NEGATIVE_INFINITY,
softNmsSigma = 0.0
) {
const $boxes = Object(tensor_util_env["a" /* convertToTensor */])(
boxes,
"boxes",
"nonMaxSuppressionAsync"
);
const $scores = Object(tensor_util_env["a" /* convertToTensor */])(
scores,
"scores",
"nonMaxSuppressionAsync"
);
const inputs = nonMaxSuppSanityCheck(
$boxes,
$scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma
);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
softNmsSigma = inputs.softNmsSigma;
const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);
const boxesVals = boxesAndScores[0];
const scoresVals = boxesAndScores[1];
const res = nonMaxSuppressionV5(
boxesVals,
scoresVals,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma
);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return res;
}
/**
* Extracts crops from the input image tensor and resizes them using bilinear
* sampling or nearest neighbor sampling (possibly with aspect ratio change)
* to a common output size specified by crop_size.
*
* @param image 4d tensor of shape `[batch,imageHeight,imageWidth, depth]`,
* where imageHeight and imageWidth must be positive, specifying the
* batch of images from which to take crops
* @param boxes 2d float32 tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the normalized
* coordinates of the box in the boxInd[i]'th image in the batch
* @param boxInd 1d int32 tensor of shape `[numBoxes]` with values in range
* `[0, batch)` that specifies the image that the `i`-th box refers to.
* @param cropSize 1d int32 tensor of 2 elements `[cropHeigh, cropWidth]`
* specifying the size to which all crops are resized to.
* @param method Optional string from `'bilinear' | 'nearest'`,
* defaults to bilinear, which specifies the sampling method for resizing
* @param extrapolationValue A threshold for deciding when to remove boxes based
* on score. Defaults to 0.
* @return A 4D tensor of the shape `[numBoxes,cropHeight,cropWidth,depth]`
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function cropAndResize_(image, boxes, boxInd, cropSize, method, extrapolationValue) {
const $image = Object(tensor_util_env["a" /* convertToTensor */])(
image,
"image",
"cropAndResize"
);
const $boxes = Object(tensor_util_env["a" /* convertToTensor */])(
boxes,
"boxes",
"cropAndResize",
"float32"
);
const $boxInd = Object(tensor_util_env["a" /* convertToTensor */])(
boxInd,
"boxInd",
"cropAndResize",
"int32"
);
method = method || "bilinear";
extrapolationValue = extrapolationValue || 0;
const numBoxes = $boxes.shape[0];
util["assert"](
$image.rank === 4,
() => "Error in cropAndResize: image must be rank 4," + `but got rank ${$image.rank}.`
);
util["assert"](
$boxes.rank === 2 && $boxes.shape[1] === 4,
() =>
`Error in cropAndResize: boxes must be have size [${numBoxes},4] ` +
`but had shape ${$boxes.shape}.`
);
util["assert"](
$boxInd.rank === 1 && $boxInd.shape[0] === numBoxes,
() =>
`Error in cropAndResize: boxInd must be have size [${numBoxes}] ` +
`but had shape ${$boxes.shape}.`
);
util["assert"](
cropSize.length === 2,
() =>
`Error in cropAndResize: cropSize must be of length 2, but got ` +
`length ${cropSize.length}.`
);
util["assert"](
cropSize[0] >= 1 && cropSize[1] >= 1,
() => `cropSize must be atleast [1,1], but was ${cropSize}`
);
util["assert"](
method === "bilinear" || method === "nearest",
() => `method must be bilinear or nearest, but was ${method}`
);
const forward = (backend, save) =>
backend.cropAndResize($image, $boxes, $boxInd, cropSize, method, extrapolationValue);
const res = engine["a" /* ENGINE */].runKernelFunc(
forward,
{ images: $image, boxes: $boxes, boxInd: $boxInd },
null /* der */,
"CropAndResize",
{ method, extrapolationValue, cropSize }
);
return res;
}
const resizeBilinear = Object(operation["a" /* op */])({ resizeBilinear_ });
const resizeNearestNeighbor = Object(operation["a" /* op */])({ resizeNearestNeighbor_ });
const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
const nonMaxSuppressionWithScore = Object(operation["a" /* op */])({
nonMaxSuppressionWithScore_,
});
const nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;
const cropAndResize = Object(operation["a" /* op */])({ cropAndResize_ });
//# sourceMappingURL=image_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/fused_util.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.
* =============================================================================
*/
// Whether we should call fused ops.
const shouldFuse = (gradientDepth, activation) => {
const gradientMode = gradientDepth > 0;
return !gradientMode || activation === "linear";
};
//# sourceMappingURL=fused_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/fused_ops.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.
* =============================================================================
*/
// Returns gradient for fused activation.
const getFusedDyActivation = (dy, y, activation) => {
if (activation == null || activation === "linear") {
return dy;
}
if (activation === "relu") {
return dy.mul(y.step());
}
throw new Error(`Gradient for activation ${activation} has not been ` + `implemented yet.`);
};
// Returns gradient for fused bias.
const getFusedBiasGradient = (bias, dyActivation) => {
let res = dyActivation;
const reduceAxes = getReductionAxes(bias.shape, dyActivation.shape);
if (reduceAxes.length > 0) {
res = res.sum(reduceAxes);
}
return res.reshape(bias.shape);
};
const applyActivation = (x, activation, preluActivationWeights) => {
if (activation === "linear") {
return x;
} else if (activation === "relu") {
return relu(x);
} else if (activation === "elu") {
return elu(x);
} else if (activation === "relu6") {
return relu6(x);
} else if (activation === "prelu") {
return prelu(x, preluActivationWeights);
}
throw new Error(`Unknown fused activation ${activation}.`);
};
/**
* Computes the dot product of two matrices with optional activation and bias.
*
* ```js
* const a = tf.tensor2d([-1, -2], [1, 2]);
* const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const bias = tf.tensor2d([1, 2], [1, 2]);
*
* tf.fused.matMul({a, b, bias, activation: 'relu'}).print();
* ```
*
* @param obj An object with the following properties:
* - `a` First matrix in dot product operation.
* - `b` Second matrix in dot product operation.
* - `transposeA` If true, `a` is transposed before multiplication.
* - `transposeB` If true, `b` is transposed before multiplication.
* - `bias` Matrix to be added to the result.
* - `activation` Name of activation kernel (defaults to `linear`).
* - `preluActivationWeights` Tensor of prelu weights.
*/
function fusedMatMul_({
a,
b,
transposeA = false,
transposeB = false,
bias,
activation = "linear",
preluActivationWeights,
}) {
if (shouldFuse(engine["a" /* ENGINE */].state.gradientDepth, activation) === false) {
let result = matMul(a, b, transposeA, transposeB);
if (bias != null) {
result = add(result, bias);
}
return applyActivation(result, activation, preluActivationWeights);
}
let $a = Object(tensor_util_env["a" /* convertToTensor */])(a, "a", "fused matMul");
let $b = Object(tensor_util_env["a" /* convertToTensor */])(b, "b", "fused matMul");
[$a, $b] = Object(tensor_util["makeTypesMatch"])($a, $b);
const innerShapeA = transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];
const innerShapeB = transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];
const outerShapeA = transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];
const outerShapeB = transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];
const outerDimsA = $a.shape.slice(0, -2);
const outerDimsB = $b.shape.slice(0, -2);
const batchDimA = util["sizeFromShape"](outerDimsA);
const batchDimB = util["sizeFromShape"](outerDimsB);
util["assert"](
$a.rank >= 2 && $b.rank >= 2 && $a.rank === $b.rank,
() =>
`Error in fused matMul: inputs must have the same rank of at least ` +
`2, got ranks ${$a.rank} and ${$b.rank}.`
);
util["assert"](
util["arraysEqual"](outerDimsA, outerDimsB),
() =>
`Error in fused matMul: outer dimensions (${outerDimsA}) and (` +
`${outerDimsB}) of Tensors with shapes ${$a.shape} and ` +
`${$b.shape} must match.`
);
util["assert"](
innerShapeA === innerShapeB,
() =>
`Error in fused matMul: inner shapes (${innerShapeA}) and (` +
`${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +
`${$b.shape} and transposeA=${transposeA}` +
` and transposeB=${transposeB} must match.`
);
const outShape = $a.shape.slice(0, -2).concat([outerShapeA, outerShapeB]);
const a3D = transposeA
? $a.as3D(batchDimA, innerShapeA, outerShapeA)
: $a.as3D(batchDimA, outerShapeA, innerShapeA);
const b3D = transposeB
? $b.as3D(batchDimB, outerShapeB, innerShapeB)
: $b.as3D(batchDimB, innerShapeB, outerShapeB);
let $bias;
if (bias != null) {
$bias = Object(tensor_util_env["a" /* convertToTensor */])(bias, "bias", "fused matMul");
[$bias] = Object(tensor_util["makeTypesMatch"])($bias, $a);
assertAndGetBroadcastShape(outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = Object(tensor_util_env["a" /* convertToTensor */])(
preluActivationWeights,
"prelu weights",
"fused matMul"
);
}
const grad = (dy, saved) => {
const [a3D, b3D, y] = saved;
const dyActivation = getFusedDyActivation(dy, y, activation);
let biasGradient = {};
if (bias != null) {
biasGradient = { bias: () => getFusedBiasGradient($bias, dyActivation) };
}
if (!transposeA && !transposeB) {
return Object.assign(
{
a: () => dyActivation.matMul(b3D, false, true),
b: () => a3D.matMul(dyActivation, true, false),
},
biasGradient
);
} else if (!transposeA && transposeB) {
return Object.assign(
{
a: () => dyActivation.matMul(b3D, false, false),
b: () => dyActivation.matMul(a3D, true, false),
},
biasGradient
);
} else if (transposeA && !transposeB) {
return Object.assign(
{
a: () => b3D.matMul(dyActivation, false, true),
b: () => a3D.matMul(dyActivation, false, false),
},
biasGradient
);
} else {
return Object.assign(
{
a: () => b3D.matMul(dyActivation, true, true),
b: () => dyActivation.matMul(a3D, true, true),
},
biasGradient
);
}
};
const inputs = { a: a3D, b: b3D };
if (bias != null) {
inputs.bias = $bias;
}
if (preluActivationWeights != null) {
inputs.preluActivationWeights = $preluActivationWeights;
}
const inputsToSave = [a3D, b3D];
const outputsToSave = [true];
const res = engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const y = backend.fusedBatchMatMul({
a: a3D,
b: b3D,
transposeA,
transposeB,
bias: $bias,
activation,
preluActivationWeights: $preluActivationWeights,
});
save([a3D, b3D, y]);
return y;
},
inputs,
grad,
"_FusedMatMul",
{ transposeA, transposeB, activation },
inputsToSave,
outputsToSave
);
return res.reshape(outShape);
}
/**
* Computes a 2D convolution over the input x, optionally fused with adding a
* bias and applying an activation.
*
* ```js
* const inputDepth = 2;
* const inShape = [2, 2, 2, inputDepth];
* const outputDepth = 2;
* const fSize = 1;
* const pad = 0;
* const strides = 1;
*
* const x = tf.tensor4d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
* 16], inShape);
* const w = tf.tensor4d([-1, 1, -2, 0.5], [fSize, fSize, inputDepth,
* outputDepth]);
*
* tf.fused.conv2d({ x, filter: w, strides, pad, dataFormat: 'NHWC',
* dilations: [1, 1], bias: tf.scalar(5), activation: 'relu' }).print();
* ```
*
* @param obj An object with the following properties:
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid` output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
* @param bias Tensor to be added to the result.
* @param activation Name of activation kernel (defaults to `linear`) to be
* applied
* after biasAdd.
* @param preluActivationWeights Tensor of prelu weights to be applied as part
* of a `prelu` activation, typically the same shape as `x`.
*/
function fusedConv2d_({
x,
filter,
strides,
pad,
dataFormat = "NHWC",
dilations = [1, 1],
dimRoundingMode,
bias,
activation = "linear",
preluActivationWeights,
}) {
activation = activation || "linear";
if (shouldFuse(engine["a" /* ENGINE */].state.gradientDepth, activation) === false) {
let result = conv2d(x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
if (bias != null) {
result = add(result, bias);
}
return applyActivation(result, activation, preluActivationWeights);
}
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "conv2d");
const $filter = Object(tensor_util_env["a" /* convertToTensor */])(
filter,
"filter",
"conv2d"
);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = $x.as4D(1, $x.shape[0], $x.shape[1], $x.shape[2]);
}
util["assert"](
x4D.rank === 4,
() => `Error in fused conv2d: input must be rank 4, but got rank ` + `${x4D.rank}.`
);
util["assert"](
$filter.rank === 4,
() => `Error in fused conv2d: filter must be rank 4, but got rank ` + `${$filter.rank}.`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in fused conv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
util["assert"](
x4D.shape[3] === $filter.shape[2],
() =>
`Error in conv2d: depth of input (${x4D.shape[3]}) must match ` +
`input depth for filter ${$filter.shape[2]}.`
);
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in conv2D: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
util["assert"](
dataFormat === "NHWC",
() =>
`Error in conv2d: got dataFormat of ${dataFormat} but only NHWC is currently supported.`
);
const convInfo = computeConv2DInfo(
x4D.shape,
$filter.shape,
strides,
dilations,
pad,
dimRoundingMode
);
let $bias;
if (bias != null) {
$bias = Object(tensor_util_env["a" /* convertToTensor */])(bias, "bias", "fused conv2d");
[$bias] = Object(tensor_util["makeTypesMatch"])($bias, $x);
assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = Object(tensor_util_env["a" /* convertToTensor */])(
preluActivationWeights,
"prelu weights",
"fused conv2d"
);
}
const grad = (dy, saved) => {
const [$filter, x4D, y] = saved;
const dyActivation = getFusedDyActivation(dy, y, activation);
util["assert"](
tupleValuesAreOne(dilations),
() =>
"Error in gradient of fused conv2D: " +
`dilation rates greater than 1 ` +
`are not yet supported in gradients. Got dilations '${dilations}'`
);
let biasGradient = {};
if (bias != null) {
biasGradient = { bias: () => getFusedBiasGradient($bias, dyActivation) };
}
return Object.assign(
{
x: () => conv2DBackpropInput(x4D.shape, dyActivation, $filter, strides, pad),
filter: () => conv2DBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad),
},
biasGradient
);
};
const inputs = { x: x4D, filter: $filter };
if (bias != null) {
inputs.bias = $bias;
}
if (preluActivationWeights != null) {
inputs.preluActivationWeights = $preluActivationWeights;
}
const inputsToSave = [$filter, x4D];
const outputsToSave = [true]; // Save the only output.
const res = engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.fusedConv2d({
input: x4D,
filter: $filter,
convInfo,
bias: $bias,
activation,
preluActivationWeights: $preluActivationWeights,
});
save([$filter, x4D, res]);
return res;
},
inputs,
grad,
"FusedConv2D",
{ convInfo, activation },
inputsToSave,
outputsToSave
);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
}
return res;
}
/**
* Computes depthwise 2D convolution, optionally fused with adding a
* bias and applying an activation.
*
* Given a 4D `input` array and a `filter` array of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing
* `inChannels` convolutional filters of depth 1, this op applies a
* different filter to each input channel (expanding from 1 channel to
* `channelMultiplier` channels for each), then concatenates the results
* together. The output has `inChannels * channelMultiplier` channels.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
* for more details.
*
* @param obj An object with the following properties:
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
* @param bias Tensor to be added to the result.
* @param activation Name of activation kernel (defaults to `linear`).
* @param preluActivationWeights Tensor of prelu weights to be applied as part
* of a `prelu` activation, typically the same shape as `x`.
*/
function fusedDepthwiseConv2d_({
x,
filter,
strides,
pad,
dataFormat = "NHWC",
dilations = [1, 1],
dimRoundingMode,
bias,
activation = "linear",
preluActivationWeights,
}) {
if (shouldFuse(engine["a" /* ENGINE */].state.gradientDepth, activation) === false) {
let result = depthwiseConv2d(
x,
filter,
strides,
pad,
dataFormat,
dilations,
dimRoundingMode
);
if (bias != null) {
result = add(result, bias);
}
return applyActivation(result, activation, preluActivationWeights);
}
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, "x", "depthwiseConv2d");
const $filter = Object(tensor_util_env["a" /* convertToTensor */])(
filter,
"filter",
"depthwiseConv2d"
);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = $x.as4D(1, $x.shape[0], $x.shape[1], $x.shape[2]);
}
util["assert"](
x4D.rank === 4,
() =>
`Error in fused depthwiseConv2d: input must be rank 4, but got ` + `rank ${x4D.rank}.`
);
util["assert"](
$filter.rank === 4,
() =>
`Error in fused depthwiseConv2d: filter must be rank 4, ` +
`but got rank ${$filter.rank}.`
);
util["assert"](
x4D.shape[3] === $filter.shape[2],
() =>
`Error in fused depthwiseConv2d: number of input channels ` +
`(${x4D.shape[3]}) must match the inChannels dimension in ` +
`filter ${$filter.shape[2]}.`
);
if (dilations == null) {
dilations = [1, 1];
}
util["assert"](
eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in fused depthwiseConv2d: Either strides or dilations must " +
`be 1. Got strides ${strides} and dilations '${dilations}'`
);
if (dimRoundingMode != null) {
util["assert"](
util["isInt"](pad),
() =>
`Error in fused depthwiseConv2d: pad must be an integer when ` +
`using dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`
);
}
const convInfo = computeConv2DInfo(
x4D.shape,
$filter.shape,
strides,
dilations,
pad,
dimRoundingMode,
true /* depthwise */
);
let $bias;
if (bias != null) {
$bias = Object(tensor_util_env["a" /* convertToTensor */])(bias, "bias", "fused conv2d");
[$bias] = Object(tensor_util["makeTypesMatch"])($bias, $x);
assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = Object(tensor_util_env["a" /* convertToTensor */])(
preluActivationWeights,
"prelu weights",
"fused depthwiseConv2d"
);
}
const grad = (dy, saved) => {
util["assert"](
tupleValuesAreOne(dilations),
() =>
"Error in gradient of fused depthwiseConv2d: dilation rates " +
`greater than 1 are not yet supported. Got dilations ` +
`'${dilations}'`
);
const [$filter, x4D, y] = saved;
const dyActivation = getFusedDyActivation(dy, y, activation);
let biasGradient = {};
if (bias != null) {
biasGradient = { bias: () => getFusedBiasGradient($bias, dyActivation) };
}
return Object.assign(
{
x: () =>
depthwiseConv2dNativeBackpropInput(x4D.shape, dyActivation, $filter, convInfo),
filter: () =>
depthwiseConv2dNativeBackpropFilter(x4D, dyActivation, $filter.shape, convInfo),
},
biasGradient
);
};
const inputs = { x: x4D, filter: $filter };
if (bias != null) {
inputs.bias = $bias;
}
if (preluActivationWeights != null) {
inputs.preluActivationWeights = $preluActivationWeights;
}
const inputsToSave = [$filter, x4D];
const outputsToSave = [true];
const res = engine["a" /* ENGINE */].runKernelFunc(
(backend, save) => {
const res = backend.fusedDepthwiseConv2D({
input: x4D,
filter: $filter,
convInfo,
bias: $bias,
activation,
preluActivationWeights: $preluActivationWeights,
});
save([$filter, x4D, res]);
return res;
},
inputs,
grad,
"FusedDepthwiseConv2D",
{ convInfo, activation },
inputsToSave,
outputsToSave
);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
}
return res;
}
const fused_ops_matMul = Object(operation["a" /* op */])({ fusedMatMul_ });
const fused_ops_conv2d = Object(operation["a" /* op */])({ fusedConv2d_ });
const fused_ops_depthwiseConv2d = Object(operation["a" /* op */])({ fusedDepthwiseConv2d_ });
//# sourceMappingURL=fused_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/ops.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Modularized ops.
// Second level exports.
//# sourceMappingURL=ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/optimizer.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @doc {heading: 'Training', subheading: 'Classes', namespace: 'train'} */
class optimizer_Optimizer extends Serializable {
/**
* Executes `f()` and minimizes the scalar output of `f()` by computing
* gradients of y with respect to the list of trainable variables provided by
* `varList`. If no list is provided, it defaults to all trainable variables.
*
* @param f The function to execute and whose output to minimize.
* @param returnCost Whether to return the scalar cost value produced by
* executing `f()`.
* @param varList An optional list of variables to update. If specified, only
* the trainable variables in varList will be updated by minimize. Defaults to
* all trainable variables.
*/
/** @doc {heading: 'Training', subheading: 'Optimizers'} */
minimize(f, returnCost = false, varList) {
const { value, grads } = this.computeGradients(f, varList);
if (varList != null) {
const gradArray = varList.map((v) => ({ name: v.name, tensor: grads[v.name] }));
this.applyGradients(gradArray);
} else {
this.applyGradients(grads);
}
// Dispose gradients.
dispose(grads);
if (returnCost) {
return value;
} else {
value.dispose();
return null;
}
}
/**
* The number of iterations that this optimizer instance has been invoked for.
*/
get iterations() {
if (this.iterations_ == null) {
this.iterations_ = 0;
}
return this.iterations_;
}
incrementIterations() {
this.iterations_ = this.iterations + 1;
}
/**
* Executes f() and computes the gradient of the scalar output of f() with
* respect to the list of trainable variables provided by `varList`. If no
* list is provided, it defaults to all trainable variables.
*
* @param f The function to execute and whose output to use for computing
* gradients with respect to variables.
* @param varList An optional list of variables to compute gradients with
* respect to. If specified, only the trainable variables in varList will have
* gradients computed with respect to. Defaults to all trainable variables.
*/
computeGradients(f, varList) {
return variableGrads(f, varList);
}
/**
* Dispose the variables (if any) owned by this optimizer instance.
*/
dispose() {
if (this.iterations_ != null) {
dispose(this.iterations_);
}
}
async saveIterations() {
if (this.iterations_ == null) {
this.iterations_ = 0;
}
return {
name: "iter",
// TODO(cais): Use 'int64' type when available.
tensor: Object(tensor_ops["e" /* scalar */])(this.iterations_, "int32"),
};
}
async getWeights() {
throw new Error("getWeights() is not implemented for this optimizer yet.");
}
async setWeights(weightValues) {
throw new Error(
`setWeights() is not implemented for this optimizer class ` + `${this.getClassName()}`
);
}
/**
* Extract the first element of the weight values and set it
* as the iterations counter variable of this instance of optimizer.
*
* @param weightValues
* @returns Weight values with the first element consumed and excluded.
*/
async extractIterations(weightValues) {
this.iterations_ = (await weightValues[0].tensor.data())[0];
return weightValues.slice(1);
}
}
Object.defineProperty(optimizer_Optimizer, Symbol.hasInstance, {
value: (instance) => {
return (
instance.minimize != null &&
instance.computeGradients != null &&
instance.applyGradients != null
);
},
});
//# sourceMappingURL=optimizer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/adadelta_optimizer.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @doclink Optimizer */
class adadelta_optimizer_AdadeltaOptimizer extends optimizer_Optimizer {
constructor(learningRate, rho, epsilon = null) {
super();
this.learningRate = learningRate;
this.rho = rho;
this.epsilon = epsilon;
this.accumulatedGrads = [];
this.accumulatedUpdates = [];
if (epsilon == null) {
this.epsilon = engine["a" /* ENGINE */].backend.epsilon();
}
}
applyGradients(variableGradients) {
const variableNames = Array.isArray(variableGradients)
? variableGradients.map((item) => item.name)
: Object.keys(variableGradients);
variableNames.forEach((name, i) => {
const value = engine["a" /* ENGINE */].registeredVariables[name];
const trainable = false;
if (this.accumulatedGrads[i] == null) {
this.accumulatedGrads[i] = {
originalName: `${name}/accum_grad`,
variable: tidy(() =>
Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable)
),
};
}
if (this.accumulatedUpdates[i] == null) {
this.accumulatedUpdates[i] = {
originalName: `${name}/accum_var`,
variable: tidy(() =>
Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable)
),
};
}
const gradient = Array.isArray(variableGradients)
? variableGradients[i].tensor
: variableGradients[name];
if (gradient == null) {
return;
}
const accumulatedGrad = this.accumulatedGrads[i].variable;
const accumulatedUpdate = this.accumulatedUpdates[i].variable;
tidy(() => {
const newAccumulatedGrad = accumulatedGrad
.mul(this.rho)
.add(gradient.square().mul(1 - this.rho));
const updates = accumulatedUpdate
.add(this.epsilon)
.sqrt()
.div(accumulatedGrad.add(this.epsilon).sqrt())
.mul(gradient);
const newAccumulatedUpdate = accumulatedUpdate
.mul(this.rho)
.add(updates.square().mul(1 - this.rho));
accumulatedGrad.assign(newAccumulatedGrad);
accumulatedUpdate.assign(newAccumulatedUpdate);
const newValue = updates.mul(-this.learningRate).add(value);
value.assign(newValue);
});
});
this.incrementIterations();
}
dispose() {
if (this.accumulatedUpdates != null) {
dispose(this.accumulatedGrads.map((v) => v.variable));
dispose(this.accumulatedUpdates.map((v) => v.variable));
}
}
async getWeights() {
// Order matters for Python compatibility.
const variables = [...this.accumulatedGrads, ...this.accumulatedUpdates];
return [await this.saveIterations()].concat(
variables.map((v) => ({ name: v.originalName, tensor: v.variable }))
);
}
async setWeights(weightValues) {
weightValues = await this.extractIterations(weightValues);
const variableCount = weightValues.length / 2;
const trainable = false;
this.accumulatedGrads = weightValues.slice(0, variableCount).map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
this.accumulatedUpdates = weightValues
.slice(variableCount, variableCount * 2)
.map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
}
getConfig() {
return {
learningRate: this.learningRate,
rho: this.rho,
epsilon: this.epsilon,
};
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(config["learningRate"], config["rho"], config["epsilon"]);
}
}
/** @nocollapse */
adadelta_optimizer_AdadeltaOptimizer.className = "Adadelta"; // Name matters for Python compatibility.
registerClass(adadelta_optimizer_AdadeltaOptimizer);
//# sourceMappingURL=adadelta_optimizer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/adagrad_optimizer.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @doclink Optimizer */
class adagrad_optimizer_AdagradOptimizer extends optimizer_Optimizer {
constructor(learningRate, initialAccumulatorValue = 0.1) {
super();
this.learningRate = learningRate;
this.initialAccumulatorValue = initialAccumulatorValue;
this.accumulatedGrads = [];
}
applyGradients(variableGradients) {
const variableNames = Array.isArray(variableGradients)
? variableGradients.map((item) => item.name)
: Object.keys(variableGradients);
variableNames.forEach((name, i) => {
const value = engine["a" /* ENGINE */].registeredVariables[name];
if (this.accumulatedGrads[i] == null) {
const trainable = false;
this.accumulatedGrads[i] = {
originalName: `${name}/accumulator`,
variable: tidy(() =>
fill(value.shape, this.initialAccumulatorValue).variable(trainable)
),
};
}
const gradient = Array.isArray(variableGradients)
? variableGradients[i].tensor
: variableGradients[name];
if (gradient == null) {
return;
}
const accumulatedGrad = this.accumulatedGrads[i].variable;
tidy(() => {
const newAccumulatedGrad = accumulatedGrad.add(gradient.square());
accumulatedGrad.assign(newAccumulatedGrad);
const newValue = gradient
.div(newAccumulatedGrad.add(engine["a" /* ENGINE */].backend.epsilon()).sqrt())
.mul(-this.learningRate)
.add(value);
value.assign(newValue);
});
});
this.incrementIterations();
}
dispose() {
if (this.accumulatedGrads != null) {
dispose(this.accumulatedGrads.map((v) => v.variable));
}
}
async getWeights() {
// Order matters for Python compatibility.
return [await this.saveIterations()].concat(
this.accumulatedGrads.map((v) => ({ name: v.originalName, tensor: v.variable }))
);
}
async setWeights(weightValues) {
weightValues = await this.extractIterations(weightValues);
const trainable = false;
this.accumulatedGrads = weightValues.map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
}
getConfig() {
return {
learningRate: this.learningRate,
initialAccumulatorValue: this.initialAccumulatorValue,
};
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(config["learningRate"], config["initialAccumulatorValue"]);
}
}
/** @nocollapse */
adagrad_optimizer_AdagradOptimizer.className = "Adagrad"; // Note: Name matters for Python compatibility.
registerClass(adagrad_optimizer_AdagradOptimizer);
//# sourceMappingURL=adagrad_optimizer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/adam_optimizer.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class adam_optimizer_AdamOptimizer extends optimizer_Optimizer {
constructor(learningRate, beta1, beta2, epsilon = null) {
super();
this.learningRate = learningRate;
this.beta1 = beta1;
this.beta2 = beta2;
this.epsilon = epsilon;
this.accumulatedFirstMoment = [];
this.accumulatedSecondMoment = [];
tidy(() => {
// accB* will be updated by batch.
this.accBeta1 = Object(tensor_ops["e" /* scalar */])(beta1).variable();
this.accBeta2 = Object(tensor_ops["e" /* scalar */])(beta2).variable();
});
if (epsilon == null) {
this.epsilon = engine["a" /* ENGINE */].backend.epsilon();
}
}
applyGradients(variableGradients) {
const varNames = Array.isArray(variableGradients)
? variableGradients.map((v) => v.name)
: Object.keys(variableGradients);
tidy(() => {
const oneMinusAccBeta1 = sub(1, this.accBeta1);
const oneMinusAccBeta2 = sub(1, this.accBeta2);
varNames.forEach((name, i) => {
const value = engine["a" /* ENGINE */].registeredVariables[name];
const trainable = false;
if (this.accumulatedFirstMoment[i] == null) {
this.accumulatedFirstMoment[i] = {
originalName: `${name}/m`,
variable: tidy(() =>
Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable)
),
};
}
if (this.accumulatedSecondMoment[i] == null) {
this.accumulatedSecondMoment[i] = {
originalName: `${name}/v`,
variable: tidy(() =>
Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable)
),
};
}
const gradient = Array.isArray(variableGradients)
? variableGradients[i].tensor
: variableGradients[name];
if (gradient == null) {
return;
}
const firstMoment = this.accumulatedFirstMoment[i].variable;
const secondMoment = this.accumulatedSecondMoment[i].variable;
const newFirstMoment = firstMoment.mul(this.beta1).add(gradient.mul(1 - this.beta1));
const newSecondMoment = secondMoment
.mul(this.beta2)
.add(gradient.square().mul(1 - this.beta2));
const biasCorrectedFirstMoment = newFirstMoment.div(oneMinusAccBeta1);
const biasCorrectedSecondMoment = newSecondMoment.div(oneMinusAccBeta2);
firstMoment.assign(newFirstMoment);
secondMoment.assign(newSecondMoment);
const newValue = biasCorrectedFirstMoment
.div(biasCorrectedSecondMoment.sqrt().add(this.epsilon))
.mul(-this.learningRate)
.add(value);
value.assign(newValue);
});
this.accBeta1.assign(this.accBeta1.mul(this.beta1));
this.accBeta2.assign(this.accBeta2.mul(this.beta2));
});
this.incrementIterations();
}
dispose() {
this.accBeta1.dispose();
this.accBeta2.dispose();
if (this.accumulatedFirstMoment != null) {
dispose(this.accumulatedFirstMoment.map((v) => v.variable));
}
if (this.accumulatedSecondMoment != null) {
dispose(this.accumulatedSecondMoment.map((v) => v.variable));
}
}
async getWeights() {
// Order matters for Python compatibility.
const variables = [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];
return [await this.saveIterations()].concat(
variables.map((v) => ({ name: v.originalName, tensor: v.variable }))
);
}
async setWeights(weightValues) {
weightValues = await this.extractIterations(weightValues);
tidy(() => {
this.accBeta1.assign(pow(this.beta1, this.iterations_ + 1));
this.accBeta2.assign(pow(this.beta2, this.iterations_ + 1));
});
const variableCount = weightValues.length / 2;
const trainable = false;
this.accumulatedFirstMoment = weightValues.slice(0, variableCount).map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
this.accumulatedSecondMoment = weightValues
.slice(variableCount, variableCount * 2)
.map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
}
getConfig() {
return {
learningRate: this.learningRate,
beta1: this.beta1,
beta2: this.beta2,
epsilon: this.epsilon,
};
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(
config["learningRate"],
config["beta1"],
config["beta2"],
config["epsilon"]
);
}
}
/** @nocollapse */
adam_optimizer_AdamOptimizer.className = "Adam"; // Note: Name matters for Python compatibility.
registerClass(adam_optimizer_AdamOptimizer);
//# sourceMappingURL=adam_optimizer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/adamax_optimizer.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class adamax_optimizer_AdamaxOptimizer extends optimizer_Optimizer {
constructor(learningRate, beta1, beta2, epsilon = null, decay = 0.0) {
super();
this.learningRate = learningRate;
this.beta1 = beta1;
this.beta2 = beta2;
this.epsilon = epsilon;
this.decay = decay;
this.accumulatedFirstMoment = [];
this.accumulatedWeightedInfNorm = [];
tidy(() => {
this.iteration = Object(tensor_ops["e" /* scalar */])(0).variable();
this.accBeta1 = Object(tensor_ops["e" /* scalar */])(beta1).variable();
});
if (epsilon == null) {
this.epsilon = engine["a" /* ENGINE */].backend.epsilon();
}
}
applyGradients(variableGradients) {
const variableNames = Array.isArray(variableGradients)
? variableGradients.map((item) => item.name)
: Object.keys(variableGradients);
tidy(() => {
const oneMinusAccBeta1 = sub(1, this.accBeta1);
const lr = div(-this.learningRate, this.iteration.mul(this.decay).add(1));
variableNames.forEach((name, i) => {
const value = engine["a" /* ENGINE */].registeredVariables[name];
const trainable = false;
if (this.accumulatedFirstMoment[i] == null) {
this.accumulatedFirstMoment[i] = {
originalName: `${name}/m`,
variable: Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable),
};
}
if (this.accumulatedWeightedInfNorm[i] == null) {
this.accumulatedWeightedInfNorm[i] = {
originalName: `${name}/v`,
variable: Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable),
};
}
const gradient = Array.isArray(variableGradients)
? variableGradients[i].tensor
: variableGradients[name];
if (gradient == null) {
return;
}
const firstMoment = this.accumulatedFirstMoment[i].variable;
const weightedInfNorm = this.accumulatedWeightedInfNorm[i].variable;
const newFirstMoment = firstMoment.mul(this.beta1).add(gradient.mul(1 - this.beta1));
const ut0 = weightedInfNorm.mul(this.beta2);
const ut1 = gradient.abs();
const newWeightedInfNorm = ut0.maximum(ut1);
firstMoment.assign(newFirstMoment);
weightedInfNorm.assign(newWeightedInfNorm);
const newValue = lr
.div(oneMinusAccBeta1)
.mul(newFirstMoment.div(newWeightedInfNorm.add(this.epsilon)))
.add(value);
value.assign(newValue);
});
this.iteration.assign(this.iteration.add(1));
this.accBeta1.assign(this.accBeta1.mul(this.beta1));
});
this.incrementIterations();
}
dispose() {
this.accBeta1.dispose();
this.iteration.dispose();
if (this.accumulatedFirstMoment != null) {
dispose(this.accumulatedFirstMoment.map((v) => v.variable));
}
if (this.accumulatedWeightedInfNorm != null) {
dispose(this.accumulatedWeightedInfNorm.map((v) => v.variable));
}
}
async getWeights() {
throw new Error("getWeights() is not implemented for Adamax yet.");
}
async setWeights(weightValues) {
throw new Error("setWeights() is not implemented for Adamax yet.");
}
getConfig() {
return {
learningRate: this.learningRate,
beta1: this.beta1,
beta2: this.beta2,
epsilon: this.epsilon,
decay: this.decay,
};
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(
config["learningRate"],
config["beta1"],
config["beta2"],
config["epsilon"],
config["decay"]
);
}
}
/** @nocollapse */
adamax_optimizer_AdamaxOptimizer.className = "Adamax"; // Note: Name matters for Python compatbility.
registerClass(adamax_optimizer_AdamaxOptimizer);
//# sourceMappingURL=adamax_optimizer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/sgd_optimizer.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @doclink Optimizer */
class sgd_optimizer_SGDOptimizer extends optimizer_Optimizer {
constructor(learningRate) {
super();
this.learningRate = learningRate;
this.setLearningRate(learningRate);
}
applyGradients(variableGradients) {
const varNames = Array.isArray(variableGradients)
? variableGradients.map((v) => v.name)
: Object.keys(variableGradients);
varNames.forEach((name, i) => {
const gradient = Array.isArray(variableGradients)
? variableGradients[i].tensor
: variableGradients[name];
if (gradient == null) {
return;
}
const value = engine["a" /* ENGINE */].registeredVariables[name];
tidy(() => {
const newValue = this.c.mul(gradient).add(value);
value.assign(newValue);
});
});
this.incrementIterations();
}
/**
* Sets the learning rate of the optimizer.
*/
setLearningRate(learningRate) {
this.learningRate = learningRate;
if (this.c != null) {
this.c.dispose();
}
this.c = keep(Object(tensor_ops["e" /* scalar */])(-learningRate));
}
dispose() {
this.c.dispose();
}
async getWeights() {
return [await this.saveIterations()];
}
async setWeights(weightValues) {
weightValues = await this.extractIterations(weightValues);
if (weightValues.length !== 0) {
throw new Error("SGD optimizer does not have settable weights.");
}
}
getConfig() {
return { learningRate: this.learningRate };
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(config["learningRate"]);
}
}
/** @nocollapse */
sgd_optimizer_SGDOptimizer.className = "SGD"; // Note: Name matters for Python compatibility.
registerClass(sgd_optimizer_SGDOptimizer);
//# sourceMappingURL=sgd_optimizer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/momentum_optimizer.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @doclink Optimizer */
class momentum_optimizer_MomentumOptimizer extends sgd_optimizer_SGDOptimizer {
constructor(learningRate, momentum, useNesterov = false) {
super(learningRate);
this.learningRate = learningRate;
this.momentum = momentum;
this.useNesterov = useNesterov;
this.accumulations = [];
this.m = Object(tensor_ops["e" /* scalar */])(this.momentum);
}
applyGradients(variableGradients) {
const variableNames = Array.isArray(variableGradients)
? variableGradients.map((item) => item.name)
: Object.keys(variableGradients);
variableNames.forEach((name, i) => {
const value = engine["a" /* ENGINE */].registeredVariables[name];
if (this.accumulations[i] == null) {
const trainable = false;
this.accumulations[i] = {
originalName: `${name}/momentum`,
variable: tidy(() =>
Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable)
),
};
}
const accumulation = this.accumulations[i].variable;
const gradient = Array.isArray(variableGradients)
? variableGradients[i].tensor
: variableGradients[name];
if (gradient == null) {
return;
}
tidy(() => {
let newValue;
const newAccumulation = this.m.mul(accumulation).add(gradient);
if (this.useNesterov) {
newValue = this.c.mul(gradient.add(newAccumulation.mul(this.m))).add(value);
} else {
newValue = this.c.mul(newAccumulation).add(value);
}
accumulation.assign(newAccumulation);
value.assign(newValue);
});
});
this.incrementIterations();
}
dispose() {
this.m.dispose();
if (this.accumulations != null) {
dispose(this.accumulations.map((v) => v.variable));
}
}
/**
* Sets the momentum of the optimizer.
*
* @param momentum
*/
setMomentum(momentum) {
this.momentum = momentum;
}
async getWeights() {
// Order matters for Python compatibility.
return [await this.saveIterations()].concat(
this.accumulations.map((v) => ({ name: v.originalName, tensor: v.variable }))
);
}
async setWeights(weightValues) {
weightValues = await this.extractIterations(weightValues);
const trainable = false;
this.accumulations = weightValues.map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
}
getConfig() {
return {
learningRate: this.learningRate,
momentum: this.momentum,
useNesterov: this.useNesterov,
};
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(config["learningRate"], config["momentum"], config["useNesterov"]);
}
}
/** @nocollapse */
momentum_optimizer_MomentumOptimizer.className = "Momentum"; // Name matters for Python compatibility.
registerClass(momentum_optimizer_MomentumOptimizer);
//# sourceMappingURL=momentum_optimizer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/rmsprop_optimizer.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @doclink Optimizer */
class rmsprop_optimizer_RMSPropOptimizer extends optimizer_Optimizer {
constructor(learningRate, decay = 0.9, momentum = 0.0, epsilon = null, centered = false) {
super();
this.learningRate = learningRate;
this.decay = decay;
this.momentum = momentum;
this.epsilon = epsilon;
this.accumulatedMeanSquares = [];
this.accumulatedMoments = [];
this.accumulatedMeanGrads = [];
this.centered = centered;
if (epsilon == null) {
this.epsilon = engine["a" /* ENGINE */].backend.epsilon();
}
if (learningRate == null) {
throw new Error(`learningRate for RMSPropOptimizer must be defined.`);
}
}
applyGradients(variableGradients) {
const variableNames = Array.isArray(variableGradients)
? variableGradients.map((item) => item.name)
: Object.keys(variableGradients);
variableNames.forEach((name, i) => {
const value = engine["a" /* ENGINE */].registeredVariables[name];
const trainable = false;
if (this.accumulatedMeanSquares[i] == null) {
this.accumulatedMeanSquares[i] = {
originalName: `${name}/rms`,
variable: tidy(() =>
Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable)
),
};
}
if (this.accumulatedMoments[i] == null) {
this.accumulatedMoments[i] = {
originalName: `${name}/momentum`,
variable: tidy(() =>
Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable)
),
};
}
if (this.accumulatedMeanGrads[i] == null && this.centered) {
this.accumulatedMeanGrads[i] = {
originalName: `${name}/mg`,
variable: tidy(() =>
Object(tensor_ops["o" /* zerosLike */])(value).variable(trainable)
),
};
}
const gradient = Array.isArray(variableGradients)
? variableGradients[i].tensor
: variableGradients[name];
if (gradient == null) {
return;
}
const accumulatedMeanSquare = this.accumulatedMeanSquares[i].variable;
const accumulatedMoments = this.accumulatedMoments[i].variable;
tidy(() => {
const newAccumulatedMeanSquare = accumulatedMeanSquare
.mul(this.decay)
.add(gradient.square().mul(1 - this.decay));
if (this.centered) {
const accumulatedMeanGrad = this.accumulatedMeanGrads[i].variable;
// Centered gradient
const newAccumulatedMeanGrad = accumulatedMeanGrad
.mul(this.decay)
.add(gradient.mul(1 - this.decay));
const newAccumulatedMoments = accumulatedMoments
.mul(this.momentum)
.add(
gradient
.mul(this.learningRate)
.div(
newAccumulatedMeanSquare
.sub(newAccumulatedMeanGrad.square().add(this.epsilon))
.sqrt()
)
);
accumulatedMeanSquare.assign(newAccumulatedMeanSquare);
accumulatedMeanGrad.assign(newAccumulatedMeanGrad);
accumulatedMoments.assign(newAccumulatedMoments);
const newValue = value.sub(newAccumulatedMoments);
value.assign(newValue);
} else {
// Plain gradient
const newAccumulatedMeanSquare = accumulatedMeanSquare
.mul(this.decay)
.add(gradient.square().mul(1 - this.decay));
const newAccumulatedMoments = accumulatedMoments
.mul(this.momentum)
.add(
gradient
.mul(this.learningRate)
.div(newAccumulatedMeanSquare.add(this.epsilon).sqrt())
);
accumulatedMeanSquare.assign(newAccumulatedMeanSquare);
accumulatedMoments.assign(newAccumulatedMoments);
const newValue = value.sub(newAccumulatedMoments);
value.assign(newValue);
}
});
});
this.incrementIterations();
}
dispose() {
if (this.accumulatedMeanSquares != null) {
dispose(this.accumulatedMeanSquares.map((v) => v.variable));
}
if (this.accumulatedMeanGrads != null && this.centered) {
dispose(this.accumulatedMeanGrads.map((v) => v.variable));
}
if (this.accumulatedMoments != null) {
dispose(this.accumulatedMoments.map((v) => v.variable));
}
}
async getWeights() {
// Order matters for Python compatibility.
const variables = [...this.accumulatedMeanSquares, ...this.accumulatedMoments];
if (this.centered) {
variables.push(...this.accumulatedMeanGrads);
}
return [await this.saveIterations()].concat(
variables.map((v) => ({ name: v.originalName, tensor: v.variable }))
);
}
async setWeights(weightValues) {
weightValues = await this.extractIterations(weightValues);
const variableCount = this.centered ? weightValues.length / 3 : weightValues.length / 2;
const trainable = false;
this.accumulatedMeanSquares = weightValues.slice(0, variableCount).map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
this.accumulatedMoments = weightValues
.slice(variableCount, variableCount * 2)
.map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
if (this.centered) {
this.accumulatedMeanGrads = weightValues
.slice(variableCount * 2, variableCount * 3)
.map((v) => ({
originalName: v.name,
variable: v.tensor.variable(trainable),
}));
}
}
getConfig() {
return {
learningRate: this.learningRate,
decay: this.decay,
momentum: this.momentum,
epsilon: this.epsilon,
centered: this.centered,
};
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(
config["learningRate"],
config["decay"],
config["momentum"],
config["epsilon"],
config["centered"]
);
}
}
/** @nocollapse */
rmsprop_optimizer_RMSPropOptimizer.className = "RMSProp"; // Note: Name matters for Python compatibility.
registerClass(rmsprop_optimizer_RMSPropOptimizer);
//# sourceMappingURL=rmsprop_optimizer.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/types.js
var dist_types = __webpack_require__(23);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/optimizers/optimizer_constructors.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class optimizer_constructors_OptimizerConstructors {
/**
* Constructs a `tf.SGDOptimizer` that uses stochastic gradient descent.
*
* ```js
* // Fit a quadratic function by learning the coefficients a, b, c.
* const xs = tf.tensor1d([0, 1, 2, 3]);
* const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);
*
* const a = tf.scalar(Math.random()).variable();
* const b = tf.scalar(Math.random()).variable();
* const c = tf.scalar(Math.random()).variable();
*
* // y = a * x^2 + b * x + c.
* const f = x => a.mul(x.square()).add(b.mul(x)).add(c);
* const loss = (pred, label) => pred.sub(label).square().mean();
*
* const learningRate = 0.01;
* const optimizer = tf.train.sgd(learningRate);
*
* // Train the model.
* for (let i = 0; i < 10; i++) {
* optimizer.minimize(() => loss(f(xs), ys));
* }
*
* // Make predictions.
* console.log(
* `a: ${a.dataSync()}, b: ${b.dataSync()}, c: ${c.dataSync()}`);
* const preds = f(xs).dataSync();
* preds.forEach((pred, i) => {
* console.log(`x: ${i}, pred: ${pred}`);
* });
* ```
*
* @param learningRate The learning rate to use for the SGD algorithm.
*/
/**
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static sgd(learningRate) {
return new sgd_optimizer_SGDOptimizer(learningRate);
}
/**
* Constructs a `tf.MomentumOptimizer` that uses momentum gradient
* descent.
*
* See
* [http://proceedings.mlr.press/v28/sutskever13.pdf](
* http://proceedings.mlr.press/v28/sutskever13.pdf)
*
* @param learningRate The learning rate to use for the Momentum gradient
* descent algorithm.
* @param momentum The momentum to use for the momentum gradient descent
* algorithm.
*/
/**
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static momentum(learningRate, momentum, useNesterov = false) {
return new momentum_optimizer_MomentumOptimizer(learningRate, momentum, useNesterov);
}
/**
* Constructs a `tf.RMSPropOptimizer` that uses RMSProp gradient
* descent. This implementation uses plain momentum and is not centered
* version of RMSProp.
*
* See
* [http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf](
* http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
*
* @param learningRate The learning rate to use for the RMSProp gradient
* descent algorithm.
* @param decay The discounting factor for the history/coming gradient.
* @param momentum The momentum to use for the RMSProp gradient descent
* algorithm.
* @param epsilon Small value to avoid zero denominator.
* @param centered If true, gradients are normalized by the estimated
* variance of the gradient.
*/
/**
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static rmsprop(
learningRate,
decay = 0.9,
momentum = 0.0,
epsilon = null,
centered = false
) {
return new rmsprop_optimizer_RMSPropOptimizer(
learningRate,
decay,
momentum,
epsilon,
centered
);
}
/**
* Constructs a `tf.AdamOptimizer` that uses the Adam algorithm.
* See [https://arxiv.org/abs/1412.6980](https://arxiv.org/abs/1412.6980)
*
* @param learningRate The learning rate to use for the Adam gradient
* descent algorithm.
* @param beta1 The exponential decay rate for the 1st moment estimates.
* @param beta2 The exponential decay rate for the 2nd moment estimates.
* @param epsilon A small constant for numerical stability.
*/
/**
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static adam(learningRate = 0.001, beta1 = 0.9, beta2 = 0.999, epsilon = null) {
return new adam_optimizer_AdamOptimizer(learningRate, beta1, beta2, epsilon);
}
/**
* Constructs a `tf.AdadeltaOptimizer` that uses the Adadelta algorithm.
* See [https://arxiv.org/abs/1212.5701](https://arxiv.org/abs/1212.5701)
*
* @param learningRate The learning rate to use for the Adadelta gradient
* descent algorithm.
* @param rho The learning rate decay over each update.
* @param epsilon A constant epsilon used to better condition the grad
* update.
*/
/**
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static adadelta(learningRate = 0.001, rho = 0.95, epsilon = null) {
return new adadelta_optimizer_AdadeltaOptimizer(learningRate, rho, epsilon);
}
/**
* Constructs a `tf.AdamaxOptimizer` that uses the Adamax algorithm.
* See [https://arxiv.org/abs/1412.6980](https://arxiv.org/abs/1412.6980)
*
* @param learningRate The learning rate to use for the Adamax gradient
* descent algorithm.
* @param beta1 The exponential decay rate for the 1st moment estimates.
* @param beta2 The exponential decay rate for the 2nd moment estimates.
* @param epsilon A small constant for numerical stability.
* @param decay The learning rate decay over each update.
*/
/**
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static adamax(
learningRate = 0.002,
beta1 = 0.9,
beta2 = 0.999,
epsilon = null,
decay = 0.0
) {
return new adamax_optimizer_AdamaxOptimizer(learningRate, beta1, beta2, epsilon, decay);
}
/**
* Constructs a `tf.AdagradOptimizer` that uses the Adagrad algorithm.
* See
* [http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf](
* http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
* or
* [http://ruder.io/optimizing-gradient-descent/index.html#adagrad](
* http://ruder.io/optimizing-gradient-descent/index.html#adagrad)
*
* @param learningRate The learning rate to use for the Adagrad gradient
* descent algorithm.
* @param initialAccumulatorValue Starting value for the accumulators, must be
* positive.
*/
/**
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static adagrad(learningRate, initialAccumulatorValue = 0.1) {
return new adagrad_optimizer_AdagradOptimizer(learningRate, initialAccumulatorValue);
}
}
//# sourceMappingURL=optimizer_constructors.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/train.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// So typings can propagate.
// tslint:disable-next-line:no-unused-expression
[
momentum_optimizer_MomentumOptimizer,
sgd_optimizer_SGDOptimizer,
adadelta_optimizer_AdadeltaOptimizer,
adagrad_optimizer_AdagradOptimizer,
rmsprop_optimizer_RMSPropOptimizer,
adamax_optimizer_AdamaxOptimizer,
adam_optimizer_AdamOptimizer,
];
const train = {
sgd: optimizer_constructors_OptimizerConstructors.sgd,
momentum: optimizer_constructors_OptimizerConstructors.momentum,
adadelta: optimizer_constructors_OptimizerConstructors.adadelta,
adagrad: optimizer_constructors_OptimizerConstructors.adagrad,
rmsprop: optimizer_constructors_OptimizerConstructors.rmsprop,
adamax: optimizer_constructors_OptimizerConstructors.adamax,
adam: optimizer_constructors_OptimizerConstructors.adam,
};
//# sourceMappingURL=train.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/browser_util.js
var browser_util = __webpack_require__(40);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/array_ops_util.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gets the new shape of the input Tensor after it's been reshaped
* to:
* [blockShape[0], ..., blockShape[M-1], batch / prod(blockShape),
* inputShape[1], ..., inputShape[N-1]]
*
* See step 1: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd
*/
function getReshaped(inputShape, blockShape, prod, batchToSpace = true) {
let reshaped = [];
if (batchToSpace) {
reshaped = reshaped.concat(blockShape.slice(0));
reshaped.push(inputShape[0] / prod);
reshaped = reshaped.concat(inputShape.slice(1));
} else {
reshaped = reshaped.concat(inputShape[0]);
const spatialLength = blockShape.length;
for (let i = 0; i < spatialLength; ++i) {
reshaped = reshaped.concat([inputShape[i + 1] / blockShape[i], blockShape[i]]);
}
reshaped = reshaped.concat(inputShape.slice(spatialLength + 1));
}
return reshaped;
}
/**
* Gets the permutation that will transpose the dimensions of the
* reshaped tensor to shape:
*
* [batch / prod(block_shape),inputShape[1], blockShape[0], ...,
* inputShape[M], blockShape[M-1],inputShape[M+1], ..., inputShape[N-1]]
*
* see step 2: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd
*/
function getPermuted(reshapedRank, blockShapeRank, batchToSpace = true) {
const permuted = [];
if (batchToSpace) {
permuted.push(blockShapeRank);
for (let i = blockShapeRank + 1; i < reshapedRank; ++i) {
if (i <= 2 * blockShapeRank) {
permuted.push(i);
permuted.push(i - (blockShapeRank + 1));
} else {
permuted.push(i);
}
}
} else {
const permutedBeforeBatch = [];
const permutedAfterBatch = [];
for (let i = 1; i < reshapedRank; ++i) {
if (i >= blockShapeRank * 2 + 1 || i % 2 === 1) {
permutedAfterBatch.push(i);
} else {
permutedBeforeBatch.push(i);
}
}
permuted.push(...permutedBeforeBatch);
permuted.push(0);
permuted.push(...permutedAfterBatch);
}
return permuted;
}
/**
* Gets the shape of the reshaped and permuted input Tensor before any cropping
* is applied. The new shape will be:
*
* [batch / prod(blockShape),inputShape[1] * blockShape[0], ...,
* inputShape[M] * blockShape[M-1],inputShape[M+1], ..., inputShape[N-1]]
*
* See step 3: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd
*/
function getReshapedPermuted(inputShape, blockShape, prod, batchToSpace = true) {
const reshapedPermuted = [];
if (batchToSpace) {
reshapedPermuted.push(inputShape[0] / prod);
} else {
reshapedPermuted.push(inputShape[0] * prod);
}
for (let i = 1; i < inputShape.length; ++i) {
if (i <= blockShape.length) {
if (batchToSpace) {
reshapedPermuted.push(blockShape[i - 1] * inputShape[i]);
} else {
reshapedPermuted.push(inputShape[i] / blockShape[i - 1]);
}
} else {
reshapedPermuted.push(inputShape[i]);
}
}
return reshapedPermuted;
}
/**
* Converts the crops argument into the beginning coordinates of a slice
* operation.
*/
function getSliceBeginCoords(crops, blockShape) {
const sliceBeginCoords = [0];
for (let i = 0; i < blockShape; ++i) {
sliceBeginCoords.push(crops[i][0]);
}
return sliceBeginCoords;
}
/**
* Converts the crops argument into the size of a slice operation. When
* combined with getSliceBeginCoords this function allows the reshaped and
* permuted Tensor to be cropped to its final output shape of:
*
* inputShape[1] * blockShape[0] - crops[0,0] - crops[0,1], ...,
* inputShape[M] * blockShape[M-1] -crops[M-1,0] -
* crops[M-1,1],inputShape[M+1], ..., inputShape[N-1]]
*
* See step 4: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd
*/
function getSliceSize(uncroppedShape, crops, blockShape) {
const sliceSize = uncroppedShape.slice(0, 1);
for (let i = 0; i < blockShape; ++i) {
sliceSize.push(uncroppedShape[i + 1] - crops[i][0] - crops[i][1]);
}
return sliceSize;
}
//# sourceMappingURL=array_ops_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/erf_util.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ERF_P = 0.3275911;
const ERF_A1 = 0.254829592;
const ERF_A2 = -0.284496736;
const ERF_A3 = 1.421413741;
const ERF_A4 = -1.453152027;
const ERF_A5 = 1.061405429;
//# sourceMappingURL=erf_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/log.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function warn(...msg) {
if (!Object(environment["c" /* env */])().getBool("IS_TEST")) {
console.warn(...msg);
}
}
function log_log(...msg) {
if (!Object(environment["c" /* env */])().getBool("IS_TEST")) {
console.log(...msg);
}
}
//# sourceMappingURL=log.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/complex_util.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Merges real and imaginary Float32Arrays into a single complex Float32Array.
*
* The memory layout is interleaved as follows:
* real: [r0, r1, r2]
* imag: [i0, i1, i2]
* complex: [r0, i0, r1, i1, r2, i2]
*
* This is the inverse of splitRealAndImagArrays.
*
* @param real The real values of the complex tensor values.
* @param imag The imag values of the complex tensor values.
* @returns A complex tensor as a Float32Array with merged values.
*/
function mergeRealAndImagArrays(real, imag) {
if (real.length !== imag.length) {
throw new Error(
`Cannot merge real and imag arrays of different lengths. real:` +
`${real.length}, imag: ${imag.length}.`
);
}
const result = new Float32Array(real.length * 2);
for (let i = 0; i < result.length; i += 2) {
result[i] = real[i / 2];
result[i + 1] = imag[i / 2];
}
return result;
}
/**
* Splits a complex Float32Array into real and imag parts.
*
* The memory layout is interleaved as follows:
* complex: [r0, i0, r1, i1, r2, i2]
* real: [r0, r1, r2]
* imag: [i0, i1, i2]
*
* This is the inverse of mergeRealAndImagArrays.
*
* @param complex The complex tensor values.
* @returns An object with real and imag Float32Array components of the complex
* tensor.
*/
function splitRealAndImagArrays(complex) {
const real = new Float32Array(complex.length / 2);
const imag = new Float32Array(complex.length / 2);
for (let i = 0; i < complex.length; i += 2) {
real[i / 2] = complex[i];
imag[i / 2] = complex[i + 1];
}
return { real, imag };
}
/**
* Extracts even indexed complex values in the given array.
* @param complex The complex tensor values
*/
function complexWithEvenIndex(complex) {
const len = Math.ceil(complex.length / 4);
const real = new Float32Array(len);
const imag = new Float32Array(len);
for (let i = 0; i < complex.length; i += 4) {
real[Math.floor(i / 4)] = complex[i];
imag[Math.floor(i / 4)] = complex[i + 1];
}
return { real, imag };
}
/**
* Extracts odd indexed comple values in the given array.
* @param complex The complex tensor values
*/
function complexWithOddIndex(complex) {
const len = Math.floor(complex.length / 4);
const real = new Float32Array(len);
const imag = new Float32Array(len);
for (let i = 2; i < complex.length; i += 4) {
real[Math.floor(i / 4)] = complex[i];
imag[Math.floor(i / 4)] = complex[i + 1];
}
return { real, imag };
}
/**
* Get the map representing a complex value in the given array.
* @param complex The complex tensor values.
* @param index An index of the target complex value.
*/
function getComplexWithIndex(complex, index) {
const real = complex[index * 2];
const imag = complex[index * 2 + 1];
return { real, imag };
}
/**
* Insert a given complex value into the TypedArray.
* @param data The array in which the complex value is inserted.
* @param c The complex value to be inserted.
* @param index An index of the target complex value.
*/
function assignToTypedArray(data, real, imag, index) {
data[index * 2] = real;
data[index * 2 + 1] = imag;
}
/**
* Make the list of exponent terms used by FFT.
*/
function exponents(n, inverse) {
const real = new Float32Array(n / 2);
const imag = new Float32Array(n / 2);
for (let i = 0; i < Math.ceil(n / 2); i++) {
const x = (inverse ? 2 : -2) * Math.PI * (i / n);
real[i] = Math.cos(x);
imag[i] = Math.sin(x);
}
return { real, imag };
}
/**
* Make the exponent term used by FFT.
*/
function exponent(k, n, inverse) {
const x = (inverse ? 2 : -2) * Math.PI * (k / n);
const real = Math.cos(x);
const imag = Math.sin(x);
return { real, imag };
}
//# sourceMappingURL=complex_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/backend_util.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Utilities needed by backend consumers of tf-core.
function castTensor(x, dtype, backend) {
if (dtype === "complex64") {
if (x.dtype === "complex64") {
return x.clone();
}
const zerosTensor = Object(tensor_ops["n" /* zeros */])(x.shape);
const floatX = x.toFloat();
const result = backend.complex(floatX, zerosTensor);
zerosTensor.dispose();
floatX.dispose();
return result;
}
if (!Object(util["hasEncodingLoss"])(x.dtype, dtype)) {
// We don't change the underlying data, since we cast to higher
// precision.
return engine["a" /* ENGINE */].makeTensorFromDataId(x.dataId, x.shape, dtype);
}
if (x.dtype === "complex64") {
const real = backend.real(x);
const result = real.cast(dtype);
real.dispose();
return result;
}
if (dtype === "int32") {
return backend.int(x);
} else if (dtype === "bool") {
const zero = Object(tensor_ops["e" /* scalar */])(0, x.dtype);
const result = backend.notEqual(x, zero);
zero.dispose();
return result;
} else {
throw new Error(`Error in Cast: failed to cast ${x.dtype} to ${dtype}`);
}
}
function reshapeTensor(x, shape) {
return engine["a" /* ENGINE */].makeTensorFromDataId(x.dataId, shape, x.dtype);
}
function linspaceImpl(start, stop, num) {
const step = (stop - start) / (num - 1);
const values = Object(util["makeZerosTypedArray"])(num, "float32");
values[0] = start;
for (let i = 1; i < values.length; i++) {
values[i] = values[i - 1] + step;
}
return Object(tensor_ops["g" /* tensor1d */])(values, "float32");
}
//# sourceMappingURL=backend_util.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/device_util.js
var device_util = __webpack_require__(36);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/split_shared.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// TODO(annxingyuan): Use this helper in WASM Split kernel once intermediate
// kernels have been modularized in WebGL and CPU
// https://github.com/tensorflow/tfjs/issues/2822.
/** Shared implementation of the split kernel across WebGL and CPU. */
function split_shared_split(x, sizeSplits, axis) {
const begin = new Array(x.rank).fill(0);
const size = x.shape.slice();
return sizeSplits.map((s) => {
const sliceSize = [...size];
sliceSize[axis] = s;
const slice = x.slice(begin, sliceSize);
begin[axis] += s;
return slice;
});
}
//# sourceMappingURL=split_shared.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/tile_impl.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.
* =============================================================================
*/
/**
* An implementation of the tile kernel shared between webgl and cpu for string
* tensors only.
*/
function tile_impl_tile(xBuf, reps) {
const newShape = new Array(xBuf.rank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = xBuf.shape[i] * reps[i];
}
const result = array_ops_buffer(newShape, xBuf.dtype);
for (let i = 0; i < result.values.length; ++i) {
const newLoc = result.indexToLoc(i);
const originalLoc = new Array(xBuf.rank);
for (let j = 0; j < originalLoc.length; j++) {
originalLoc[j] = newLoc[j] % xBuf.shape[j];
}
const originalIndex = xBuf.locToIndex(originalLoc);
result.values[i] = xBuf.values[originalIndex];
}
return result.toTensor();
}
//# sourceMappingURL=tile_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/topk_impl.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** An implementation of the TopK kernel shared between webgl and cpu. */
function topkImpl(x, xShape, xDtype, k, sorted) {
// Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.
const lastDim = xShape[xShape.length - 1];
const [batch, size] = [x.length / lastDim, lastDim];
const allTopKVals = Object(util["getTypedArrayFromDType"])(xDtype, batch * k);
const allTopKIndices = Object(util["getTypedArrayFromDType"])("int32", batch * k);
for (let b = 0; b < batch; b++) {
const offset = b * size;
const vals = x.subarray(offset, offset + size);
const valAndInd = [];
for (let i = 0; i < vals.length; i++) {
valAndInd.push({ value: vals[i], index: i });
}
valAndInd.sort((a, b) => b.value - a.value);
const outOffset = b * k;
const topKVals = allTopKVals.subarray(outOffset, outOffset + k);
const topKIndices = allTopKIndices.subarray(outOffset, outOffset + k);
for (let i = 0; i < k; i++) {
topKVals[i] = valAndInd[i].value;
topKIndices[i] = valAndInd[i].index;
}
}
// Reshape back to the original input shape, except that the last
// dimension is k.
const outputShape = xShape.slice();
outputShape[outputShape.length - 1] = k;
return [
Object(tensor_ops["f" /* tensor */])(allTopKVals, outputShape, xDtype),
Object(tensor_ops["f" /* tensor */])(allTopKIndices, outputShape, "int32"),
];
}
//# sourceMappingURL=topk_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/kernel_impls.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
//# sourceMappingURL=kernel_impls.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/backend.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const EPSILON_FLOAT32 = 1e-7;
const EPSILON_FLOAT16 = 1e-4;
/** Convenient class for storing tensor-related data. */
class DataStorage {
constructor(backend, dataMover) {
this.backend = backend;
this.dataMover = dataMover;
this.data = new WeakMap();
this.dataIdsCount = 0;
}
get(dataId) {
if (!this.data.has(dataId)) {
this.dataMover.moveData(this.backend, dataId);
}
return this.data.get(dataId);
}
set(dataId, value) {
this.dataIdsCount++;
this.data.set(dataId, value);
}
has(dataId) {
return this.data.has(dataId);
}
delete(dataId) {
this.dataIdsCount--;
return this.data.delete(dataId);
}
numDataIds() {
return this.dataIdsCount;
}
}
/**
* The interface that defines the kernels that should be implemented when
* adding a new backend. New backends don't need to implement every one of the
* methods, this can be done gradually (throw an error for unimplemented
* methods).
*/
class KernelBackend {
time(f) {
return notYetImplemented("time");
}
read(dataId) {
return notYetImplemented("read");
}
readSync(dataId) {
return notYetImplemented("readSync");
}
numDataIds() {
return notYetImplemented("numDataIds");
}
disposeData(dataId) {
return notYetImplemented("disposeData");
}
write(values, shape, dtype) {
return notYetImplemented("write");
}
move(dataId, values, shape, dtype) {
return notYetImplemented("move");
}
memory() {
return notYetImplemented("memory");
}
/** Returns the highest precision for floats in bits (e.g. 16 or 32) */
floatPrecision() {
return notYetImplemented("floatPrecision");
}
/** Returns the smallest representable number. */
epsilon() {
return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
}
batchMatMul(a, b, transposeA, transposeB) {
return notYetImplemented("batchMatMul");
}
fusedBatchMatMul({
a,
b,
transposeA,
transposeB,
bias,
activation,
preluActivationWeights,
}) {
return notYetImplemented("fusedBatchMatMul");
}
slice(x, begin, size) {
return notYetImplemented("slice");
}
stridedSlice(x, begin, end, strides) {
return notYetImplemented("stridedSlice");
}
unstack(x, axis) {
return notYetImplemented("unstack");
}
reverse(a, axis) {
return notYetImplemented("reverse");
}
concat(tensors, axis) {
return notYetImplemented("concat");
}
neg(a) {
return notYetImplemented("neg");
}
add(a, b) {
return notYetImplemented("add");
}
addN(tensors) {
return notYetImplemented("addN");
}
subtract(a, b) {
return notYetImplemented("subtract");
}
multiply(a, b) {
return notYetImplemented("multiply");
}
realDivide(a, b) {
return notYetImplemented("realDivide");
}
floorDiv(a, b) {
return notYetImplemented("floorDiv");
}
sum(x, axes) {
return notYetImplemented("sum");
}
prod(x, axes) {
return notYetImplemented("prod");
}
unsortedSegmentSum(x, segmentIds, numSegments) {
return notYetImplemented("unsortedSegmentSum");
}
argMin(x, axis) {
return notYetImplemented("argMin");
}
argMax(x, axis) {
return notYetImplemented("argMax");
}
equal(a, b) {
return notYetImplemented("equal");
}
notEqual(a, b) {
return notYetImplemented("notEqual");
}
less(a, b) {
return notYetImplemented("less");
}
lessEqual(a, b) {
return notYetImplemented("lessEqual");
}
greater(a, b) {
return notYetImplemented("greater");
}
greaterEqual(a, b) {
return notYetImplemented("greaterEqual");
}
logicalNot(a) {
return notYetImplemented("logicalNot");
}
logicalAnd(a, b) {
return notYetImplemented("logicalAnd");
}
logicalOr(a, b) {
return notYetImplemented("logicalOr");
}
where(condition) {
return notYetImplemented("where");
}
select(condition, a, b) {
return notYetImplemented("select");
}
topk(x, k, sorted) {
return notYetImplemented("topk");
}
min(x, axes) {
return notYetImplemented("min");
}
minimum(a, b) {
return notYetImplemented("minimum");
}
mod(a, b) {
return notYetImplemented("mod");
}
max(x, axes) {
return notYetImplemented("max");
}
maximum(a, b) {
return notYetImplemented("maximum");
}
all(x, axes) {
return notYetImplemented("all");
}
any(x, axes) {
return notYetImplemented("any");
}
squaredDifference(a, b) {
return notYetImplemented("squaredDifference");
}
ceil(x) {
return notYetImplemented("ceil");
}
floor(x) {
return notYetImplemented("floor");
}
round(x) {
return notYetImplemented("round");
}
sign(x) {
return notYetImplemented("sign");
}
isNaN(x) {
return notYetImplemented("isNaN");
}
isInf(x) {
return notYetImplemented("isInf");
}
isFinite(x) {
return notYetImplemented("isFinite");
}
pow(a, b) {
return notYetImplemented("pow");
}
exp(x) {
return notYetImplemented("exp");
}
expm1(x) {
return notYetImplemented("expm1");
}
softmax(x, dim) {
return notYetImplemented("softmax");
}
log(x) {
return notYetImplemented("log");
}
log1p(x) {
return notYetImplemented("log1p");
}
sqrt(x) {
return notYetImplemented("sqrt");
}
rsqrt(x) {
return notYetImplemented("rsqrt");
}
square(x) {
return notYetImplemented("square");
}
reciprocal(x) {
return notYetImplemented("reciprocal");
}
relu(x) {
return notYetImplemented("relu");
}
relu6(x) {
return notYetImplemented("relu6");
}
prelu(x, a) {
return notYetImplemented("prelu");
}
elu(x) {
return notYetImplemented("elu");
}
eluDer(dy, y) {
return notYetImplemented("eluDer");
}
selu(x) {
return notYetImplemented("selu");
}
int(x) {
return notYetImplemented("int");
}
clip(x, min, max) {
return notYetImplemented("clip");
}
abs(x) {
return notYetImplemented("abs");
}
complexAbs(x) {
return notYetImplemented("complexAbs");
}
sigmoid(x) {
return notYetImplemented("sigmoid");
}
softplus(x) {
return notYetImplemented("softplus");
}
sin(x) {
return notYetImplemented("sin");
}
cos(x) {
return notYetImplemented("cos");
}
tan(x) {
return notYetImplemented("tan");
}
asin(x) {
return notYetImplemented("asin");
}
acos(x) {
return notYetImplemented("acos");
}
atan(x) {
return notYetImplemented("atan");
}
atan2(a, b) {
return notYetImplemented("atan2");
}
sinh(x) {
return notYetImplemented("sinh");
}
cosh(x) {
return notYetImplemented("cosh");
}
tanh(x) {
return notYetImplemented("tanh");
}
asinh(x) {
return notYetImplemented("asinh");
}
acosh(x) {
return notYetImplemented("acosh");
}
atanh(x) {
return notYetImplemented("atanh");
}
erf(x) {
return notYetImplemented("erf");
}
step(x, alpha) {
return notYetImplemented("step");
}
fusedConv2d({ input, filter, convInfo, bias, activation, preluActivationWeights }) {
return notYetImplemented("fusedConv2d");
}
conv2d(x, filter, convInfo) {
return notYetImplemented("conv2d");
}
conv2dDerInput(dy, filter, convInfo) {
return notYetImplemented("conv2dDerInput");
}
conv2dDerFilter(x, dY, convInfo) {
return notYetImplemented("conv2dDerFilter");
}
fusedDepthwiseConv2D({
input,
filter,
convInfo,
bias,
activation,
preluActivationWeights,
}) {
return notYetImplemented("fusedDepthwiseConv2D");
}
depthwiseConv2D(input, filter, convInfo) {
return notYetImplemented("depthwiseConv2D");
}
depthwiseConv2DDerInput(dy, filter, convInfo) {
return notYetImplemented("depthwiseConv2DDerInput");
}
depthwiseConv2DDerFilter(x, dY, convInfo) {
return notYetImplemented("depthwiseConv2DDerFilter");
}
conv3d(x, filter, convInfo) {
return notYetImplemented("conv3d");
}
conv3dDerInput(dy, filter, convInfo) {
return notYetImplemented("conv3dDerInput");
}
conv3dDerFilter(x, dY, convInfo) {
return notYetImplemented("conv3dDerFilter");
}
maxPool(x, convInfo) {
return notYetImplemented("maxPool");
}
maxPoolBackprop(dy, x, y, convInfo) {
return notYetImplemented("maxPoolBackprop");
}
avgPool(x, convInfo) {
return notYetImplemented("avgPool");
}
avgPoolBackprop(dy, x, convInfo) {
return notYetImplemented("avgPoolBackprop");
}
avgPool3d(x, convInfo) {
return notYetImplemented("avgPool3d");
}
avgPool3dBackprop(dy, x, convInfo) {
return notYetImplemented("avgPool3dBackprop");
}
maxPool3d(x, convInfo) {
return notYetImplemented("maxPool3d");
}
maxPool3dBackprop(dy, x, y, convInfo) {
return notYetImplemented("maxPool3dBackprop");
}
reshape(x, shape) {
return notYetImplemented("reshape");
}
cast(x, dtype) {
return notYetImplemented("cast");
}
tile(x, reps) {
return notYetImplemented("tile");
}
pad(x, paddings, constantValue) {
return notYetImplemented("pad");
}
transpose(x, perm) {
return notYetImplemented("transpose");
}
gather(x, indices, axis) {
return notYetImplemented("gather");
}
gatherND(x, indices) {
return notYetImplemented("gatherND");
}
scatterND(indices, updates, shape) {
return notYetImplemented("scatterND");
}
batchToSpaceND(x, blockShape, crops) {
return notYetImplemented("batchToSpaceND");
}
spaceToBatchND(x, blockShape, paddings) {
return notYetImplemented("spaceToBatchND");
}
resizeBilinear(x, newHeight, newWidth, alignCorners) {
return notYetImplemented("resizeBilinear");
}
resizeBilinearBackprop(dy, x, alignCorners) {
return notYetImplemented("resizeBilinearBackprop");
}
resizeNearestNeighbor(x, newHEight, newWidth, alignCorners) {
return notYetImplemented("resizeNearestNeighbor");
}
resizeNearestNeighborBackprop(dy, x, alignCorners) {
return notYetImplemented("resizeNearestNeighborBackprop");
}
batchNorm(x, mean, variance, offset, scale, varianceEpsilon) {
return notYetImplemented("batchNorm");
}
localResponseNormalization4D(x, radius, bias, alpha, beta) {
return notYetImplemented("localResponseNormalization4D");
}
LRNGrad(dy, inputImage, outputImage, radius, bias, alpha, beta) {
return notYetImplemented("LRNGrad");
}
multinomial(logits, normalized, numSamples, seed) {
return notYetImplemented("multinomial");
}
oneHot(indices, depth, onValue, offValue) {
return notYetImplemented("oneHot");
}
cumsum(x, axis, exclusive, reverse) {
return notYetImplemented("cumsum");
}
nonMaxSuppression(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
return notYetImplemented("nonMaxSuppression");
}
fft(x) {
return notYetImplemented("fft");
}
ifft(x) {
return notYetImplemented("ifft");
}
complex(real, imag) {
return notYetImplemented("complex");
}
real(input) {
return notYetImplemented("real");
}
imag(input) {
return notYetImplemented("imag");
}
cropAndResize(image, boxes, boxIndex, cropSize, method, extrapolationValue) {
return notYetImplemented("cropAndResize");
}
depthToSpace(x, blockSize, dataFormat) {
return notYetImplemented("depthToSpace");
}
// Aligns with the "SplitV" kernel in TensorFlow.
split(value, sizeSplits, axis) {
return notYetImplemented("split");
}
sparseToDense(sparseIndices, sparseValues, outputShape, defaultValue) {
return notYetImplemented("sparseToDense");
}
diag(x) {
return notYetImplemented("diag");
}
fill(shape, value, dtype) {
return notYetImplemented("fill");
}
onesLike(x) {
return notYetImplemented("onesLike");
}
zerosLike(x) {
return notYetImplemented("zerosLike");
}
linspace(start, stop, num) {
return notYetImplemented("linspace");
}
dispose() {
return notYetImplemented("dispose");
}
}
function notYetImplemented(kernelName) {
throw new Error(
`'${kernelName}' not yet implemented or not found in the registry. ` +
`Did you forget to import the kernel?`
);
}
//# sourceMappingURL=backend.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/add.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.add = function (b) {
this.throwIfDisposed();
return add(this, b);
};
//# sourceMappingURL=add.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/atan2.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.atan2 = function (b) {
this.throwIfDisposed();
return atan2(this, b);
};
//# sourceMappingURL=atan2.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/avg_pool.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.avgPool = function (
filterSize,
strides,
pad,
dimRoundingMode
) {
this.throwIfDisposed();
return avgPool(this, filterSize, strides, pad, dimRoundingMode);
};
//# sourceMappingURL=avg_pool.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/batchnorm.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.batchNorm = function (
mean,
variance,
offset,
scale,
varianceEpsilon
) {
this.throwIfDisposed();
return batchNorm(this, mean, variance, offset, scale, varianceEpsilon);
};
//# sourceMappingURL=batchnorm.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/broadcast_to.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.broadcastTo = function (shape) {
this.throwIfDisposed();
return broadcastTo(this, shape);
};
//# sourceMappingURL=broadcast_to.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/batch_to_space_nd.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.batchToSpaceND = function (blockShape, crops) {
this.throwIfDisposed();
return batchToSpaceND(this, blockShape, crops);
};
//# sourceMappingURL=batch_to_space_nd.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/concat.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.concat = function (x, axis) {
this.throwIfDisposed();
if (x instanceof dist_tensor["a" /* Tensor */]) {
x = [x];
}
return concat([this, ...x], axis);
};
//# sourceMappingURL=concat.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/conv1d.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.conv1d = function (
filter,
stride,
pad,
dataFormat,
dilation,
dimRoundingMode
) {
this.throwIfDisposed();
return conv1d(this, filter, stride, pad, dataFormat, dilation, dimRoundingMode);
};
//# sourceMappingURL=conv1d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/conv2d.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.conv2d = function (
filter,
strides,
pad,
dataFormat,
dilations,
dimRoundingMode
) {
this.throwIfDisposed();
return conv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
};
//# sourceMappingURL=conv2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/conv2d_transpose.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.conv2dTranspose = function (
filter,
outputShape,
strides,
pad,
dimRoundingMode
) {
this.throwIfDisposed();
return conv2dTranspose(this, filter, outputShape, strides, pad, dimRoundingMode);
};
//# sourceMappingURL=conv2d_transpose.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/cumsum.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.cumsum = function (axis, exclusive, reverse) {
this.throwIfDisposed();
return cumsum(this, axis, exclusive, reverse);
};
//# sourceMappingURL=cumsum.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/depth_to_space.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.depthToSpace = function (blockSize, dataFormat) {
this.throwIfDisposed();
return depthToSpace(this, blockSize, dataFormat);
};
//# sourceMappingURL=depth_to_space.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/depthwise_conv2d.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.depthwiseConv2d = function (
filter,
strides,
pad,
dataFormat,
dilations,
dimRoundingMode
) {
this.throwIfDisposed();
return depthwiseConv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
};
//# sourceMappingURL=depthwise_conv2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/depthwise_conv2D_deprecated.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @deprecated Use `depthwiseConv2d` instead.
*/
dist_tensor["a" /* Tensor */].prototype.depthwiseConv2D = function (
filter,
strides,
pad,
dataFormat,
dilations,
dimRoundingMode
) {
deprecationWarn("depthwiseConv2D is deprecated, use depthwiseConv2d instead");
this.throwIfDisposed();
return depthwiseConv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
};
//# sourceMappingURL=depthwise_conv2D_deprecated.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/div.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.div = function (b) {
this.throwIfDisposed();
return div(this, b);
};
//# sourceMappingURL=div.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/div_no_nan.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.divNoNan = function (b) {
this.throwIfDisposed();
return divNoNan(this, b);
};
//# sourceMappingURL=div_no_nan.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/dot.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.dot = function (b) {
this.throwIfDisposed();
return dot(this, b);
};
//# sourceMappingURL=dot.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/elu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.elu = function () {
this.throwIfDisposed();
return elu(this);
};
//# sourceMappingURL=elu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/equal.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.equal = function (b) {
this.throwIfDisposed();
return equal(this, b);
};
//# sourceMappingURL=equal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/floorDiv.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.floorDiv = function (b) {
this.throwIfDisposed();
return floorDiv(this, b);
};
//# sourceMappingURL=floorDiv.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/greater.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.greater = function (b) {
this.throwIfDisposed();
return greater(this, b);
};
//# sourceMappingURL=greater.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/greater_equal.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.greaterEqual = function (b) {
this.throwIfDisposed();
return greaterEqual(this, b);
};
//# sourceMappingURL=greater_equal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/leaky_relu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.leakyRelu = function (alpha) {
this.throwIfDisposed();
return leakyRelu(this, alpha);
};
//# sourceMappingURL=leaky_relu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/less.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.less = function (b) {
this.throwIfDisposed();
return less(this, b);
};
//# sourceMappingURL=less.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/less_equal.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.lessEqual = function (b) {
this.throwIfDisposed();
return lessEqual(this, b);
};
//# sourceMappingURL=less_equal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/local_response_normalization.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.localResponseNormalization = function (
depthRadius,
bias,
alpha,
beta
) {
this.throwIfDisposed();
return localResponseNormalization(this, depthRadius, bias, alpha, beta);
};
//# sourceMappingURL=local_response_normalization.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/mat_mul.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.matMul = function (b, transposeA, transposeB) {
this.throwIfDisposed();
return matMul(this, b, transposeA, transposeB);
};
//# sourceMappingURL=mat_mul.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/max.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.max = function (axis, keepDims) {
this.throwIfDisposed();
return max_max(this, axis, keepDims);
};
//# sourceMappingURL=max.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/max_pool.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.maxPool = function (
filterSize,
strides,
pad,
dimRoundingMode
) {
this.throwIfDisposed();
return maxPool(this, filterSize, strides, pad, dimRoundingMode);
};
//# sourceMappingURL=max_pool.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/maximum.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.maximum = function (b) {
this.throwIfDisposed();
return maximum(this, b);
};
//# sourceMappingURL=maximum.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/minimum.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.minimum = function (b) {
this.throwIfDisposed();
return minimum(this, b);
};
//# sourceMappingURL=minimum.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/mod.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.mod = function (b) {
this.throwIfDisposed();
return mod(this, b);
};
//# sourceMappingURL=mod.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/mul.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.mul = function (b) {
this.throwIfDisposed();
return mul(this, b);
};
//# sourceMappingURL=mul.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/not_equal.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.notEqual = function (b) {
this.throwIfDisposed();
return notEqual(this, b);
};
//# sourceMappingURL=not_equal.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/one_hot.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.oneHot = function (depth, onValue = 1, offValue = 0) {
this.throwIfDisposed();
return oneHot(this, depth, onValue, offValue);
};
//# sourceMappingURL=one_hot.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/pad.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.pad = function (paddings, constantValue) {
this.throwIfDisposed();
return pad_pad(this, paddings, constantValue);
};
//# sourceMappingURL=pad.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/pool.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.pool = function (
windowShape,
poolingType,
padding,
dilationRate,
strides
) {
this.throwIfDisposed();
return pool(this, windowShape, poolingType, padding, dilationRate, strides);
};
//# sourceMappingURL=pool.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/pow.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.pow = function (exp) {
this.throwIfDisposed();
return pow(this, exp);
};
//# sourceMappingURL=pow.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/prelu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.prelu = function (alpha) {
this.throwIfDisposed();
return prelu(this, alpha);
};
//# sourceMappingURL=prelu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/relu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.relu = function () {
this.throwIfDisposed();
return relu(this);
};
//# sourceMappingURL=relu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/relu6.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.relu6 = function () {
this.throwIfDisposed();
return relu6(this);
};
//# sourceMappingURL=relu6.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/selu.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.selu = function () {
this.throwIfDisposed();
return selu(this);
};
//# sourceMappingURL=selu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/separable_conv2d.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.separableConv2d = function (
depthwiseFilter,
pointwiseFilter,
strides,
pad,
dilation,
dataFormat
) {
this.throwIfDisposed();
return separableConv2d(
this,
depthwiseFilter,
pointwiseFilter,
strides,
pad,
dilation,
dataFormat
);
};
//# sourceMappingURL=separable_conv2d.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/split.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.split = function (numOrSizeSplits, axis) {
this.throwIfDisposed();
return split(this, numOrSizeSplits, axis);
};
//# sourceMappingURL=split.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/squared_difference.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.squaredDifference = function (b) {
this.throwIfDisposed();
return squaredDifference(this, b);
};
//# sourceMappingURL=squared_difference.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/space_to_batch_nd.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.spaceToBatchND = function (blockShape, paddings) {
this.throwIfDisposed();
return spaceToBatchND(this, blockShape, paddings);
};
//# sourceMappingURL=space_to_batch_nd.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/sub.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.sub = function (b) {
this.throwIfDisposed();
return sub(this, b);
};
//# sourceMappingURL=sub.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/tile.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.tile = function (reps) {
this.throwIfDisposed();
return tile(this, reps);
};
//# sourceMappingURL=tile.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/transpose.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
dist_tensor["a" /* Tensor */].prototype.transpose = function (perm) {
this.throwIfDisposed();
return transpose(this, perm);
};
//# sourceMappingURL=transpose.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/public/chained_ops/register_all_chained_ops.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
//# sourceMappingURL=register_all_chained_ops.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @fileoverview
* @suppress {partialAlias} Optimization disabled due to passing the module
* object into a function below:
*
* import * as ops from './ops/ops';
* setOpHandler(ops);
*/
// Engine is the global singleton that needs to be initialized before the rest
// of the app.
// Register backend-agnostic flags.
// Register all the gradients.
// Serialization.
// Optimizers.
// Top-level method exports.
// Second level exports.
// Backend specific.
Object(dist_tensor["e" /* setOpHandler */])(ops_namespaceObject);
// Export all kernel names / info.
// Import all op chainers and add type info to Tensor.
//# sourceMappingURL=index.js.map
/***/
},
/* 1 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"shuffle",
function () {
return shuffle;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"clamp",
function () {
return clamp;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"nearestLargerEven",
function () {
return nearestLargerEven;
}
);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sum", function () {
return sum;
});
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"randUniform",
function () {
return randUniform;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"distSquared",
function () {
return distSquared;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"assert",
function () {
return assert;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"assertShapesMatch",
function () {
return assertShapesMatch;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"assertNonNull",
function () {
return assertNonNull;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"flatten",
function () {
return flatten;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"sizeFromShape",
function () {
return sizeFromShape;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isScalarShape",
function () {
return isScalarShape;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"arraysEqual",
function () {
return arraysEqual;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isInt",
function () {
return isInt;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"tanh",
function () {
return tanh;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"sizeToSquarishShape",
function () {
return sizeToSquarishShape;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"createShuffledIndices",
function () {
return createShuffledIndices;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"rightPad",
function () {
return rightPad;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"repeatedTry",
function () {
return repeatedTry;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"inferFromImplicitShape",
function () {
return inferFromImplicitShape;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"parseAxisParam",
function () {
return parseAxisParam;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"squeezeShape",
function () {
return squeezeShape;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"getTypedArrayFromDType",
function () {
return getTypedArrayFromDType;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"getArrayFromDType",
function () {
return getArrayFromDType;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"checkConversionForErrors",
function () {
return checkConversionForErrors;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isValidDtype",
function () {
return isValidDtype;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"hasEncodingLoss",
function () {
return hasEncodingLoss;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isTypedArray",
function () {
return isTypedArray;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"bytesPerElement",
function () {
return bytesPerElement;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"bytesFromStringArray",
function () {
return bytesFromStringArray;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isString",
function () {
return isString;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isBoolean",
function () {
return isBoolean;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isNumber",
function () {
return isNumber;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"inferDtype",
function () {
return inferDtype;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isFunction",
function () {
return isFunction;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"nearestDivisor",
function () {
return nearestDivisor;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"computeStrides",
function () {
return computeStrides;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"toTypedArray",
function () {
return toTypedArray;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"toNestedArray",
function () {
return toNestedArray;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"makeOnesTypedArray",
function () {
return makeOnesTypedArray;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"makeZerosTypedArray",
function () {
return makeZerosTypedArray;
}
);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "now", function () {
return now;
});
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"assertNonNegativeIntegerDimensions",
function () {
return assertNonNegativeIntegerDimensions;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"fetch",
function () {
return fetch;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"encodeString",
function () {
return encodeString;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"decodeString",
function () {
return decodeString;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"locToIndex",
function () {
return locToIndex;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"indexToLoc",
function () {
return indexToLoc;
}
);
/* harmony import */ var _environment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10);
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Shuffles the array in-place using Fisher-Yates algorithm.
*
* ```js
* const a = [1, 2, 3, 4, 5];
* tf.util.shuffle(a);
* console.log(a);
* ```
*
* @param array The array to shuffle in-place.
*/
/** @doc {heading: 'Util', namespace: 'util'} */
// tslint:disable-next-line:no-any
function shuffle(array) {
let counter = array.length;
let temp = 0;
let index = 0;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = (Math.random() * counter) | 0;
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
}
/** Clamps a value to a specified range. */
function clamp(min, x, max) {
return Math.max(min, Math.min(x, max));
}
function nearestLargerEven(val) {
return val % 2 === 0 ? val : val + 1;
}
function sum(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
/**
* Returns a sample from a uniform [a, b) distribution.
*
* @param a The minimum support (inclusive).
* @param b The maximum support (exclusive).
* @return A pseudorandom number on the half-open interval [a,b).
*/
function randUniform(a, b) {
const r = Math.random();
return b * r + (1 - r) * a;
}
/** Returns the squared Euclidean distance between two vectors. */
function distSquared(a, b) {
let result = 0;
for (let i = 0; i < a.length; i++) {
const diff = Number(a[i]) - Number(b[i]);
result += diff * diff;
}
return result;
}
/**
* Asserts that the expression is true. Otherwise throws an error with the
* provided message.
*
* ```js
* const x = 2;
* tf.util.assert(x === 2, 'x is not 2');
* ```
*
* @param expr The expression to assert (as a boolean).
* @param msg A function that returns the message to report when throwing an
* error. We use a function for performance reasons.
*/
/** @doc {heading: 'Util', namespace: 'util'} */
function assert(expr, msg) {
if (!expr) {
throw new Error(typeof msg === "string" ? msg : msg());
}
}
function assertShapesMatch(shapeA, shapeB, errorMessagePrefix = "") {
assert(
arraysEqual(shapeA, shapeB),
() => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`
);
}
function assertNonNull(a) {
assert(a != null, () => `The input to the tensor constructor must be a non-null value.`);
}
// NOTE: We explicitly type out what T extends instead of any so that
// util.flatten on a nested array of number doesn't try to infer T as a
// number[][], causing us to explicitly type util.flatten<number>().
/**
* Flattens an arbitrarily nested array.
*
* ```js
* const a = [[1, 2], [3, 4], [5, [6, [7]]]];
* const flat = tf.util.flatten(a);
* console.log(flat);
* ```
*
* @param arr The nested array to flatten.
* @param result The destination array which holds the elements.
* @param skipTypedArray If true, avoids flattening the typed arrays. Defaults
* to false.
*/
/** @doc {heading: 'Util', namespace: 'util'} */
function flatten(arr, result = [], skipTypedArray = false) {
if (result == null) {
result = [];
}
if (Array.isArray(arr) || (isTypedArray(arr) && !skipTypedArray)) {
for (let i = 0; i < arr.length; ++i) {
flatten(arr[i], result, skipTypedArray);
}
} else {
result.push(arr);
}
return result;
}
/**
* Returns the size (number of elements) of the tensor given its shape.
*
* ```js
* const shape = [3, 4, 2];
* const size = tf.util.sizeFromShape(shape);
* console.log(size);
* ```
*/
/** @doc {heading: 'Util', namespace: 'util'} */
function sizeFromShape(shape) {
if (shape.length === 0) {
// Scalar.
return 1;
}
let size = shape[0];
for (let i = 1; i < shape.length; i++) {
size *= shape[i];
}
return size;
}
function isScalarShape(shape) {
return shape.length === 0;
}
function arraysEqual(n1, n2) {
if (n1 === n2) {
return true;
}
if (n1 == null || n2 == null) {
return false;
}
if (n1.length !== n2.length) {
return false;
}
for (let i = 0; i < n1.length; i++) {
if (n1[i] !== n2[i]) {
return false;
}
}
return true;
}
function isInt(a) {
return a % 1 === 0;
}
function tanh(x) {
// tslint:disable-next-line:no-any
if (Math.tanh != null) {
// tslint:disable-next-line:no-any
return Math.tanh(x);
}
if (x === Infinity) {
return 1;
} else if (x === -Infinity) {
return -1;
} else {
const e2x = Math.exp(2 * x);
return (e2x - 1) / (e2x + 1);
}
}
function sizeToSquarishShape(size) {
const width = Math.ceil(Math.sqrt(size));
return [width, Math.ceil(size / width)];
}
/**
* Creates a new array with randomized indicies to a given quantity.
*
* ```js
* const randomTen = tf.util.createShuffledIndices(10);
* console.log(randomTen);
* ```
*
* @param number Quantity of how many shuffled indicies to create.
*/
/** @doc {heading: 'Util', namespace: 'util'} */
function createShuffledIndices(n) {
const shuffledIndices = new Uint32Array(n);
for (let i = 0; i < n; ++i) {
shuffledIndices[i] = i;
}
shuffle(shuffledIndices);
return shuffledIndices;
}
function rightPad(a, size) {
if (size <= a.length) {
return a;
}
return a + " ".repeat(size - a.length);
}
function repeatedTry(checkFn, delayFn = (counter) => 0, maxCounter) {
return new Promise((resolve, reject) => {
let tryCount = 0;
const tryFn = () => {
if (checkFn()) {
resolve();
return;
}
tryCount++;
const nextBackoff = delayFn(tryCount);
if (maxCounter != null && tryCount >= maxCounter) {
reject();
return;
}
setTimeout(tryFn, nextBackoff);
};
tryFn();
});
}
/**
* Given the full size of the array and a shape that may contain -1 as the
* implicit dimension, returns the inferred shape where -1 is replaced.
* E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].
*
* @param shape The shape, which may contain -1 in some dimension.
* @param size The full size (number of elements) of the array.
* @return The inferred shape where -1 is replaced with the inferred size.
*/
function inferFromImplicitShape(shape, size) {
let shapeProd = 1;
let implicitIdx = -1;
for (let i = 0; i < shape.length; ++i) {
if (shape[i] >= 0) {
shapeProd *= shape[i];
} else if (shape[i] === -1) {
if (implicitIdx !== -1) {
throw Error(
`Shapes can only have 1 implicit size. ` +
`Found -1 at dim ${implicitIdx} and dim ${i}`
);
}
implicitIdx = i;
} else if (shape[i] < 0) {
throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);
}
}
if (implicitIdx === -1) {
if (size > 0 && size !== shapeProd) {
throw Error(`Size(${size}) must match the product of shape ${shape}`);
}
return shape;
}
if (shapeProd === 0) {
throw Error(`Cannot infer the missing size in [${shape}] when ` + `there are 0 elements`);
}
if (size % shapeProd !== 0) {
throw Error(
`The implicit shape can't be a fractional number. ` + `Got ${size} / ${shapeProd}`
);
}
const newShape = shape.slice();
newShape[implicitIdx] = size / shapeProd;
return newShape;
}
function parseAxisParam(axis, shape) {
const rank = shape.length;
// Normalize input
axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);
// Check for valid range
assert(
axis.every((ax) => ax >= -rank && ax < rank),
() =>
`All values in axis param must be in range [-${rank}, ${rank}) but ` +
`got axis ${axis}`
);
// Check for only integers
assert(
axis.every((ax) => isInt(ax)),
() => `All values in axis param must be integers but ` + `got axis ${axis}`
);
// Handle negative axis.
return axis.map((a) => (a < 0 ? rank + a : a));
}
/** Reduces the shape by removing all dimensions of shape 1. */
function squeezeShape(shape, axis) {
const newShape = [];
const keptDims = [];
const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
const axes = axis == null || isEmptyArray ? null : parseAxisParam(axis, shape).sort();
let j = 0;
for (let i = 0; i < shape.length; ++i) {
if (axes != null) {
if (axes[j] === i && shape[i] !== 1) {
throw new Error(`Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);
}
if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
newShape.push(shape[i]);
keptDims.push(i);
}
if (axes[j] <= i) {
j++;
}
}
if (shape[i] !== 1) {
newShape.push(shape[i]);
keptDims.push(i);
}
}
return { newShape, keptDims };
}
function getTypedArrayFromDType(dtype, size) {
let values = null;
if (dtype == null || dtype === "float32") {
values = new Float32Array(size);
} else if (dtype === "int32") {
values = new Int32Array(size);
} else if (dtype === "bool") {
values = new Uint8Array(size);
} else {
throw new Error(`Unknown data type ${dtype}`);
}
return values;
}
function getArrayFromDType(dtype, size) {
let values = null;
if (dtype == null || dtype === "float32") {
values = new Float32Array(size);
} else if (dtype === "int32") {
values = new Int32Array(size);
} else if (dtype === "bool") {
values = new Uint8Array(size);
} else if (dtype === "string") {
values = new Array(size);
} else {
throw new Error(`Unknown data type ${dtype}`);
}
return values;
}
function checkConversionForErrors(vals, dtype) {
for (let i = 0; i < vals.length; i++) {
const num = vals[i];
if (isNaN(num) || !isFinite(num)) {
throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);
}
}
}
/** Returns true if the dtype is valid. */
function isValidDtype(dtype) {
return (
dtype === "bool" ||
dtype === "complex64" ||
dtype === "float32" ||
dtype === "int32" ||
dtype === "string"
);
}
/**
* Returns true if the new type can't encode the old type without loss of
* precision.
*/
function hasEncodingLoss(oldType, newType) {
if (newType === "complex64") {
return false;
}
if (newType === "float32" && oldType !== "complex64") {
return false;
}
if (newType === "int32" && oldType !== "float32" && oldType !== "complex64") {
return false;
}
if (newType === "bool" && oldType === "bool") {
return false;
}
return true;
}
function isTypedArray(a) {
return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array;
}
function bytesPerElement(dtype) {
if (dtype === "float32" || dtype === "int32") {
return 4;
} else if (dtype === "complex64") {
return 8;
} else if (dtype === "bool") {
return 1;
} else {
throw new Error(`Unknown dtype ${dtype}`);
}
}
/**
* Returns the approximate number of bytes allocated in the string array - 2
* bytes per character. Computing the exact bytes for a native string in JS is
* not possible since it depends on the encoding of the html page that serves
* the website.
*/
function bytesFromStringArray(arr) {
if (arr == null) {
return 0;
}
let bytes = 0;
arr.forEach((x) => (bytes += x.length));
return bytes;
}
/** Returns true if the value is a string. */
function isString(value) {
return typeof value === "string" || value instanceof String;
}
function isBoolean(value) {
return typeof value === "boolean";
}
function isNumber(value) {
return typeof value === "number";
}
function inferDtype(values) {
if (Array.isArray(values)) {
return inferDtype(values[0]);
}
if (values instanceof Float32Array) {
return "float32";
} else if (values instanceof Int32Array || values instanceof Uint8Array) {
return "int32";
} else if (isNumber(values)) {
return "float32";
} else if (isString(values)) {
return "string";
} else if (isBoolean(values)) {
return "bool";
}
return "float32";
}
function isFunction(f) {
return !!(f && f.constructor && f.call && f.apply);
}
function nearestDivisor(size, start) {
for (let i = start; i < size; ++i) {
if (size % i === 0) {
return i;
}
}
return size;
}
function computeStrides(shape) {
const rank = shape.length;
if (rank < 2) {
return [];
}
// Last dimension has implicit stride of 1, thus having D-1 (instead of D)
// strides.
const strides = new Array(rank - 1);
strides[rank - 2] = shape[rank - 1];
for (let i = rank - 3; i >= 0; --i) {
strides[i] = strides[i + 1] * shape[i + 1];
}
return strides;
}
function toTypedArray(a, dtype, debugMode) {
if (dtype === "string") {
throw new Error("Cannot convert a string[] to a TypedArray");
}
if (Array.isArray(a)) {
a = flatten(a);
}
if (debugMode) {
checkConversionForErrors(a, dtype);
}
if (noConversionNeeded(a, dtype)) {
return a;
}
if (dtype == null || dtype === "float32" || dtype === "complex64") {
return new Float32Array(a);
} else if (dtype === "int32") {
return new Int32Array(a);
} else if (dtype === "bool") {
const bool = new Uint8Array(a.length);
for (let i = 0; i < bool.length; ++i) {
if (Math.round(a[i]) !== 0) {
bool[i] = 1;
}
}
return bool;
} else {
throw new Error(`Unknown data type ${dtype}`);
}
}
function createNestedArray(offset, shape, a) {
const ret = new Array();
if (shape.length === 1) {
const d = shape[0];
for (let i = 0; i < d; i++) {
ret[i] = a[offset + i];
}
} else {
const d = shape[0];
const rest = shape.slice(1);
const len = rest.reduce((acc, c) => acc * c);
for (let i = 0; i < d; i++) {
ret[i] = createNestedArray(offset + i * len, rest, a);
}
}
return ret;
}
// Provide a nested array of TypedArray in given shape.
function toNestedArray(shape, a) {
if (shape.length === 0) {
// Scalar type should return a single number.
return a[0];
}
const size = shape.reduce((acc, c) => acc * c);
if (size === 0) {
// A tensor with shape zero should be turned into empty list.
return [];
}
if (size !== a.length) {
throw new Error(`[${shape}] does not match the input size.`);
}
return createNestedArray(0, shape, a);
}
function noConversionNeeded(a, dtype) {
return (
(a instanceof Float32Array && dtype === "float32") ||
(a instanceof Int32Array && dtype === "int32") ||
(a instanceof Uint8Array && dtype === "bool")
);
}
function makeOnesTypedArray(size, dtype) {
const array = makeZerosTypedArray(size, dtype);
for (let i = 0; i < array.length; i++) {
array[i] = 1;
}
return array;
}
function makeZerosTypedArray(size, dtype) {
if (dtype == null || dtype === "float32" || dtype === "complex64") {
return new Float32Array(size);
} else if (dtype === "int32") {
return new Int32Array(size);
} else if (dtype === "bool") {
return new Uint8Array(size);
} else {
throw new Error(`Unknown data type ${dtype}`);
}
}
/**
* Returns the current high-resolution time in milliseconds relative to an
* arbitrary time in the past. It works across different platforms (node.js,
* browsers).
*
* ```js
* console.log(tf.util.now());
* ```
*/
/** @doc {heading: 'Util', namespace: 'util'} */
function now() {
return Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().platform.now();
}
function assertNonNegativeIntegerDimensions(shape) {
shape.forEach((dimSize) => {
assert(
Number.isInteger(dimSize) && dimSize >= 0,
() =>
`Tensor must have a shape comprised of positive integers but got ` +
`shape [${shape}].`
);
});
}
/**
* Returns a platform-specific implementation of
* [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
*
* If `fetch` is defined on the global object (`window`, `process`, etc.),
* `tf.util.fetch` returns that function.
*
* If not, `tf.util.fetch` returns a platform-specific solution.
*
* ```js
* const resource = await tf.util.fetch('https://unpkg.com/@tensorflow/tfjs');
* // handle response
* ```
*/
/** @doc {heading: 'Util'} */
function fetch(path, requestInits) {
return Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().platform.fetch(
path,
requestInits
);
}
/**
* Encodes the provided string into bytes using the provided encoding scheme.
*
* @param s The string to encode.
* @param encoding The encoding scheme. Defaults to utf-8.
*
*/
/** @doc {heading: 'Util'} */
function encodeString(s, encoding = "utf-8") {
encoding = encoding || "utf-8";
return Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().platform.encode(
s,
encoding
);
}
/**
* Decodes the provided bytes into a string using the provided encoding scheme.
* @param bytes The bytes to decode.
*
* @param encoding The encoding scheme. Defaults to utf-8.
*/
/** @doc {heading: 'Util'} */
function decodeString(bytes, encoding = "utf-8") {
encoding = encoding || "utf-8";
return Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().platform.decode(
bytes,
encoding
);
}
/**
* Computes flat index for a given location (multidimentionsal index) in a
* Tensor/multidimensional array.
*
* @param locs Location in the tensor.
* @param rank Rank of the tensor.
* @param strides Tensor strides.
*/
function locToIndex(locs, rank, strides) {
if (rank === 0) {
return 0;
} else if (rank === 1) {
return locs[0];
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += strides[i] * locs[i];
}
return index;
}
/**
* Computes the location (multidimensional index) in a tensor/multidimentional
* array for a given flat index.
*
* @param index Index in flat array.
* @param rank Rank of tensor.
* @param strides Strides of tensor.
*/
function indexToLoc(index, rank, strides) {
if (rank === 0) {
return [];
} else if (rank === 1) {
return [index];
}
const locs = new Array(rank);
for (let i = 0; i < locs.length - 1; ++i) {
locs[i] = Math.floor(index / strides[i]);
index -= locs[i] * strides[i];
}
locs[locs.length - 1] = index;
return locs;
}
//# sourceMappingURL=util.js.map
/***/
},
/* 2 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return getParamValue;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return getTensor;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function () {
return getTensorsForCurrentContenxt;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return getNodeNameAndIndex;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function () {
return parseNodeName;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function () {
return split;
});
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function getParamValue(paramName, node, tensorMap, context) {
const inputParam = node.inputParams[paramName];
if (inputParam && inputParam.inputIndexStart !== undefined) {
const start = inputParam.inputIndexStart;
const end =
inputParam.inputIndexEnd === 0
? undefined
: inputParam.inputIndexEnd === undefined
? start + 1
: inputParam.inputIndexEnd;
if (inputParam.type === "tensor") {
return getTensor(node.inputNames[inputParam.inputIndexStart], tensorMap, context);
}
if (inputParam.type === "tensors") {
const inputs = node.inputNames.slice(start, end);
return inputs.map((name) => getTensor(name, tensorMap, context));
}
const data = Array.prototype.slice.call(
getTensor(node.inputNames.slice(start)[0], tensorMap, context).dataSync()
);
return inputParam.type === "number" ? data[0] : data;
}
const attrParam = node.attrParams[paramName];
return attrParam && attrParam.value;
}
/**
* Retrieve the tensor based on input name by extracting the node name and
* output index information.
* @param name Node input name
* @param tensorsMap Tensors map keyed by the node
*/
function getTensor(name, tensorsMap, context) {
const [nodeName, index] = parseNodeName(name);
const contextId = context.currentContextIds.find((contextId) => {
return !!tensorsMap[getNodeNameWithContextId(nodeName, contextId)];
});
return contextId !== undefined
? tensorsMap[getNodeNameWithContextId(nodeName, contextId)][index]
: undefined;
}
/**
* Retrieve the tensors based on input name for current context.
* @param name Node input name
* @param tensorsMap Tensors map keyed by the node
*/
function getTensorsForCurrentContenxt(name, tensorsMap, context) {
return tensorsMap[getNodeNameWithContextId(name, context.currentContextId)];
}
/**
* Returns the node name and index from the Node input name.
* @param inputName The input name of the node, in format of
* node_name:output_index, i.e. MatMul:0, if the output_index is not set, it is
* default to 0.
*/
function getNodeNameAndIndex(inputName, context) {
const [nodeName, index] = parseNodeName(inputName);
return [getNodeNameWithContextId(nodeName, context && context.currentContextId), index];
}
function getNodeNameWithContextId(name, contextId) {
return !!contextId ? `${name}-${contextId}` : name;
}
function parseNodeName(name) {
const parts = name.split(":");
if (parts.length === 1) {
return [name, 0];
}
const nodeName = parts[0];
return [nodeName, Number(parts[parts.length - 1])];
}
function split(arr, size) {
const res = [];
for (let i = 0; i < arr.length; i += size) {
res.push(arr.slice(i, i + size));
}
return res;
}
//# sourceMappingURL=utils.js.map
/***/
},
/* 3 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return inferShape;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return convertToTensor;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return convertToTensorArray;
});
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _environment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10);
/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function inferShape(val, dtype) {
let firstElem = val;
if (Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(val)) {
return dtype === "string" ? [] : [val.length];
}
if (!Array.isArray(val)) {
return []; // Scalar.
}
const shape = [];
while (
Array.isArray(firstElem) ||
(Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(firstElem) &&
dtype !== "string")
) {
shape.push(firstElem.length);
firstElem = firstElem[0];
}
if (
Array.isArray(val) &&
Object(_environment__WEBPACK_IMPORTED_MODULE_1__[/* env */ "c"])().getBool(
"TENSORLIKE_CHECK_SHAPE_CONSISTENCY"
)
) {
deepAssertShapeConsistency(val, shape, []);
}
return shape;
}
function deepAssertShapeConsistency(val, shape, indices) {
indices = indices || [];
if (
!Array.isArray(val) &&
!Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(val)
) {
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assert"])(
shape.length === 0,
() =>
`Element arr[${indices.join("][")}] is a primitive, ` +
`but should be an array/TypedArray of ${shape[0]} elements`
);
return;
}
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assert"])(
shape.length > 0,
() =>
`Element arr[${indices.join("][")}] should be a primitive, ` +
`but is an array of ${val.length} elements`
);
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assert"])(
val.length === shape[0],
() =>
`Element arr[${indices.join("][")}] should have ${shape[0]} ` +
`elements, but has ${val.length} elements`
);
const subShape = shape.slice(1);
for (let i = 0; i < val.length; ++i) {
deepAssertShapeConsistency(val[i], subShape, indices.concat(i));
}
}
function assertDtype(expectedDtype, actualDType, argName, functionName) {
if (expectedDtype == null) {
return;
}
if (
(expectedDtype !== "numeric" && expectedDtype !== actualDType) ||
(expectedDtype === "numeric" && actualDType === "string")
) {
throw new Error(
`Argument '${argName}' passed to '${functionName}' must ` +
`be ${expectedDtype} tensor, but got ${actualDType} tensor`
);
}
}
function convertToTensor(x, argName, functionName, parseAsDtype = "numeric") {
if (x instanceof _tensor__WEBPACK_IMPORTED_MODULE_2__[/* Tensor */ "a"]) {
assertDtype(parseAsDtype, x.dtype, argName, functionName);
return x;
}
let inferredDtype = Object(_util__WEBPACK_IMPORTED_MODULE_3__["inferDtype"])(x);
// If the user expects a bool/int/float, use that info to update the
// inferredDtype when it is not a string.
if (inferredDtype !== "string" && ["bool", "int32", "float32"].indexOf(parseAsDtype) >= 0) {
inferredDtype = parseAsDtype;
}
assertDtype(parseAsDtype, inferredDtype, argName, functionName);
if (
x == null ||
(!Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(x) &&
!Array.isArray(x) &&
typeof x !== "number" &&
typeof x !== "boolean" &&
typeof x !== "string")
) {
const type = x == null ? "null" : x.constructor.name;
throw new Error(
`Argument '${argName}' passed to '${functionName}' must be a ` +
`Tensor or TensorLike, but got '${type}'`
);
}
const inferredShape = inferShape(x, inferredDtype);
if (!Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(x) && !Array.isArray(x)) {
x = [x];
}
const skipTypedArray = true;
const values =
inferredDtype !== "string"
? Object(_util__WEBPACK_IMPORTED_MODULE_3__["toTypedArray"])(
x,
inferredDtype,
Object(_environment__WEBPACK_IMPORTED_MODULE_1__[/* env */ "c"])().getBool("DEBUG")
)
: Object(_util__WEBPACK_IMPORTED_MODULE_3__["flatten"])(x, [], skipTypedArray);
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].makeTensor(
values,
inferredShape,
inferredDtype
);
}
function convertToTensorArray(arg, argName, functionName, parseAsDtype = "numeric") {
if (!Array.isArray(arg)) {
throw new Error(
`Argument ${argName} passed to ${functionName} must be a ` +
"`Tensor[]` or `TensorLike[]`"
);
}
const tensors = arg;
return tensors.map(
(t, i) => convertToTensor(t, `${argName}[${i}]`, functionName),
parseAsDtype
);
}
//# sourceMappingURL=tensor_util_env.js.map
/***/
},
/* 4 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return op;
});
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Used for wrapping functions that perform math operations on
* Tensors. The function will be wrapped in a named scope that cleans all
* memory usage after the function is done.
*/
function op(f) {
const keys = Object.keys(f);
if (keys.length !== 1) {
throw new Error(
`Please provide an object with a single key ` +
`(operation name) mapping to a function. Got an object with ` +
`${keys.length} keys.`
);
}
let opName = keys[0];
const fn = f[opName];
// Strip the underscore from the end of the function name.
if (opName.endsWith("_")) {
opName = opName.substring(0, opName.length - 1);
}
// tslint:disable-next-line:no-any
const f2 = (...args) => {
_engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].startScope(opName);
try {
const result = fn(...args);
if (result instanceof Promise) {
console.error("Cannot return a Promise inside of tidy.");
}
_engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].endScope(result);
return result;
} catch (ex) {
_engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].endScope(null);
throw ex;
}
};
Object.defineProperty(f2, "name", { value: opName, configurable: true });
// tslint:disable-next-line:no-any
return f2;
}
//# sourceMappingURL=operation.js.map
/***/
},
/* 5 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function () {
return /* binding */ ENGINE;
});
// UNUSED EXPORTS: Engine
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/environment.js
var dist_environment = __webpack_require__(10);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/global_util.js
var global_util = __webpack_require__(33);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/kernel_registry.js
var kernel_registry = __webpack_require__(17);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/util.js
var util = __webpack_require__(1);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/profiler.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Profiler {
constructor(backendTimer, logger) {
this.backendTimer = backendTimer;
this.logger = logger;
if (logger == null) {
this.logger = new profiler_Logger();
}
}
profileKernel(kernelName, inputs, f) {
let outputs;
const holdResultWrapperFn = () => {
outputs = f();
};
const timer = this.backendTimer.time(holdResultWrapperFn);
outputs.forEach((r) => {
// Dangling promise here because we don't want to propagate up
// asynchronicity.
r.data().then((vals) => {
checkComputationForErrors(vals, r.dtype, kernelName);
timer.then((timing) => {
let extraInfo = "";
if (timing.getExtraProfileInfo != null) {
extraInfo = timing.getExtraProfileInfo();
}
this.logger.logKernelProfile(
kernelName,
r,
vals,
timing.kernelMs,
inputs,
extraInfo
);
});
});
});
return outputs;
}
}
function checkComputationForErrors(vals, dtype, kernelName) {
if (dtype !== "float32") {
// Only floating point computations will generate NaN values
return false;
}
for (let i = 0; i < vals.length; i++) {
const num = vals[i];
if (isNaN(num) || !isFinite(num)) {
// Throwing custom exception so behavior is testable.
console.warn(`Found ${num} in the result of '${kernelName}'`);
return true;
}
}
return false;
}
class profiler_Logger {
logKernelProfile(name, result, vals, timeMs, inputs, extraInfo) {
const time =
typeof timeMs === "number" ? util["rightPad"](`${timeMs}ms`, 9) : timeMs["error"];
const paddedName = util["rightPad"](name, 25);
const rank = result.rank;
const size = result.size;
const shape = util["rightPad"](result.shape.toString(), 14);
let inputShapesDescription = "";
for (const name in inputs) {
const input = inputs[name];
// The input might be a non-tensor (e.g HTMLImageElement), in which case
// we claim the output shape as input shape.
const inputShape = input.shape || result.shape;
const inputRank = inputShape.length;
inputShapesDescription += `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ""} `;
}
console.log(
`%c${paddedName}\t%c${time}\t%c${rank}D ${shape}\t%c${size}\t%c${inputShapesDescription}\t%c${extraInfo}`,
"font-weight:bold",
"color:red",
"color:blue",
"color: orange",
"color: green",
"color: steelblue"
);
}
}
//# sourceMappingURL=profiler.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tape.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes a list of TapeNodes that connect x to y, filtering everything else
* out and preserving the order of the original tape elements.
*
* @param tape The tape elements to filter.
* @param xs The input Tensors.
* @param y The output Tensor.
*/
function getFilteredNodesXToY(tape, xs, y) {
// Forward pass to compute all the nodes and Tensors that are transitively a
// function of x.
const tensorsFromX = {};
const nodesFromX = {};
for (let i = 0; i < xs.length; i++) {
tensorsFromX[xs[i].id] = true;
}
for (let i = 0; i < tape.length; i++) {
const node = tape[i];
const nodeInputs = node.inputs;
for (const inputName in nodeInputs) {
const input = nodeInputs[inputName];
let anyInputFromX = false;
for (let j = 0; j < xs.length; j++) {
if (tensorsFromX[input.id]) {
node.outputs.forEach((output) => (tensorsFromX[output.id] = true));
anyInputFromX = true;
nodesFromX[node.id] = true;
break;
}
}
if (anyInputFromX) {
break;
}
}
}
// Backward pass to find all of the nodes and Tensors that lead to y.
const tensorsLeadToY = {};
tensorsLeadToY[y.id] = true;
const nodesToY = {};
for (let i = tape.length - 1; i >= 0; i--) {
const node = tape[i];
const nodeInputs = node.inputs;
// If any of the outputs lead to y, mark all of the inputs as leading to y.
for (let j = 0; j < node.outputs.length; j++) {
if (tensorsLeadToY[node.outputs[j].id]) {
for (const inputName in nodeInputs) {
tensorsLeadToY[nodeInputs[inputName].id] = true;
nodesToY[node.id] = true;
}
break;
}
}
}
// Return the paths that come from x and lead to y.
const filteredTape = [];
for (let i = 0; i < tape.length; i++) {
const node = tape[i];
if (nodesFromX[node.id] && nodesToY[node.id]) {
// Prune the inputs from the node that aren't a function of x.
const prunedInputs = {};
for (const inputName in node.inputs) {
const nodeInput = node.inputs[inputName];
if (tensorsFromX[nodeInput.id]) {
prunedInputs[inputName] = nodeInput;
}
}
// Copy the node and overwrite inputsAndArgs to the pruned version.
const prunedNode = Object.assign({}, node);
prunedNode.inputs = prunedInputs;
prunedNode.outputs = node.outputs;
filteredTape.push(prunedNode);
}
}
return filteredTape;
}
/**
* Backpropagate gradients through the filtered TapeNodes.
*
* @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map
* is mutated by this method.
* @param filteredTape The filtered TapeNodes to backprop through.
*/
function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy) {
// Walk the tape backward and keep a map of Tensor to its gradient.
for (let i = filteredTape.length - 1; i >= 0; i--) {
const node = filteredTape[i];
const dys = [];
node.outputs.forEach((o) => {
const gradTensor = tensorAccumulatedGradientMap[o.id];
if (gradTensor != null) {
dys.push(gradTensor);
} else {
// This particular output is not in the back-propagation subgraph, so it
// does not affect the final output, thus we put null for its dy.
dys.push(null);
}
});
if (node.gradient == null) {
throw new Error(
`Cannot compute gradient: gradient function not found ` + `for ${node.kernelName}.`
);
}
// Backprop dy through this node and accumulate gradients over the inputs.
const inputGradients = node.gradient(dys);
for (const inputName in node.inputs) {
if (!(inputName in inputGradients)) {
throw new Error(
`Cannot backprop through input ${inputName}. ` +
`Available gradients found: ${Object.keys(inputGradients)}.`
);
}
// Call the gradient function.
const dx = tidy(() => inputGradients[inputName]());
if (dx.dtype !== "float32") {
throw new Error(
`Error in gradient for op ${node.kernelName}. The gradient of input ` +
`${inputName} must have 'float32' dtype, but has '${dx.dtype}'`
);
}
const x = node.inputs[inputName];
if (!util["arraysEqual"](dx.shape, x.shape)) {
throw new Error(
`Error in gradient for op ${node.kernelName}. The gradient of input ` +
`'${inputName}' has shape '${dx.shape}', which does not match ` +
`the shape of the input '${x.shape}'`
);
}
if (tensorAccumulatedGradientMap[x.id] == null) {
tensorAccumulatedGradientMap[x.id] = dx;
} else {
const curGradient = tensorAccumulatedGradientMap[x.id];
tensorAccumulatedGradientMap[x.id] = curGradient.add(dx);
curGradient.dispose();
}
}
}
}
//# sourceMappingURL=tape.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor.js + 1 modules
var tensor = __webpack_require__(7);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor_util.js
var tensor_util = __webpack_require__(11);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/engine.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class EngineState {
constructor() {
// Public since optimizers will use it.
this.registeredVariables = {};
this.nextTapeNodeId = 0;
this.numBytes = 0;
this.numTensors = 0;
this.numStringTensors = 0;
this.numDataBuffers = 0;
// Number of nested tf.grad() statements when computing higher-order
// gradients. E.g. `1` for first-order gradients and `2` for second-order
// gradients. Used to track if the tape should be removed after a backprop.
this.gradientDepth = 0;
// Number of nested kernel calls. When kernel depth is greater than 1, we turn
// off the tape.
this.kernelDepth = 0;
this.scopeStack = [];
/**
* Keeps track of the number of data moves during a kernel execution. We
* maintain a stack since kernels can call other kernels, recursively.
*/
this.numDataMovesStack = [];
this.nextScopeId = 0;
this.tensorInfo = new WeakMap();
this.profiling = false;
this.activeProfile = {
newBytes: 0,
newTensors: 0,
peakBytes: 0,
kernels: [],
result: null,
};
}
dispose() {
for (const variableName in this.registeredVariables) {
this.registeredVariables[variableName].dispose();
}
}
}
class engine_Engine {
constructor(ENV) {
this.ENV = ENV;
this.registry = {};
this.registryFactory = {};
this.pendingBackendInitId = 0;
this.state = new EngineState();
}
async ready() {
if (this.pendingBackendInit != null) {
return this.pendingBackendInit.then(() => {});
}
if (this.backendInstance != null) {
return;
}
const sortedBackends = this.getSortedBackends();
for (let i = 0; i < sortedBackends.length; i++) {
const backendName = sortedBackends[i];
const success = await this.initializeBackend(backendName).success;
if (success) {
await this.setBackend(backendName);
return;
}
}
throw new Error(
`Could not initialize any backends, all backend initializations ` + `failed.`
);
}
get backend() {
if (this.pendingBackendInit != null) {
throw new Error(
`Backend '${this.backendName}' has not yet been initialized. Make ` +
`sure to await tf.ready() or await tf.setBackend() before calling ` +
`other methods`
);
}
if (this.backendInstance == null) {
const { name, asyncInit } = this.initializeBackendsAndReturnBest();
if (asyncInit) {
throw new Error(
`The highest priority backend '${name}' has not yet been ` +
`initialized. Make sure to await tf.ready() or ` +
`await tf.setBackend() before calling other methods`
);
}
this.setBackend(name);
}
return this.backendInstance;
}
backendNames() {
return Object.keys(this.registryFactory);
}
findBackend(backendName) {
if (!(backendName in this.registry)) {
// If the backend hasn't been initialized but we have a registry entry for
// it, initialize it and return it.
if (backendName in this.registryFactory) {
const { asyncInit } = this.initializeBackend(backendName);
if (asyncInit) {
// Backend is not ready yet.
return null;
}
} else {
return null;
}
}
return this.registry[backendName];
}
findBackendFactory(backendName) {
if (!(backendName in this.registryFactory)) {
return null;
}
return this.registryFactory[backendName].factory;
}
registerBackend(backendName, factory, priority = 1) {
if (backendName in this.registryFactory) {
console.warn(
`${backendName} backend was already registered. ` +
`Reusing existing backend factory.`
);
return false;
}
this.registryFactory[backendName] = { factory, priority };
return true;
}
async setBackend(backendName) {
if (this.registryFactory[backendName] == null) {
throw new Error(`Backend name '${backendName}' not found in registry`);
}
this.backendName = backendName;
if (this.registry[backendName] == null) {
this.backendInstance = null;
const { success, asyncInit } = this.initializeBackend(backendName);
const result = asyncInit ? await success : success;
if (!result) {
return false;
}
}
this.backendInstance = this.registry[backendName];
this.setupRegisteredKernels();
// Reset the profiler.
this.profiler = new Profiler(this.backendInstance);
return true;
}
setupRegisteredKernels() {
const kernels = Object(kernel_registry["c" /* getKernelsForBackend */])(this.backendName);
kernels.forEach((kernel) => {
if (kernel.setupFunc != null) {
kernel.setupFunc(this.backendInstance);
}
});
}
disposeRegisteredKernels(backendName) {
const kernels = Object(kernel_registry["c" /* getKernelsForBackend */])(backendName);
kernels.forEach((kernel) => {
if (kernel.disposeFunc != null) {
kernel.disposeFunc(this.registry[backendName]);
}
});
}
/**
* Initializes a backend by looking up the backend name in the factory
* registry and calling the factory method. Returns a boolean representing
* whether the initialization of the backend suceeded. Throws an error if
* there is no backend in the factory registry.
*/
initializeBackend(backendName) {
const registryFactoryEntry = this.registryFactory[backendName];
if (registryFactoryEntry == null) {
throw new Error(`Cannot initialize backend ${backendName}, no registration found.`);
}
try {
const backend = registryFactoryEntry.factory();
// Test if the factory returns a promise.
if (Promise.resolve(backend) === backend) {
const promiseId = ++this.pendingBackendInitId;
const success = backend
.then((backendInstance) => {
// Outdated promise. Another backend was set in the meantime.
if (promiseId < this.pendingBackendInitId) {
return false;
}
this.registry[backendName] = backendInstance;
this.pendingBackendInit = null;
return true;
})
.catch((err) => {
// Outdated promise. Another backend was set in the meantime.
if (promiseId < this.pendingBackendInitId) {
return false;
}
this.pendingBackendInit = null;
console.warn(`Initialization of backend ${backendName} failed`);
console.warn(err.stack || err.message);
return false;
});
this.pendingBackendInit = success;
return { success, asyncInit: true };
} else {
this.registry[backendName] = backend;
return { success: true, asyncInit: false };
}
} catch (err) {
console.warn(`Initialization of backend ${backendName} failed`);
console.warn(err.stack || err.message);
return { success: false, asyncInit: false };
}
}
removeBackend(backendName) {
if (!(backendName in this.registryFactory)) {
throw new Error(`${backendName} backend not found in registry`);
}
if (this.backendName === backendName && this.pendingBackendInit != null) {
// There is a pending promise of the backend we want to remove. Make it
// obsolete.
this.pendingBackendInitId++;
}
if (backendName in this.registry) {
this.disposeRegisteredKernels(backendName);
this.registry[backendName].dispose();
delete this.registry[backendName];
}
delete this.registryFactory[backendName];
// Unset the backend if it is active.
if (this.backendName === backendName) {
this.pendingBackendInit = null;
this.backendName = null;
this.backendInstance = null;
}
}
getSortedBackends() {
if (Object.keys(this.registryFactory).length === 0) {
throw new Error("No backend found in registry.");
}
return Object.keys(this.registryFactory).sort((a, b) => {
// Highest priority comes first.
return this.registryFactory[b].priority - this.registryFactory[a].priority;
});
}
initializeBackendsAndReturnBest() {
const sortedBackends = this.getSortedBackends();
for (let i = 0; i < sortedBackends.length; i++) {
const backendName = sortedBackends[i];
const { success, asyncInit } = this.initializeBackend(backendName);
if (asyncInit || success) {
return { name: backendName, asyncInit };
}
}
throw new Error(
`Could not initialize any backends, all backend initializations ` + `failed.`
);
}
moveData(backend, dataId) {
const info = this.state.tensorInfo.get(dataId);
const srcBackend = info.backend;
const values = this.readSync(dataId);
// Delete the tensor from the old backend and move it to the new
// backend.
srcBackend.disposeData(dataId);
info.backend = backend;
backend.move(dataId, values, info.shape, info.dtype);
if (this.shouldCheckForMemLeaks()) {
// Track the number of moves during a kernel execution to correctly
// detect memory leaks.
this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
}
}
tidy(nameOrFn, fn) {
let name = null;
if (fn == null) {
// Called with only 1 argument.
if (typeof nameOrFn !== "function") {
throw new Error("Please provide a function to tidy()");
}
fn = nameOrFn;
} else {
// Called with 2 arguments.
if (typeof nameOrFn !== "string" && !(nameOrFn instanceof String)) {
throw new Error(
"When calling with two arguments, the first argument " +
"to tidy() must be a string"
);
}
if (typeof fn !== "function") {
throw new Error(
"When calling with two arguments, the 2nd argument " +
"to tidy() must be a function"
);
}
name = nameOrFn;
// TODO(nsthorat,smilkov): Do operation logging and performance
// profiling.
}
let result;
return this.scopedRun(
() => this.startScope(name),
() => this.endScope(result),
() => {
result = fn();
if (result instanceof Promise) {
console.error("Cannot return a Promise inside of tidy.");
}
return result;
}
);
}
scopedRun(start, end, f) {
start();
try {
const res = f();
end();
return res;
} catch (ex) {
end();
throw ex;
}
}
nextTensorId() {
return engine_Engine.nextTensorId++;
}
nextVariableId() {
return engine_Engine.nextVariableId++;
}
/**
* This method is called instead of the public-facing tensor.clone() when
* saving a tensor for backwards pass. It makes sure to add the clone
* operation to the tape regardless of being called inside a kernel
* execution.
*
* This method will go away once all kernels are modularized since we won't
* need to turn off the tape inside runKernel().
*/
clone(x) {
const y = this.makeTensorFromDataId(x.dataId, x.shape, x.dtype);
const inputs = { x };
const grad = (dy) => ({ x: () => dy.toFloat() });
const saved = [];
this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});
return y;
}
/**
* Execute a kernel with the given name and return the output tensor.
*
* @param kernelName The name of the kernel to execute.
* @param inputs A map of input names to tensors.
* @param attrs A map of attribute names to their values. An attribute is a
* primitive (non-tensor) input to the kernel.
* @param inputsToSave A list of tensors, inputs to save for the backprop
* computation.
* @param outputsToSave A list of booleans, specifying which output to save
* for the backprop computation. These are booleans since the output
* tensors are not visible to the user.
*/
runKernel(kernelName, inputs, attrs, inputsToSave, outputsToSave) {
const forwardFunc = null;
const backwardsFunc = null;
// Call runKernel as a stop-gap until we modularize all kernels.
// Once we modularize all kernels, we will remove the existing
// `runKernelFunc`.
return this.runKernelFunc(
forwardFunc,
inputs,
backwardsFunc,
kernelName,
attrs,
inputsToSave,
outputsToSave
);
}
shouldCheckForMemLeaks() {
return this.ENV.getBool("IS_TEST");
}
checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos) {
const numDataIdsAfter = this.backend.numDataIds();
// Count the number of data ids associated with the result of the kernel.
let numOutputDataIds = 0;
outInfos.forEach((info) => {
// Complex numbers allocate 3 data ids, one for 'real', one for
// 'imaginary', and one for the container that holds the former two.
numOutputDataIds += info.dtype === "complex64" ? 3 : 1;
});
// Account for the number of moves during kernel execution. A "data move"
// can happen in the middle of a kernel execution, placing a new (key,value)
// pair in the data storage. Since data moves have net zero effect (we
// always remove the data from the old backend), we have to cancel them out
// when detecting memory leaks.
const numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];
const dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;
if (dataIdsLeaked > 0) {
throw new Error(
`Backend '${this.backendName}' has an internal memory leak ` +
`(${dataIdsLeaked} data ids) after running '${kernelName}'`
);
}
}
/**
* @deprecated Use `runKernel` for newly added kernels. Keep using this method
* only for kernels that are not yet fully modularized.
*/
runKernelFunc(
forwardFunc,
inputs,
backwardsFunc,
kernelName,
attrs,
inputsToSave,
outputsToSave
) {
let outputs;
let saved = [];
const isTapeOn = this.isTapeOn();
if (kernelName == null) {
kernelName = this.state.activeScope != null ? this.state.activeScope.name : "";
}
const startingBytecount = this.state.numBytes;
const startingNumTensors = this.state.numTensors;
if (this.shouldCheckForMemLeaks()) {
this.state.numDataMovesStack.push(0);
}
let kernelFunc;
const kernel = Object(kernel_registry["b" /* getKernel */])(kernelName, this.backendName);
let out;
if (kernel != null) {
kernelFunc = () => {
const numDataIdsBefore = this.backend.numDataIds();
out = kernel.kernelFunc({ inputs, attrs, backend: this.backend });
const outInfos = Array.isArray(out) ? out : [out];
if (this.shouldCheckForMemLeaks()) {
this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);
}
const outTensors = outInfos.map(({ dataId, shape, dtype }) =>
this.makeTensorFromDataId(dataId, shape, dtype)
);
// Save the inputs and outputs.
// Do not save unless we are recording to the tape. Otherwise it would
// cause a mem leak since we would never run backprop, which disposes
// the kept tensors.
if (isTapeOn) {
let tensorsToSave = this.getTensorsForGradient(kernelName, inputs, outTensors);
if (tensorsToSave == null) {
// Fallback for ops that call runKernelFunc and pass in
// inputsToSave and outputsToSave. Currently this is the set of ops
// with kernel support in the WASM backend. Once those ops and
// respective gradients are modularised we can remove this path.
if (outputsToSave == null) {
outputsToSave = [];
}
const outsToSave = outTensors.filter((_, i) => outputsToSave[i]);
tensorsToSave = (inputsToSave || []).slice().concat(outsToSave);
}
saved = this.saveTensorsForBackwardMode(tensorsToSave);
}
return outTensors;
};
} else {
const saveFunc = (tensors) => {
// Do not save unless we are recording to the tape. Otherwise it would
// cause a mem leak since we would never run backprop, which disposes
// the kept tensors.
if (!isTapeOn) {
return;
}
saved = tensors.map((tensor) => this.keep(this.clone(tensor)));
};
kernelFunc = () => {
const numDataIdsBefore = this.backend.numDataIds();
out = this.tidy(() => forwardFunc(this.backend, saveFunc));
const outs = Array.isArray(out) ? out : [out];
if (this.shouldCheckForMemLeaks()) {
this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outs);
}
return outs;
};
}
// Stop recording to a tape when running a kernel.
this.scopedRun(
() => this.state.kernelDepth++,
() => this.state.kernelDepth--,
() => {
if (!this.ENV.getBool("DEBUG")) {
outputs = kernelFunc();
} else {
outputs = this.profiler.profileKernel(kernelName, inputs, () => kernelFunc());
}
}
);
if (isTapeOn) {
this.addTapeNode(kernelName, inputs, outputs, backwardsFunc, saved, attrs);
}
if (this.state.profiling) {
this.state.activeProfile.kernels.push({
name: kernelName,
bytesAdded: this.state.numBytes - startingBytecount,
totalBytesSnapshot: this.state.numBytes,
tensorsAdded: this.state.numTensors - startingNumTensors,
totalTensorsSnapshot: this.state.numTensors,
inputShapes: Object.keys(inputs).map((key) => inputs[key].shape),
outputShapes: outputs.map((item) => item.shape),
});
}
return Array.isArray(out) ? outputs : outputs[0];
}
/**
* Saves tensors used in forward mode for use in backward mode.
*
* @param tensors the list of tensors to save.
*/
saveTensorsForBackwardMode(tensors) {
const saved = tensors.map((tensor) => this.keep(this.clone(tensor)));
return saved;
}
/**
* Returns a list of tensors to save for a given gradient calculation.
*
* Returns undefined if their is no registered gradient for this kernel in the
* gradient registry.
*
* @param kernelName name of kernel to look up gradient for.
* @param inputs a map of input tensors.
* @param outputs an array of output tensors from forward mode of kernel.
*/
getTensorsForGradient(kernelName, inputs, outputs) {
const gradConfig = Object(kernel_registry["a" /* getGradient */])(kernelName);
if (gradConfig != null) {
const inputsToSave = gradConfig.inputsToSave || [];
const outputsToSave = gradConfig.outputsToSave || [];
// If saveAllInputs is true, all inputs will be saved. Otherwise, inputs
// specified in inputsToSave will be saved.
let inputTensorsToSave;
if (gradConfig.saveAllInputs) {
util["assert"](
Array.isArray(inputs),
() => "saveAllInputs is true, expected inputs to be an array."
);
inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);
} else {
inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);
}
const outputTensorsToSave = outputs.filter((_, i) => outputsToSave[i]);
return inputTensorsToSave.concat(outputTensorsToSave);
}
// TODO(yassogba) throw exception here once all runkernelFunc calls with
// inputsToSave/outputsToSave are removed
return null;
}
/**
* Internal method used by public APIs for tensor creation. Makes a new
* tensor with the provided shape, dtype and values. It always
* creates a new data id and writes the values to the underlying backend.
*/
makeTensor(values, shape, dtype, backend) {
if (values == null) {
throw new Error("Values passed to engine.makeTensor() are null");
}
dtype = dtype || "float32";
backend = backend || this.backend;
let backendVals = values;
if (dtype === "string" && util["isString"](values[0])) {
backendVals = values.map((d) => util["encodeString"](d));
}
const dataId = backend.write(backendVals, shape, dtype);
const t = new tensor["a" /* Tensor */](shape, dtype, dataId, this.nextTensorId());
this.incRef(t, backend);
// Count bytes for string tensors.
if (dtype === "string") {
const info = this.state.tensorInfo.get(dataId);
const newBytes = Object(util["bytesFromStringArray"])(backendVals);
this.state.numBytes += newBytes - info.bytes;
info.bytes = newBytes;
}
return t;
}
/**
* Internal method used by backends. Makes a new tensor
* that is a wrapper around an existing data id. It doesn't create
* a new data id, only increments the ref count used in memory tracking.
*/
makeTensorFromDataId(dataId, shape, dtype, backend) {
dtype = dtype || "float32";
const t = new tensor["a" /* Tensor */](shape, dtype, dataId, this.nextTensorId());
this.incRef(t, backend);
return t;
}
makeVariable(initialValue, trainable = true, name, dtype) {
name = name || this.nextVariableId().toString();
if (dtype != null && dtype !== initialValue.dtype) {
initialValue = initialValue.asType(dtype);
}
const v = new tensor["c" /* Variable */](
initialValue,
trainable,
name,
this.nextTensorId()
);
if (this.state.registeredVariables[v.name] != null) {
throw new Error(`Variable with name ${v.name} was already registered`);
}
this.state.registeredVariables[v.name] = v;
this.incRef(v, this.backend);
return v;
}
incRef(a, backend) {
const refCount = this.state.tensorInfo.has(a.dataId)
? this.state.tensorInfo.get(a.dataId).refCount
: 0;
this.state.numTensors++;
if (a.dtype === "string") {
this.state.numStringTensors++;
}
if (refCount === 0) {
this.state.numDataBuffers++;
// Bytes for complex numbers are counted by their components. Bytes for
// string tensors are counted when writing values.
let bytes = 0;
if (a.dtype !== "complex64" && a.dtype !== "string") {
bytes = a.size * util["bytesPerElement"](a.dtype);
}
this.state.tensorInfo.set(a.dataId, {
backend: backend || this.backend,
dtype: a.dtype,
shape: a.shape,
bytes,
refCount: 0,
});
this.state.numBytes += bytes;
}
this.state.tensorInfo.get(a.dataId).refCount++;
if (!(a instanceof tensor["c" /* Variable */])) {
this.track(a);
}
}
disposeTensor(a) {
if (!this.state.tensorInfo.has(a.dataId)) {
return;
}
this.state.numTensors--;
if (a.dtype === "string") {
this.state.numStringTensors--;
}
const info = this.state.tensorInfo.get(a.dataId);
const refCount = info.refCount;
if (refCount <= 1) {
// Don't count bytes for complex numbers as they are counted by their
// components.
if (a.dtype !== "complex64") {
this.state.numBytes -= info.bytes;
}
this.state.numDataBuffers--;
info.backend.disposeData(a.dataId);
this.state.tensorInfo.delete(a.dataId);
} else {
this.state.tensorInfo.get(a.dataId).refCount--;
}
// TODO(nsthorat): Construct an error and save the stack trace for
// debugging when in debug mode. Creating a stack trace is too expensive
// to do unconditionally.
}
disposeVariables() {
for (const varName in this.state.registeredVariables) {
const v = this.state.registeredVariables[varName];
this.disposeVariable(v);
}
}
disposeVariable(v) {
this.disposeTensor(v);
if (this.state.registeredVariables[v.name] != null) {
delete this.state.registeredVariables[v.name];
}
}
memory() {
const info = this.backend.memory();
info.numTensors = this.state.numTensors;
info.numDataBuffers = this.state.numDataBuffers;
info.numBytes = this.state.numBytes;
if (this.state.numStringTensors > 0) {
info.unreliable = true;
if (info.reasons == null) {
info.reasons = [];
}
info.reasons.push(
"Memory usage by string tensors is approximate " + "(2 bytes per character)"
);
}
return info;
}
async profile(query) {
this.state.profiling = true;
const startBytes = this.state.numBytes;
const startNumTensors = this.state.numTensors;
this.state.activeProfile.kernels = [];
this.state.activeProfile.result = query();
this.state.profiling = false;
this.state.activeProfile.peakBytes = Math.max(
...this.state.activeProfile.kernels.map((d) => d.totalBytesSnapshot)
);
this.state.activeProfile.newBytes = this.state.numBytes - startBytes;
this.state.activeProfile.newTensors = this.state.numTensors - startNumTensors;
return this.state.activeProfile;
}
isTapeOn() {
return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
}
addTapeNode(kernelName, inputs, outputs, gradientsFunc, saved, attrs) {
const tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved };
const gradConfig = Object(kernel_registry["a" /* getGradient */])(kernelName);
if (gradConfig != null) {
gradientsFunc = gradConfig.gradFunc;
}
if (gradientsFunc != null) {
tapeNode.gradient = (dys) => {
// TODO(smilkov): To optimize back-prop, pass dys that are not used in
// the backprop graph to the user as null instead of zeros
dys = dys.map((dy, i) => {
if (dy == null) {
const output = outputs[i];
const vals = util["makeZerosTypedArray"](output.size, output.dtype);
return this.makeTensor(vals, output.shape, output.dtype);
}
return dy;
});
// Grad functions of ops with single outputs expect a dy, while ops
// with multiple outputs expect dys (array of dy).
return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);
};
}
this.state.activeTape.push(tapeNode);
}
keep(result) {
result.kept = true;
return result;
}
startTape() {
if (this.state.gradientDepth === 0) {
this.state.activeTape = [];
}
this.state.gradientDepth++;
}
endTape() {
this.state.gradientDepth--;
}
/**
* Start a scope. Use this with endScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
startScope(name) {
const scopeInfo = {
track: [],
name: "unnamed scope",
id: this.state.nextScopeId++,
};
if (name) {
scopeInfo.name = name;
}
this.state.scopeStack.push(scopeInfo);
this.state.activeScope = scopeInfo;
}
/**
* End a scope. Use this with startScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
endScope(result) {
const tensorsToTrackInParent = Object(tensor_util["getTensorsInContainer"])(result);
const tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map((t) => t.id));
// Dispose the arrays tracked in this scope.
for (let i = 0; i < this.state.activeScope.track.length; i++) {
const tensor = this.state.activeScope.track[i];
if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {
tensor.dispose();
}
}
const oldScope = this.state.scopeStack.pop();
this.state.activeScope =
this.state.scopeStack.length === 0
? null
: this.state.scopeStack[this.state.scopeStack.length - 1];
// Track the current result in the parent scope.
tensorsToTrackInParent.forEach((tensor) => {
// Only track the tensor if was allocated in the inner scope and is not
// globally kept.
if (!tensor.kept && tensor.scopeId === oldScope.id) {
this.track(tensor);
}
});
}
/**
* Returns gradients of `f` with respect to each of the `xs`. The gradients
* returned are of the same length as `xs`, but some might be null if `f`
* was not a function of that `x`. It also takes optional dy to multiply the
* gradient, which defaults to `1`.
*/
gradients(f, xs, dy, allowNoGradients = false) {
util["assert"](xs.length > 0, () => "gradients() received an empty list of xs.");
if (dy != null && dy.dtype !== "float32") {
throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);
}
const y = this.scopedRun(
() => this.startTape(),
() => this.endTape(),
() => this.tidy("forward", f)
);
util["assert"](
y instanceof tensor["a" /* Tensor */],
() => "The result y returned by f() must be a tensor."
);
// Filter out the nodes that don't connect x => y.
const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);
if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {
throw new Error(
"Cannot compute gradient of y=f(x) with respect to x. Make sure " +
"that the f you passed encloses all operations that lead from x " +
"to y."
);
}
return this.tidy("backward", () => {
const accumulatedGradientMap = {};
accumulatedGradientMap[y.id] = dy == null ? ones(y.shape) : dy;
// Backprop gradients through the filtered nodes.
backpropagateGradients(
accumulatedGradientMap,
filteredTape,
// Pass the tidy function to avoid circular dep with `tape.ts`.
(f) => this.tidy(f)
);
const grads = xs.map((x) => accumulatedGradientMap[x.id]);
if (this.state.gradientDepth === 0) {
// This means that we are not computing higher-order gradients
// and can clean up the tape.
this.state.activeTape.forEach((node) => {
for (const tensor of node.saved) {
tensor.dispose();
}
});
this.state.activeTape = null;
}
return { value: y, grads };
});
}
customGrad(f) {
util["assert"](
util["isFunction"](f),
() => "The f passed in customGrad(f) must be a function."
);
return (...inputs) => {
util["assert"](
inputs.every((t) => t instanceof tensor["a" /* Tensor */]),
() => "The args passed in customGrad(f)(x1, x2,...) must all be " + "tensors"
);
let res;
const inputMap = {};
inputs.forEach((input, i) => {
inputMap[i] = input;
});
return this.runKernelFunc(
(_, save) => {
res = f(...[...inputs, save]);
util["assert"](
res.value instanceof tensor["a" /* Tensor */],
() =>
"The function f passed in customGrad(f) must return an " +
"object where `obj.value` is a tensor"
);
util["assert"](
util["isFunction"](res.gradFunc),
() =>
"The function f passed in customGrad(f) must return an " +
"object where `obj.gradFunc` is a function."
);
return res.value;
},
inputMap,
(dy, saved) => {
const gradRes = res.gradFunc(dy, saved);
const grads = Array.isArray(gradRes) ? gradRes : [gradRes];
util["assert"](
grads.length === inputs.length,
() =>
"The function f passed in customGrad(f) must return an " +
"object where `obj.gradFunc` is a function that returns " +
"the same number of tensors as inputs passed to f(...)."
);
util["assert"](
grads.every((t) => t instanceof tensor["a" /* Tensor */]),
() =>
"The function f passed in customGrad(f) must return an " +
"object where `obj.gradFunc` is a function that returns " +
"a list of only tensors."
);
const gradMap = {};
grads.forEach((grad, i) => {
gradMap[i] = () => grad;
});
return gradMap;
}
);
};
}
readSync(dataId) {
// Route the read to the correct backend.
const info = this.state.tensorInfo.get(dataId);
return info.backend.readSync(dataId);
}
read(dataId) {
// Route the read to the correct backend.
const info = this.state.tensorInfo.get(dataId);
return info.backend.read(dataId);
}
async time(query) {
const start = Object(util["now"])();
const timingInfo = await this.backend.time(query);
timingInfo.wallMs = Object(util["now"])() - start;
return timingInfo;
}
/**
* Tracks a Tensor in the current scope to be automatically cleaned up
* when the current scope ends, and returns the value.
*
* @param result The Tensor to track in the current scope.
*/
track(result) {
if (this.state.activeScope != null) {
result.scopeId = this.state.activeScope.id;
this.state.activeScope.track.push(result);
}
return result;
}
get registeredVariables() {
return this.state.registeredVariables;
}
/**
* Resets the engine state. Removes all backends but does not remove
* registered backend factories.
*/
reset() {
// Make any pending promise obsolete.
this.pendingBackendInitId++;
this.state.dispose();
this.ENV.reset();
this.state = new EngineState();
for (const backendName in this.registry) {
this.disposeRegisteredKernels(backendName);
this.registry[backendName].dispose();
delete this.registry[backendName];
}
this.backendName = null;
this.backendInstance = null;
this.pendingBackendInit = null;
}
}
engine_Engine.nextTensorId = 0;
engine_Engine.nextVariableId = 0;
function ones(shape) {
const values = Object(util["makeOnesTypedArray"])(
Object(util["sizeFromShape"])(shape),
"float32"
);
return ENGINE.makeTensor(values, shape, "float32");
}
function getOrMakeEngine() {
const ns = Object(global_util["b" /* getGlobalNamespace */])();
if (ns._tfengine == null) {
const environment = new dist_environment["b" /* Environment */](ns);
ns._tfengine = new engine_Engine(environment);
}
Object(dist_environment["d" /* setEnvironmentGlobal */])(ns._tfengine.ENV);
// Tell the current tensor interface that the global engine is responsible
// for tracking.
Object(tensor["f" /* setTensorTracker */])(() => ns._tfengine);
return ns._tfengine;
}
const ENGINE = getOrMakeEngine();
//# sourceMappingURL=engine.js.map
/***/
},
/* 6 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return Add;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return AddN;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return Atan2;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function () {
return AvgPool;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function () {
return AvgPoolBackprop;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function () {
return AvgPool3D;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function () {
return AvgPool3DBackprop;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function () {
return BatchMatMul;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function () {
return BatchToSpaceND;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function () {
return BroadcastTo;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function () {
return Complex;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function () {
return Concat;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function () {
return Conv2D;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function () {
return Conv2DBackpropFilter;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function () {
return Conv2DBackpropInput;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function () {
return Conv3D;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function () {
return Conv3DBackpropFilterV2;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function () {
return Conv3DBackpropInputV2;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function () {
return Cumsum;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function () {
return DepthToSpace;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function () {
return DepthwiseConv2dNative;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function () {
return DepthwiseConv2dNativeBackpropFilter;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function () {
return DepthwiseConv2dNativeBackpropInput;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "x", function () {
return Diag;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "y", function () {
return Div;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "z", function () {
return Elu;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A", function () {
return EluGrad;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "B", function () {
return Equal;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "D", function () {
return FloorDiv;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function () {
return Fill;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "F", function () {
return FusedBatchNorm;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "G", function () {
return GatherNd;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "H", function () {
return Greater;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I", function () {
return GreaterEqual;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "J", function () {
return Identity;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "K", function () {
return Imag;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "N", function () {
return Less;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "O", function () {
return LessEqual;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "L", function () {
return LRN;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "M", function () {
return LRNBackprop;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "P", function () {
return Max;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "V", function () {
return Maximum;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Q", function () {
return MaxPool;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "T", function () {
return MaxPoolBackprop;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "R", function () {
return MaxPool3D;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "S", function () {
return MaxPool3DBackprop;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "U", function () {
return MaxPoolWithArgmax;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "W", function () {
return Minimum;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "X", function () {
return Mod;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Y", function () {
return Multiply;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bb", function () {
return NotEqual;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Z", function () {
return NonMaxSuppressionV3;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ab", function () {
return NonMaxSuppressionV5;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cb", function () {
return OneHot;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "db", function () {
return PadV2;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eb", function () {
return Pool;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fb", function () {
return Pow;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gb", function () {
return Prelu;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hb", function () {
return Real;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ib", function () {
return Relu;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "jb", function () {
return Relu6;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "kb", function () {
return SelectV2;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lb", function () {
return Selu;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mb", function () {
return SpaceToBatchND;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "nb", function () {
return SplitV;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pb", function () {
return SquaredDifference;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ob", function () {
return Square;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "qb", function () {
return Sub;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rb", function () {
return Tile;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sb", function () {
return Transpose;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "E", function () {
return FromPixels;
});
const Add = "Add";
const AddN = "AddN";
const Atan2 = "Atan2";
const AvgPool = "AvgPool";
const AvgPoolBackprop = "AvgPoolBackprop";
const AvgPool3D = "AvgPool3D";
const AvgPool3DBackprop = "AvgPool3DBackprop";
const BatchMatMul = "BatchMatMul";
const BatchToSpaceND = "BatchToSpaceND";
const BroadcastTo = "BroadcastTo";
const Complex = "Complex";
const Concat = "Concat";
const Conv2D = "Conv2D";
const Conv2DBackpropFilter = "Conv2DBackpropFilter";
const Conv2DBackpropInput = "Conv2DBackpropInput";
const Conv3D = "Conv3D";
const Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2";
const Conv3DBackpropInputV2 = "Conv3DBackpropInputV2";
const Cumsum = "Cumsum";
const DepthToSpace = "DepthToSpace";
const DepthwiseConv2dNative = "DepthwiseConv2dNative";
const DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter";
const DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput";
const Diag = "Diag";
const Div = "Div";
const Elu = "Elu";
const EluGrad = "EluGrad";
const Equal = "Equal";
const FloorDiv = "FloorDiv";
const Fill = "Fill";
const FusedBatchNorm = "FusedBatchNorm";
const GatherNd = "GatherNd";
const Greater = "Greater";
const GreaterEqual = "GreaterEqual";
const Identity = "Identity";
const Imag = "Imag";
const Less = "Less";
const LessEqual = "LessEqual";
const LRN = "LRN";
const LRNBackprop = "LRNBackprop";
const Max = "Max";
const Maximum = "Maximum";
const MaxPool = "MaxPool";
const MaxPoolBackprop = "MaxPoolBackprop";
const MaxPool3D = "MaxPool3D";
const MaxPool3DBackprop = "MaxPool3DBackprop";
const MaxPoolWithArgmax = "MaxPoolWithArgmax";
const Minimum = "Minimum";
const Mod = "Mod";
const Multiply = "Multiply";
const NotEqual = "NotEqual";
const NonMaxSuppressionV3 = "NonMaxSuppressionV3";
const NonMaxSuppressionV5 = "NonMaxSuppressionV5";
const OneHot = "OneHot";
const PadV2 = "PadV2";
const Pool = "Pool";
const Pow = "Pow";
const Prelu = "Prelu";
const Real = "Real";
const Relu = "Relu";
const Relu6 = "Relu6";
const SelectV2 = "SelectV2";
const Selu = "Selu";
const SpaceToBatchND = "SpaceToBatchND";
const SplitV = "SplitV";
const SquaredDifference = "SquaredDifference";
const Square = "Square";
const Sub = "Sub";
const Tile = "Tile";
const Transpose = "Transpose";
/**
* TensorFlow.js-only kernels
*/
const FromPixels = "FromPixels";
//# sourceMappingURL=kernel_names.js.map
/***/
},
/* 7 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function () {
return /* binding */ tensor_TensorBuffer;
});
__webpack_require__.d(__webpack_exports__, "f", function () {
return /* binding */ setTensorTracker;
});
__webpack_require__.d(__webpack_exports__, "e", function () {
return /* binding */ setOpHandler;
});
__webpack_require__.d(__webpack_exports__, "d", function () {
return /* binding */ setDeprecationWarningFn;
});
__webpack_require__.d(__webpack_exports__, "a", function () {
return /* binding */ tensor_Tensor;
});
__webpack_require__.d(__webpack_exports__, "c", function () {
return /* binding */ tensor_Variable;
});
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/util.js
var util = __webpack_require__(1);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor_format.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Maximum number of values before we decide to show ellipsis.
const FORMAT_LIMIT_NUM_VALS = 20;
// Number of first and last values to show when displaying a, b,...,y, z.
const FORMAT_NUM_FIRST_LAST_VALS = 3;
// Number of significant digits to show.
const FORMAT_NUM_SIG_DIGITS = 7;
function tensorToString(vals, shape, dtype, verbose) {
const strides = Object(util["computeStrides"])(shape);
const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);
const rank = shape.length;
const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);
const lines = ["Tensor"];
if (verbose) {
lines.push(` dtype: ${dtype}`);
lines.push(` rank: ${rank}`);
lines.push(` shape: [${shape}]`);
lines.push(` values:`);
}
lines.push(valsLines.map((l) => " " + l).join("\n"));
return lines.join("\n");
}
function computeMaxSizePerColumn(vals, shape, dtype, strides) {
const n = Object(util["sizeFromShape"])(shape);
const numCols = strides[strides.length - 1];
const padPerCol = new Array(numCols).fill(0);
const rank = shape.length;
const valuesOrTuples = dtype === "complex64" ? createComplexTuples(vals) : vals;
if (rank > 1) {
for (let row = 0; row < n / numCols; row++) {
const offset = row * numCols;
for (let j = 0; j < numCols; j++) {
padPerCol[j] = Math.max(
padPerCol[j],
valToString(valuesOrTuples[offset + j], 0, dtype).length
);
}
}
}
return padPerCol;
}
function valToString(val, pad, dtype) {
let valStr;
if (Array.isArray(val)) {
valStr =
`${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +
`${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;
} else if (Object(util["isString"])(val)) {
valStr = `'${val}'`;
} else if (dtype === "bool") {
valStr = boolNumToString(val);
} else {
valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
}
return Object(util["rightPad"])(valStr, pad);
}
function boolNumToString(v) {
return v === 0 ? "false" : "true";
}
function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast = true) {
const storagePerElement = dtype === "complex64" ? 2 : 1;
const size = shape[0];
const rank = shape.length;
if (rank === 0) {
if (dtype === "complex64") {
const complexTuple = createComplexTuples(vals);
return [valToString(complexTuple[0], 0, dtype)];
}
if (dtype === "bool") {
return [boolNumToString(vals[0])];
}
return [vals[0].toString()];
}
if (rank === 1) {
if (size > FORMAT_LIMIT_NUM_VALS) {
const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;
let firstVals = Array.from(vals.slice(0, firstValsSize));
let lastVals = Array.from(
vals.slice(
(size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement,
size * storagePerElement
)
);
if (dtype === "complex64") {
firstVals = createComplexTuples(firstVals);
lastVals = createComplexTuples(lastVals);
}
return [
"[" +
firstVals.map((x, i) => valToString(x, padPerCol[i], dtype)).join(", ") +
", ..., " +
lastVals
.map((x, i) =>
valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype)
)
.join(", ") +
"]",
];
}
const displayVals = dtype === "complex64" ? createComplexTuples(vals) : Array.from(vals);
return [
"[" + displayVals.map((x, i) => valToString(x, padPerCol[i], dtype)).join(", ") + "]",
];
}
// The array is rank 2 or more.
const subshape = shape.slice(1);
const substrides = strides.slice(1);
const stride = strides[0] * storagePerElement;
const lines = [];
if (size > FORMAT_LIMIT_NUM_VALS) {
for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
const start = i * stride;
const end = start + stride;
lines.push(
...subTensorToString(
vals.slice(start, end),
subshape,
dtype,
substrides,
padPerCol,
false /* isLast */
)
);
}
lines.push("...");
for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
const start = i * stride;
const end = start + stride;
lines.push(
...subTensorToString(
vals.slice(start, end),
subshape,
dtype,
substrides,
padPerCol,
i === size - 1 /* isLast */
)
);
}
} else {
for (let i = 0; i < size; i++) {
const start = i * stride;
const end = start + stride;
lines.push(
...subTensorToString(
vals.slice(start, end),
subshape,
dtype,
substrides,
padPerCol,
i === size - 1 /* isLast */
)
);
}
}
const sep = rank === 2 ? "," : "";
lines[0] = "[" + lines[0] + sep;
for (let i = 1; i < lines.length - 1; i++) {
lines[i] = " " + lines[i] + sep;
}
let newLineSep = ",\n";
for (let i = 2; i < rank; i++) {
newLineSep += "\n";
}
lines[lines.length - 1] = " " + lines[lines.length - 1] + "]" + (isLast ? "" : newLineSep);
return lines;
}
function createComplexTuples(vals) {
const complexTuples = [];
for (let i = 0; i < vals.length; i += 2) {
complexTuples.push([vals[i], vals[i + 1]]);
}
return complexTuples;
}
//# sourceMappingURL=tensor_format.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* A mutable object, similar to `tf.Tensor`, that allows users to set values
* at locations before converting to an immutable `tf.Tensor`.
*
* See `tf.buffer` for creating a tensor buffer.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
class tensor_TensorBuffer {
constructor(shape, dtype, values) {
this.dtype = dtype;
this.shape = shape.slice();
this.size = util["sizeFromShape"](shape);
if (values != null) {
const n = values.length;
util["assert"](
n === this.size,
() =>
`Length of values '${n}' does not match the size ` +
`inferred by the shape '${this.size}'.`
);
}
if (dtype === "complex64") {
throw new Error(
`complex64 dtype TensorBuffers are not supported. Please create ` +
`a TensorBuffer for the real and imaginary parts separately and ` +
`call tf.complex(real, imag).`
);
}
this.values = values || util["getArrayFromDType"](dtype, this.size);
this.strides = Object(util["computeStrides"])(shape);
}
/**
* Sets a value in the buffer at a given location.
*
* @param value The value to set.
* @param locs The location indices.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
set(value, ...locs) {
if (locs.length === 0) {
locs = [0];
}
util["assert"](
locs.length === this.rank,
() =>
`The number of provided coordinates (${locs.length}) must ` +
`match the rank (${this.rank})`
);
const index = this.locToIndex(locs);
this.values[index] = value;
}
/**
* Returns the value in the buffer at the provided location.
*
* @param locs The location indices.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
get(...locs) {
if (locs.length === 0) {
locs = [0];
}
let i = 0;
for (const loc of locs) {
if (loc < 0 || loc >= this.shape[i]) {
const msg =
`Requested out of range element at ${locs}. ` + ` Buffer shape=${this.shape}`;
throw new Error(msg);
}
i++;
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
return this.values[index];
}
locToIndex(locs) {
if (this.rank === 0) {
return 0;
} else if (this.rank === 1) {
return locs[0];
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
return index;
}
indexToLoc(index) {
if (this.rank === 0) {
return [];
} else if (this.rank === 1) {
return [index];
}
const locs = new Array(this.shape.length);
for (let i = 0; i < locs.length - 1; ++i) {
locs[i] = Math.floor(index / this.strides[i]);
index -= locs[i] * this.strides[i];
}
locs[locs.length - 1] = index;
return locs;
}
get rank() {
return this.shape.length;
}
/**
* Creates an immutable `tf.Tensor` object from the buffer.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
toTensor() {
return trackerFn().makeTensor(this.values, this.shape, this.dtype);
}
}
// For tracking tensor creation and disposal.
let trackerFn = null;
// Used by chaining methods to call into ops.
let opHandler = null;
// Used to warn about deprecated methods.
let deprecationWarningFn = null;
// This here so that we can use this method on dev branches and keep the
// functionality at master.
// tslint:disable-next-line:no-unused-expression
[deprecationWarningFn];
/**
* An external consumer can register itself as the tensor tracker. This way
* the Tensor class can notify the tracker for every tensor created and
* disposed.
*/
function setTensorTracker(fn) {
trackerFn = fn;
}
/**
* An external consumer can register itself as the op handler. This way the
* Tensor class can have chaining methods that call into ops via the op
* handler.
*/
function setOpHandler(handler) {
opHandler = handler;
}
/**
* Sets the deprecation warning function to be used by this file. This way the
* Tensor class can be a leaf but still use the environment.
*/
function setDeprecationWarningFn(fn) {
deprecationWarningFn = fn;
}
/**
* A `tf.Tensor` object represents an immutable, multidimensional array of
* numbers that has a shape and a data type.
*
* See `tf.tensor` for details on how to create a `tf.Tensor`.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
class tensor_Tensor {
constructor(shape, dtype, dataId, id) {
/** Whether this tensor has been globally kept. */
this.kept = false;
this.isDisposedInternal = false;
this.shape = shape.slice();
this.dtype = dtype || "float32";
this.size = util["sizeFromShape"](shape);
this.strides = Object(util["computeStrides"])(shape);
this.dataId = dataId;
this.id = id;
this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
}
/** Flatten a Tensor to a 1D array. */
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
flatten() {
this.throwIfDisposed();
return this.as1D();
}
/** Converts a size-1 `tf.Tensor` to a `tf.Scalar`. */
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
asScalar() {
this.throwIfDisposed();
util["assert"](this.size === 1, () => "The array must have only 1 element.");
return this.reshape([]);
}
/** Converts a `tf.Tensor` to a `tf.Tensor1D`. */
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
as1D() {
this.throwIfDisposed();
return this.reshape([this.size]);
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor2D`.
*
* @param rows Number of rows in `tf.Tensor2D`.
* @param columns Number of columns in `tf.Tensor2D`.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
as2D(rows, columns) {
this.throwIfDisposed();
return this.reshape([rows, columns]);
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor3D`.
*
* @param rows Number of rows in `tf.Tensor3D`.
* @param columns Number of columns in `tf.Tensor3D`.
* @param depth Depth of `tf.Tensor3D`.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
as3D(rows, columns, depth) {
this.throwIfDisposed();
return this.reshape([rows, columns, depth]);
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor4D`.
*
* @param rows Number of rows in `tf.Tensor4D`.
* @param columns Number of columns in `tf.Tensor4D`.
* @param depth Depth of `tf.Tensor4D`.
* @param depth2 4th dimension of `tf.Tensor4D`.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
as4D(rows, columns, depth, depth2) {
this.throwIfDisposed();
return this.reshape([rows, columns, depth, depth2]);
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor5D`.
*
* @param rows Number of rows in `tf.Tensor5D`.
* @param columns Number of columns in `tf.Tensor5D`.
* @param depth Depth of `tf.Tensor5D`.
* @param depth2 4th dimension of `tf.Tensor5D`.
* @param depth3 5th dimension of 'tf.Tensor5D'
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
as5D(rows, columns, depth, depth2, depth3) {
this.throwIfDisposed();
return this.reshape([rows, columns, depth, depth2, depth3]);
}
/**
* Casts a `tf.Tensor` to a specified dtype.
*
* @param dtype Data-type to cast the tensor to.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
asType(dtype) {
this.throwIfDisposed();
return opHandler.cast(this, dtype);
}
get rank() {
return this.shape.length;
}
/**
* Returns a promise of `tf.TensorBuffer` that holds the underlying data.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
async buffer() {
const vals = await this.data();
return opHandler.buffer(this.shape, this.dtype, vals);
}
/** Returns a `tf.TensorBuffer` that holds the underlying data. */
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
bufferSync() {
return opHandler.buffer(this.shape, this.dtype, this.dataSync());
}
/**
* Returns the tensor data as a nested array. The transfer of data is done
* asynchronously.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
async array() {
const vals = await this.data();
return Object(util["toNestedArray"])(this.shape, vals);
}
/**
* Returns the tensor data as a nested array. The transfer of data is done
* synchronously.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
arraySync() {
return Object(util["toNestedArray"])(this.shape, this.dataSync());
}
/**
* Asynchronously downloads the values from the `tf.Tensor`. Returns a
* promise of `TypedArray` that resolves when the computation has finished.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
async data() {
this.throwIfDisposed();
const data = trackerFn().read(this.dataId);
if (this.dtype === "string") {
const bytes = await data;
try {
return bytes.map((b) => util["decodeString"](b));
} catch (_a) {
throw new Error(
"Failed to decode the string bytes into utf-8. " +
"To get the original bytes, call tensor.bytes()."
);
}
}
return data;
}
/**
* Synchronously downloads the values from the `tf.Tensor`. This blocks the
* UI thread until the values are ready, which can cause performance issues.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
dataSync() {
this.throwIfDisposed();
const data = trackerFn().readSync(this.dataId);
if (this.dtype === "string") {
try {
return data.map((b) => util["decodeString"](b));
} catch (_a) {
throw new Error(
"Failed to decode the string bytes into utf-8. " +
"To get the original bytes, call tensor.bytes()."
);
}
}
return data;
}
/** Returns the underlying bytes of the tensor's data. */
async bytes() {
this.throwIfDisposed();
const data = await trackerFn().read(this.dataId);
if (this.dtype === "string") {
return data;
} else {
return new Uint8Array(data.buffer);
}
}
/**
* Disposes `tf.Tensor` from memory.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
dispose() {
if (this.isDisposed) {
return;
}
trackerFn().disposeTensor(this);
this.isDisposedInternal = true;
}
get isDisposed() {
return this.isDisposedInternal;
}
throwIfDisposed() {
if (this.isDisposed) {
throw new Error(`Tensor is disposed.`);
}
}
/** Casts the array to type `float32` */
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
toFloat() {
return this.asType("float32");
}
/** Casts the array to type `int32` */
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
toInt() {
return this.asType("int32");
}
/** Casts the array to type `bool` */
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
toBool() {
return this.asType("bool");
}
/**
* Prints the `tf.Tensor`. See `tf.print` for details.
*
* @param verbose Whether to print verbose information about the tensor,
* including dtype and size.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
print(verbose = false) {
return opHandler.print(this, verbose);
}
/**
* Reshapes the tensor into the provided shape.
* See `tf.reshape` for more details.
*
* @param newShape An array of integers defining the output tensor shape.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
reshape(newShape) {
this.throwIfDisposed();
return opHandler.reshape(this, newShape);
}
/**
* Reshapes the tensor into the shape of the provided tensor.
*
* @param x The tensor of required shape.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
reshapeAs(x) {
this.throwIfDisposed();
return this.reshape(x.shape);
}
/**
* Returns a `tf.Tensor` that has expanded rank, by inserting a dimension
* into the tensor's shape. See `tf.expandDims` for details.
*
* @param axis The dimension index at which to insert shape of 1. Defaults to
* 0 (the first dimension).
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
expandDims(axis = 0) {
return opHandler.expandDims(this, axis);
}
/**
* Returns a `tf.Tensor` with dimensions of size 1 removed from the shape.
* See `tf.squeeze` for more details.
*
* @param axis A list of numbers. If specified, only squeezes the
* dimensions listed. The dimension index starts at 0. It is an error to
* squeeze a dimension that is not 1.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
squeeze(axis) {
this.throwIfDisposed();
return opHandler.squeeze(this, axis);
}
/** Returns a copy of the tensor. See `tf.clone` for details. */
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
clone() {
this.throwIfDisposed();
return opHandler.clone(this);
}
/**
* Returns a human-readable description of the tensor. Useful for logging.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
toString(verbose = false) {
const vals = this.dataSync();
return tensorToString(vals, this.shape, this.dtype, verbose);
}
// Below is chain API that is not exposed to docs to avoid repetition. To
// expose a method, move it above this comment and add @doc and jsdoc.
gather(indices, axis = 0) {
this.throwIfDisposed();
return opHandler.gather(this, indices, axis);
}
norm(ord = "euclidean", axis = null, keepDims = false) {
this.throwIfDisposed();
return opHandler.norm(this, ord, axis, keepDims);
}
slice(begin, size) {
this.throwIfDisposed();
return opHandler.slice(this, begin, size);
}
reverse(axis) {
this.throwIfDisposed();
return opHandler.reverse(this, axis);
}
stack(x, axis = 0) {
return opHandler.stack([this, x], axis);
}
unstack(axis = 0) {
return opHandler.unstack(this, axis);
}
// Reduction ops.
all(axis = null, keepDims = false) {
this.throwIfDisposed();
return opHandler.all(this, axis, keepDims);
}
any(axis = null, keepDims = false) {
this.throwIfDisposed();
return opHandler.any(this, axis, keepDims);
}
logSumExp(axis = null, keepDims = false) {
this.throwIfDisposed();
return opHandler.logSumExp(this, axis, keepDims);
}
sum(axis = null, keepDims = false) {
this.throwIfDisposed();
return opHandler.sum(this, axis, keepDims);
}
prod(axis = null, keepDims = false) {
this.throwIfDisposed();
return opHandler.prod(this, axis, keepDims);
}
mean(axis = null, keepDims = false) {
this.throwIfDisposed();
return opHandler.mean(this, axis, keepDims);
}
min(axis = null, keepDims = false) {
this.throwIfDisposed();
return opHandler.min(this, axis, keepDims);
}
argMin(axis = null) {
this.throwIfDisposed();
return opHandler.argMin(this, axis);
}
argMax(axis = null) {
this.throwIfDisposed();
return opHandler.argMax(this, axis);
}
// Transformations
cast(dtype) {
this.throwIfDisposed();
return opHandler.cast(this, dtype);
}
// Binary ops.
/**
* @deprecated strict variants of ops have been deprecated
*/
addStrict(x) {
this.throwIfDisposed();
return opHandler.addStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
subStrict(x) {
this.throwIfDisposed();
return opHandler.subStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
powStrict(exp) {
this.throwIfDisposed();
return opHandler.powStrict(this, exp);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
mulStrict(x) {
this.throwIfDisposed();
return opHandler.mulStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
divStrict(x) {
this.throwIfDisposed();
return opHandler.divStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
minimumStrict(x) {
this.throwIfDisposed();
return opHandler.minimumStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
maximumStrict(x) {
this.throwIfDisposed();
return opHandler.maximumStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
modStrict(x) {
this.throwIfDisposed();
return opHandler.modStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
squaredDifferenceStrict(x) {
this.throwIfDisposed();
return opHandler.squaredDifferenceStrict(this, x);
}
// Compare ops.
/**
* @deprecated strict variants of ops have been deprecated
*/
notEqualStrict(x) {
this.throwIfDisposed();
return opHandler.notEqualStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
lessStrict(x) {
this.throwIfDisposed();
return opHandler.lessStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
equalStrict(x) {
this.throwIfDisposed();
return opHandler.equalStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
lessEqualStrict(x) {
this.throwIfDisposed();
return opHandler.lessEqualStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
greaterStrict(x) {
this.throwIfDisposed();
return opHandler.greaterStrict(this, x);
}
/**
* @deprecated strict variants of ops have been deprecated
*/
greaterEqualStrict(x) {
this.throwIfDisposed();
return opHandler.greaterEqualStrict(this, x);
}
// Compare ops.
logicalAnd(x) {
this.throwIfDisposed();
return opHandler.logicalAnd(this, x);
}
logicalOr(x) {
this.throwIfDisposed();
return opHandler.logicalOr(this, x);
}
logicalNot() {
this.throwIfDisposed();
return opHandler.logicalNot(this);
}
logicalXor(x) {
this.throwIfDisposed();
return opHandler.logicalXor(this, x);
}
where(condition, x) {
this.throwIfDisposed();
return opHandler.where(condition, this, x);
}
// Unary ops.
neg() {
this.throwIfDisposed();
return opHandler.neg(this);
}
ceil() {
this.throwIfDisposed();
return opHandler.ceil(this);
}
floor() {
this.throwIfDisposed();
return opHandler.floor(this);
}
sign() {
this.throwIfDisposed();
return opHandler.sign(this);
}
isNaN() {
this.throwIfDisposed();
return opHandler.isNaN(this);
}
isInf() {
this.throwIfDisposed();
return opHandler.isInf(this);
}
isFinite() {
this.throwIfDisposed();
return opHandler.isFinite(this);
}
exp() {
this.throwIfDisposed();
return opHandler.exp(this);
}
expm1() {
this.throwIfDisposed();
return opHandler.expm1(this);
}
log() {
this.throwIfDisposed();
return opHandler.log(this);
}
log1p() {
this.throwIfDisposed();
return opHandler.log1p(this);
}
sqrt() {
this.throwIfDisposed();
return opHandler.sqrt(this);
}
rsqrt() {
this.throwIfDisposed();
return opHandler.rsqrt(this);
}
square() {
this.throwIfDisposed();
return opHandler.square(this);
}
reciprocal() {
this.throwIfDisposed();
return opHandler.reciprocal(this);
}
abs() {
this.throwIfDisposed();
return opHandler.abs(this);
}
clipByValue(min, max) {
this.throwIfDisposed();
return opHandler.clipByValue(this, min, max);
}
sigmoid() {
this.throwIfDisposed();
return opHandler.sigmoid(this);
}
logSigmoid() {
this.throwIfDisposed();
return opHandler.logSigmoid(this);
}
softplus() {
this.throwIfDisposed();
return opHandler.softplus(this);
}
zerosLike() {
this.throwIfDisposed();
return opHandler.zerosLike(this);
}
onesLike() {
this.throwIfDisposed();
return opHandler.onesLike(this);
}
sin() {
this.throwIfDisposed();
return opHandler.sin(this);
}
cos() {
this.throwIfDisposed();
return opHandler.cos(this);
}
tan() {
this.throwIfDisposed();
return opHandler.tan(this);
}
asin() {
this.throwIfDisposed();
return opHandler.asin(this);
}
acos() {
this.throwIfDisposed();
return opHandler.acos(this);
}
atan() {
this.throwIfDisposed();
return opHandler.atan(this);
}
sinh() {
this.throwIfDisposed();
return opHandler.sinh(this);
}
cosh() {
this.throwIfDisposed();
return opHandler.cosh(this);
}
tanh() {
this.throwIfDisposed();
return opHandler.tanh(this);
}
asinh() {
this.throwIfDisposed();
return opHandler.asinh(this);
}
acosh() {
this.throwIfDisposed();
return opHandler.acosh(this);
}
atanh() {
this.throwIfDisposed();
return opHandler.atanh(this);
}
erf() {
this.throwIfDisposed();
return opHandler.erf(this);
}
round() {
this.throwIfDisposed();
return opHandler.round(this);
}
step(alpha = 0.0) {
this.throwIfDisposed();
return opHandler.step(this, alpha);
}
softmax(dim = -1) {
this.throwIfDisposed();
return opHandler.softmax(this, dim);
}
logSoftmax(axis = -1) {
this.throwIfDisposed();
return opHandler.logSoftmax(this, axis);
}
// Image ops.
resizeBilinear(newShape2D, alignCorners = false) {
this.throwIfDisposed();
return opHandler.image.resizeBilinear(this, newShape2D, alignCorners);
}
resizeNearestNeighbor(newShape2D, alignCorners = false) {
this.throwIfDisposed();
return opHandler.image.resizeNearestNeighbor(this, newShape2D, alignCorners);
}
// Pooling.
variable(trainable = true, name, dtype) {
this.throwIfDisposed();
return trackerFn().makeVariable(this, trainable, name, dtype);
}
unsortedSegmentSum(segmentIds, numSegments) {
this.throwIfDisposed();
return opHandler.unsortedSegmentSum(this, segmentIds, numSegments);
}
topk(k = 1, sorted = true) {
this.throwIfDisposed();
return opHandler.topk(this, k, sorted);
}
stridedSlice(
begin,
end,
strides,
beginMask = 0,
endMask = 0,
ellipsisMask = 0,
newAxisMask = 0,
shrinkAxisMask = 0
) {
this.throwIfDisposed();
return opHandler.stridedSlice(
this,
begin,
end,
strides,
beginMask,
endMask,
ellipsisMask,
newAxisMask,
shrinkAxisMask
);
}
fft() {
this.throwIfDisposed();
return opHandler.spectral.fft(this);
}
ifft() {
this.throwIfDisposed();
return opHandler.spectral.ifft(this);
}
rfft() {
this.throwIfDisposed();
return opHandler.spectral.rfft(this);
}
irfft() {
this.throwIfDisposed();
return opHandler.spectral.irfft(this);
}
}
Object.defineProperty(tensor_Tensor, Symbol.hasInstance, {
value: (instance) => {
return (
!!instance &&
instance.dataId != null &&
instance.shape != null &&
instance.dtype != null
);
},
});
/**
* A mutable `tf.Tensor`, useful for persisting state, e.g. for training.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
class tensor_Variable extends tensor_Tensor {
constructor(initialValue, trainable, name, tensorId) {
super(initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);
this.trainable = trainable;
this.name = name;
}
/**
* Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have
* the same shape and dtype as the old `tf.Tensor`.
*
* @param newValue New tensor to be assigned to this variable.
*/
/** @doc {heading: 'Tensors', subheading: 'Classes'} */
assign(newValue) {
if (newValue.dtype !== this.dtype) {
throw new Error(
`dtype of the new value (${newValue.dtype}) and ` +
`previous value (${this.dtype}) must match`
);
}
if (!util["arraysEqual"](newValue.shape, this.shape)) {
throw new Error(
`shape of the new value (${newValue.shape}) and ` +
`previous value (${this.shape}) must match`
);
}
trackerFn().disposeTensor(this);
this.dataId = newValue.dataId;
trackerFn().incRef(this, null /* backend */);
}
dispose() {
trackerFn().disposeVariable(this);
this.isDisposedInternal = true;
}
}
Object.defineProperty(tensor_Variable, Symbol.hasInstance, {
value: (instance) => {
return (
instance instanceof tensor_Tensor &&
instance.assign != null &&
instance.assign instanceof Function
);
},
});
//# sourceMappingURL=tensor.js.map
/***/
},
/* 8 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return linspace;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return ones;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function () {
return range;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function () {
return scalar;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function () {
return tensor;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function () {
return tensor1d;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function () {
return tensor2d;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function () {
return tensor3d;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function () {
return tensor4d;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function () {
return tensor5d;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function () {
return tensor6d;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function () {
return variable;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function () {
return zeros;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return onesLike;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function () {
return zerosLike;
});
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _environment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(3);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var _complex__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(18);
/* harmony import */ var _imag__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(25);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4);
/* harmony import */ var _real__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(22);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with the provided values, shape and dtype.
*
* ```js
* // Pass an array of values to create a vector.
* tf.tensor([1, 2, 3, 4]).print();
* ```
*
* ```js
* // Pass a nested array of values to make a matrix or a higher
* // dimensional tensor.
* tf.tensor([[1, 2], [3, 4]]).print();
* ```
*
* ```js
* // Pass a flat array and specify a shape yourself.
* tf.tensor([1, 2, 3, 4], [2, 2]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`. If the values are strings,
* they will be encoded as utf-8 and kept as `Uint8Array[]`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function tensor(values, shape, dtype) {
const inferredShape = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* inferShape */ "c"]
)(values, dtype);
return makeTensor(values, shape, inferredShape, dtype);
}
/** This is shared code across all tensor creation methods. */
function makeTensor(values, shape, inferredShape, dtype) {
if (dtype == null) {
dtype = Object(_util__WEBPACK_IMPORTED_MODULE_3__["inferDtype"])(values);
}
if (dtype === "complex64") {
throw new Error(
`Cannot construct a complex64 tensor directly. ` + `Please use tf.complex(real, imag).`
);
}
if (
!Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(values) &&
!Array.isArray(values) &&
typeof values !== "number" &&
typeof values !== "boolean" &&
typeof values !== "string"
) {
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 (shape != null) {
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assertNonNegativeIntegerDimensions"])(shape);
const providedSize = Object(_util__WEBPACK_IMPORTED_MODULE_3__["sizeFromShape"])(shape);
const inferredSize = Object(_util__WEBPACK_IMPORTED_MODULE_3__["sizeFromShape"])(
inferredShape
);
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assert"])(
providedSize === inferredSize,
() =>
`Based on the provided shape, [${shape}], the tensor should have ` +
`${providedSize} values but has ${inferredSize}`
);
for (let i = 0; i < inferredShape.length; ++i) {
const inferred = inferredShape[i];
const flatDimsDontMatch =
i === inferredShape.length - 1
? inferred !==
Object(_util__WEBPACK_IMPORTED_MODULE_3__["sizeFromShape"])(shape.slice(i))
: true;
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assert"])(
inferredShape[i] === shape[i] || !flatDimsDontMatch,
() =>
`Error creating a new Tensor. Inferred shape ` +
`(${inferredShape}) does not match the provided ` +
`shape (${shape}). `
);
}
}
if (
!Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(values) &&
!Array.isArray(values)
) {
values = [values];
}
shape = shape || inferredShape;
values =
dtype !== "string"
? Object(_util__WEBPACK_IMPORTED_MODULE_3__["toTypedArray"])(
values,
dtype,
Object(_environment__WEBPACK_IMPORTED_MODULE_1__[/* env */ "c"])().getBool("DEBUG")
)
: Object(_util__WEBPACK_IMPORTED_MODULE_3__["flatten"])(values, [], true);
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].makeTensor(
values,
shape,
dtype
);
}
/**
* Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.scalar` as it makes the code more readable.
*
* ```js
* tf.scalar(3.14).print();
* ```
*
* @param value The value of the scalar.
* @param dtype The data type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function scalar(value, dtype) {
if (
((Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(value) &&
dtype !== "string") ||
Array.isArray(value)) &&
dtype !== "complex64"
) {
throw new Error(
"Error creating a new Scalar: value must be a primitive " + "(number|boolean|string)"
);
}
if (
dtype === "string" &&
Object(_util__WEBPACK_IMPORTED_MODULE_3__["isTypedArray"])(value) &&
!(value instanceof Uint8Array)
) {
throw new Error(
"When making a scalar from encoded string, " + "the value must be `Uint8Array`."
);
}
const shape = [];
const inferredShape = [];
return makeTensor(value, shape, inferredShape, dtype);
}
/**
* Creates rank-1 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor1d` as it makes the code more readable.
*
* ```js
* tf.tensor1d([1, 2, 3]).print();
* ```
*
* @param values The values of the tensor. Can be array of numbers,
* or a `TypedArray`.
* @param dtype The data type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function tensor1d(values, dtype) {
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assertNonNull"])(values);
const inferredShape = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* inferShape */ "c"]
)(values, dtype);
if (inferredShape.length !== 1) {
throw new Error("tensor1d() requires values to be a flat/TypedArray");
}
const shape = null;
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* Creates rank-2 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor2d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor2d([[1, 2], [3, 4]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor2d([1, 2, 3, 4], [2, 2]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. If not provided, it is inferred from
* `values`.
* @param dtype The data type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function tensor2d(values, shape, dtype) {
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assertNonNull"])(values);
if (shape != null && shape.length !== 2) {
throw new Error("tensor2d() requires shape to have two numbers");
}
const inferredShape = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* inferShape */ "c"]
)(values, dtype);
if (inferredShape.length !== 2 && inferredShape.length !== 1) {
throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");
}
if (inferredShape.length === 1 && shape == null) {
throw new Error(
"tensor2d() requires shape to be provided when `values` " + "are a flat/TypedArray"
);
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor3d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor3d([[[1], [2]], [[3], [4]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. If not provided, it is inferred from
* `values`.
* @param dtype The data type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function tensor3d(values, shape, dtype) {
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assertNonNull"])(values);
if (shape != null && shape.length !== 3) {
throw new Error("tensor3d() requires shape to have three numbers");
}
const inferredShape = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* inferShape */ "c"]
)(values, dtype);
if (inferredShape.length !== 3 && inferredShape.length !== 1) {
throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");
}
if (inferredShape.length === 1 && shape == null) {
throw new Error(
"tensor3d() requires shape to be provided when `values` " + "are a flat array"
);
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* Creates rank-4 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor4d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor4d([[[[1], [2]], [[3], [4]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function tensor4d(values, shape, dtype) {
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assertNonNull"])(values);
if (shape != null && shape.length !== 4) {
throw new Error("tensor4d() requires shape to have four numbers");
}
const inferredShape = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* inferShape */ "c"]
)(values, dtype);
if (inferredShape.length !== 4 && inferredShape.length !== 1) {
throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");
}
if (inferredShape.length === 1 && shape == null) {
throw new Error(
"tensor4d() requires shape to be provided when `values` " + "are a flat array"
);
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* Creates rank-5 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor5d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor5d([[[[[1], [2]], [[3], [4]]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function tensor5d(values, shape, dtype) {
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assertNonNull"])(values);
if (shape != null && shape.length !== 5) {
throw new Error("tensor5d() requires shape to have five numbers");
}
const inferredShape = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* inferShape */ "c"]
)(values, dtype);
if (inferredShape.length !== 5 && inferredShape.length !== 1) {
throw new Error(
"tensor5d() requires values to be " + "number[][][][][] or flat/TypedArray"
);
}
if (inferredShape.length === 1 && shape == null) {
throw new Error(
"tensor5d() requires shape to be provided when `values` " + "are a flat array"
);
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* Creates rank-6 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor6d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor6d([[[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor6d([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 2, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function tensor6d(values, shape, dtype) {
Object(_util__WEBPACK_IMPORTED_MODULE_3__["assertNonNull"])(values);
if (shape != null && shape.length !== 6) {
throw new Error("tensor6d() requires shape to have six numbers");
}
const inferredShape = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* inferShape */ "c"]
)(values, dtype);
if (inferredShape.length !== 6 && inferredShape.length !== 1) {
throw new Error(
"tensor6d() requires values to be number[][][][][][] or " + "flat/TypedArray"
);
}
if (inferredShape.length === 1 && shape == null) {
throw new Error(
"tensor6d() requires shape to be provided when `values` " + "are a flat array"
);
}
shape = shape || inferredShape;
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* Creates a new variable with the provided initial value.
* ```js
* const x = tf.variable(tf.tensor([1, 2, 3]));
* x.assign(tf.tensor([4, 5, 6]));
*
* x.print();
* ```
*
* @param initialValue Initial value for the tensor.
* @param trainable If true, optimizers are allowed to update it.
* @param name Name of the variable. Defaults to a unique id.
* @param dtype If set, initialValue will be converted to the given type.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function variable(initialValue, trainable = true, name, dtype) {
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].makeVariable(
initialValue,
trainable,
name,
dtype
);
}
/**
* Creates a `tf.Tensor` with all elements set to 1.
*
* ```js
* tf.ones([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The type of an element in the resulting tensor. Defaults to
* 'float'.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function ones(shape, dtype = "float32") {
if (dtype === "complex64") {
const real = ones(shape, "float32");
const imag = zeros(shape, "float32");
return Object(_complex__WEBPACK_IMPORTED_MODULE_4__[/* complex */ "a"])(real, imag);
}
const values = Object(_util__WEBPACK_IMPORTED_MODULE_3__["makeOnesTypedArray"])(
Object(_util__WEBPACK_IMPORTED_MODULE_3__["sizeFromShape"])(shape),
dtype
);
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].makeTensor(
values,
shape,
dtype
);
}
/**
* Creates a `tf.Tensor` with all elements set to 0.
*
* ```js
* tf.zeros([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The type of an element in the resulting tensor. Can
* be 'float32', 'int32' or 'bool'. Defaults to 'float'.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function zeros(shape, dtype = "float32") {
if (dtype === "complex64") {
const real = zeros(shape, "float32");
const imag = zeros(shape, "float32");
return Object(_complex__WEBPACK_IMPORTED_MODULE_4__[/* complex */ "a"])(real, imag);
}
const values = Object(_util__WEBPACK_IMPORTED_MODULE_3__["makeZerosTypedArray"])(
Object(_util__WEBPACK_IMPORTED_MODULE_3__["sizeFromShape"])(shape),
dtype
);
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].makeTensor(
values,
shape,
dtype
);
}
/**
* Creates a `tf.Tensor` with all elements set to 1 with the same shape as the
* given tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
* tf.onesLike(x).print();
* ```
* @param x A tensor.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function onesLike_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(
x,
"x",
"onesLike"
);
if ($x.dtype === "complex64") {
const r = onesLike(Object(_real__WEBPACK_IMPORTED_MODULE_7__[/* real */ "a"])($x));
const i = zerosLike(Object(_imag__WEBPACK_IMPORTED_MODULE_5__[/* imag */ "a"])($x));
return Object(_complex__WEBPACK_IMPORTED_MODULE_4__[/* complex */ "a"])(r, i);
}
const der = (dy, saved) => ({ x: () => zerosLike(dy) });
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernelFunc(
(backend) => backend.onesLike($x),
{ x: $x },
der,
"OnesLike"
);
}
/**
* Creates a `tf.Tensor` with all elements set to 0 with the same shape as the
* given tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
* tf.zerosLike(x).print();
* ```
*
* @param x The tensor of required shape.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function zerosLike_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(
x,
"x",
"zerosLike"
);
const der = (dy, saved) => ({ x: () => zerosLike(dy) });
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernelFunc(
(backend) => backend.zerosLike($x),
{ x: $x },
der,
"ZerosLike"
);
}
/**
* Return an evenly spaced sequence of numbers over the given interval.
*
* ```js
* tf.linspace(0, 9, 10).print();
* ```
* @param start The start value of the sequence.
* @param stop The end value of the sequence.
* @param num The number of values to generate.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function linspace(start, stop, num) {
if (num <= 0) {
throw new Error("The number of values should be positive.");
}
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernelFunc(
(backend) => backend.linspace(start, stop, num),
{}
);
}
/**
* Creates a new `tf.Tensor1D` filled with the numbers in the range provided.
*
* The tensor is a is half-open interval meaning it includes start, but
* excludes stop. Decrementing ranges and negative step values are also
* supported.
*
* ```js
* tf.range(0, 9, 2).print();
* ```
*
* @param start An integer start value
* @param stop An integer stop value
* @param step An integer increment (will default to 1 or -1)
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function range(start, stop, step = 1, dtype = "float32") {
if (step === 0) {
throw new Error("Cannot have a step of zero");
}
const sameStartStop = start === stop;
const increasingRangeNegativeStep = start < stop && step < 0;
const decreasingRangePositiveStep = stop < start && step > 1;
if (sameStartStop || increasingRangeNegativeStep || decreasingRangePositiveStep) {
return zeros([0], dtype);
}
const numElements = Math.abs(Math.ceil((stop - start) / step));
const values = Object(_util__WEBPACK_IMPORTED_MODULE_3__["makeZerosTypedArray"])(
numElements,
dtype
);
if (stop < start && step === 1) {
// Auto adjust the step's sign if it hasn't been set
// (or was set to 1)
step = -1;
}
values[0] = start;
for (let i = 1; i < values.length; i++) {
values[i] = values[i - 1] + step;
}
return tensor1d(values, dtype);
}
const onesLike = Object(_operation__WEBPACK_IMPORTED_MODULE_6__[/* op */ "a"])({ onesLike_ });
const zerosLike = Object(_operation__WEBPACK_IMPORTED_MODULE_6__[/* op */ "a"])({
zerosLike_,
});
//# sourceMappingURL=tensor_ops.js.map
/***/
},
/* 9 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return assertNotComplex;
});
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(0);
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function assertNotComplex(tensor, opName) {
if (!Array.isArray(tensor)) {
tensor = [tensor];
}
tensor.forEach((t) => {
if (t != null) {
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(
t.dtype !== "complex64",
() => `${opName} does not support complex64 tensors in the CPU backend.`
);
}
});
}
//# sourceMappingURL=cpu_util.js.map
/***/
},
/* 10 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return Environment;
});
/* unused harmony export getQueryParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return env;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return ENV;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function () {
return setEnvironmentGlobal;
});
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.
const TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags";
/**
* The environment contains evaluated flags as well as the registered platform.
* This is always used as a global singleton and can be retrieved with
* `tf.env()`.
*/
/** @doc {heading: 'Environment'} */
class Environment {
// tslint:disable-next-line: no-any
constructor(global) {
this.global = global;
this.flags = {};
this.flagRegistry = {};
this.urlFlags = {};
this.populateURLFlags();
}
setPlatform(platformName, platform) {
if (this.platform != null) {
console.warn(
`Platform ${this.platformName} has already been set. ` +
`Overwriting the platform with ${platform}.`
);
}
this.platformName = platformName;
this.platform = platform;
}
registerFlag(flagName, evaluationFn, setHook) {
this.flagRegistry[flagName] = { evaluationFn, setHook };
// Override the flag value from the URL. This has to happen here because the
// environment is initialized before flags get registered.
if (this.urlFlags[flagName] != null) {
const flagValue = this.urlFlags[flagName];
console.warn(`Setting feature override from URL ${flagName}: ${flagValue}.`);
this.set(flagName, flagValue);
}
}
async getAsync(flagName) {
if (flagName in this.flags) {
return this.flags[flagName];
}
this.flags[flagName] = await this.evaluateFlag(flagName);
return this.flags[flagName];
}
get(flagName) {
if (flagName in this.flags) {
return this.flags[flagName];
}
const flagValue = this.evaluateFlag(flagName);
if (flagValue instanceof Promise) {
throw new Error(
`Flag ${flagName} cannot be synchronously evaluated. ` +
`Please use getAsync() instead.`
);
}
this.flags[flagName] = flagValue;
return this.flags[flagName];
}
getNumber(flagName) {
return this.get(flagName);
}
getBool(flagName) {
return this.get(flagName);
}
getFlags() {
return this.flags;
}
// For backwards compatibility.
get features() {
return this.flags;
}
set(flagName, value) {
if (this.flagRegistry[flagName] == null) {
throw new Error(`Cannot set flag ${flagName} as it has not been registered.`);
}
this.flags[flagName] = value;
if (this.flagRegistry[flagName].setHook != null) {
this.flagRegistry[flagName].setHook(value);
}
}
evaluateFlag(flagName) {
if (this.flagRegistry[flagName] == null) {
throw new Error(`Cannot evaluate flag '${flagName}': no evaluation function found.`);
}
return this.flagRegistry[flagName].evaluationFn();
}
setFlags(flags) {
this.flags = Object.assign({}, flags);
}
reset() {
this.flags = {};
this.urlFlags = {};
this.populateURLFlags();
}
populateURLFlags() {
if (
typeof this.global === "undefined" ||
typeof this.global.location === "undefined" ||
typeof this.global.location.search === "undefined"
) {
return;
}
const urlParams = getQueryParams(this.global.location.search);
if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(",");
keyValues.forEach((keyValue) => {
const [key, value] = keyValue.split(":");
this.urlFlags[key] = parseValue(key, value);
});
}
}
}
function getQueryParams(queryString) {
const params = {};
queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {
decodeParam(params, t[0], t[1]);
return t.join("=");
});
return params;
}
function decodeParam(params, name, value) {
params[decodeURIComponent(name)] = decodeURIComponent(value || "");
}
function parseValue(flagName, value) {
value = value.toLowerCase();
if (value === "true" || value === "false") {
return value === "true";
} else if (`${+value}` === value) {
return +value;
}
throw new Error(`Could not parse value flag value ${value} for flag ${flagName}.`);
}
/**
* Returns the current environment (a global singleton).
*
* The environment object contains the evaluated feature values as well as the
* active platform.
*/
/** @doc {heading: 'Environment'} */
function env() {
return ENV;
}
let ENV = null;
function setEnvironmentGlobal(environment) {
ENV = environment;
}
//# sourceMappingURL=environment.js.map
/***/
},
/* 11 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"makeTypesMatch",
function () {
return makeTypesMatch;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"assertTypesMatch",
function () {
return assertTypesMatch;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isTensorInList",
function () {
return isTensorInList;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"getTensorsInContainer",
function () {
return getTensorsInContainer;
}
);
/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(23);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function makeTypesMatch(a, b) {
if (a.dtype === b.dtype) {
return [a, b];
}
const dtype = Object(_types__WEBPACK_IMPORTED_MODULE_1__[/* upcastType */ "c"])(
a.dtype,
b.dtype
);
return [a.cast(dtype), b.cast(dtype)];
}
function assertTypesMatch(a, b) {
Object(_util__WEBPACK_IMPORTED_MODULE_2__["assert"])(
a.dtype === b.dtype,
() => `The dtypes of the first(${a.dtype}) and` + ` second(${b.dtype}) input must match`
);
}
function isTensorInList(tensor, tensorList) {
return tensorList.some((x) => x.id === tensor.id);
}
/**
* Extracts any `Tensor`s found within the provided object.
*
* @param container an object that may be a `Tensor` or may directly contain
* `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it
* is safe to pass any object here, except that `Promise`s are not
* supported.
* @returns An array of `Tensors` found within the passed object. If the
* argument is simply a `Tensor', a list containing that `Tensor` is
* returned. If the object is not a `Tensor` or does not
* contain `Tensors`, an empty list is returned.
*/
function getTensorsInContainer(result) {
const list = [];
const seen = new Set();
walkTensorContainer(result, list, seen);
return list;
}
function walkTensorContainer(container, list, seen) {
if (container == null) {
return;
}
if (container instanceof _tensor__WEBPACK_IMPORTED_MODULE_0__[/* Tensor */ "a"]) {
list.push(container);
return;
}
if (!isIterable(container)) {
return;
}
// Iteration over keys works also for arrays.
const iterable = container;
for (const k in iterable) {
const val = iterable[k];
if (!seen.has(val)) {
seen.add(val);
walkTensorContainer(val, list, seen);
}
}
}
// tslint:disable-next-line:no-any
function isIterable(obj) {
return Array.isArray(obj) || typeof obj === "object";
}
//# sourceMappingURL=tensor_util.js.map
/***/
},
/* 12 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (global) {
var numeric = false ? undefined : exports;
if (typeof global !== "undefined") {
global.numeric = numeric;
}
numeric.version = "1.2.6";
// 1. Utility functions
numeric.bench = function bench(f, interval) {
var t1, t2, n, i;
if (typeof interval === "undefined") {
interval = 15;
}
n = 0.5;
t1 = new Date();
while (1) {
n *= 2;
for (i = n; i > 3; i -= 4) {
f();
f();
f();
f();
}
while (i > 0) {
f();
i--;
}
t2 = new Date();
if (t2 - t1 > interval) break;
}
for (i = n; i > 3; i -= 4) {
f();
f();
f();
f();
}
while (i > 0) {
f();
i--;
}
t2 = new Date();
return (1000 * (3 * n - 1)) / (t2 - t1);
};
numeric._myIndexOf = function _myIndexOf(w) {
var n = this.length,
k;
for (k = 0; k < n; ++k) if (this[k] === w) return k;
return -1;
};
numeric.myIndexOf = Array.prototype.indexOf ? Array.prototype.indexOf : numeric._myIndexOf;
numeric.Function = Function;
numeric.precision = 4;
numeric.largeArray = 50;
numeric.prettyPrint = function prettyPrint(x) {
function fmtnum(x) {
if (x === 0) {
return "0";
}
if (isNaN(x)) {
return "NaN";
}
if (x < 0) {
return "-" + fmtnum(-x);
}
if (isFinite(x)) {
var scale = Math.floor(Math.log(x) / Math.log(10));
var normalized = x / Math.pow(10, scale);
var basic = normalized.toPrecision(numeric.precision);
if (parseFloat(basic) === 10) {
scale++;
normalized = 1;
basic = normalized.toPrecision(numeric.precision);
}
return parseFloat(basic).toString() + "e" + scale.toString();
}
return "Infinity";
}
var ret = [];
function foo(x) {
var k;
if (typeof x === "undefined") {
ret.push(Array(numeric.precision + 8).join(" "));
return false;
}
if (typeof x === "string") {
ret.push('"' + x + '"');
return false;
}
if (typeof x === "boolean") {
ret.push(x.toString());
return false;
}
if (typeof x === "number") {
var a = fmtnum(x);
var b = x.toPrecision(numeric.precision);
var c = parseFloat(x.toString()).toString();
var d = [a, b, c, parseFloat(b).toString(), parseFloat(c).toString()];
for (k = 1; k < d.length; k++) {
if (d[k].length < a.length) a = d[k];
}
ret.push(Array(numeric.precision + 8 - a.length).join(" ") + a);
return false;
}
if (x === null) {
ret.push("null");
return false;
}
if (typeof x === "function") {
ret.push(x.toString());
var flag = false;
for (k in x) {
if (x.hasOwnProperty(k)) {
if (flag) ret.push(",\n");
else ret.push("\n{");
flag = true;
ret.push(k);
ret.push(": \n");
foo(x[k]);
}
}
if (flag) ret.push("}\n");
return true;
}
if (x instanceof Array) {
if (x.length > numeric.largeArray) {
ret.push("...Large Array...");
return true;
}
var flag = false;
ret.push("[");
for (k = 0; k < x.length; k++) {
if (k > 0) {
ret.push(",");
if (flag) ret.push("\n ");
}
flag = foo(x[k]);
}
ret.push("]");
return true;
}
ret.push("{");
var flag = false;
for (k in x) {
if (x.hasOwnProperty(k)) {
if (flag) ret.push(",\n");
flag = true;
ret.push(k);
ret.push(": \n");
foo(x[k]);
}
}
ret.push("}");
return true;
}
foo(x);
return ret.join("");
};
numeric.parseDate = function parseDate(d) {
function foo(d) {
if (typeof d === "string") {
return Date.parse(d.replace(/-/g, "/"));
}
if (!(d instanceof Array)) {
throw new Error("parseDate: parameter must be arrays of strings");
}
var ret = [],
k;
for (k = 0; k < d.length; k++) {
ret[k] = foo(d[k]);
}
return ret;
}
return foo(d);
};
numeric.parseFloat = function parseFloat_(d) {
function foo(d) {
if (typeof d === "string") {
return parseFloat(d);
}
if (!(d instanceof Array)) {
throw new Error("parseFloat: parameter must be arrays of strings");
}
var ret = [],
k;
for (k = 0; k < d.length; k++) {
ret[k] = foo(d[k]);
}
return ret;
}
return foo(d);
};
numeric.parseCSV = function parseCSV(t) {
var foo = t.split("\n");
var j, k;
var ret = [];
var pat = /(([^'",]*)|('[^']*')|("[^"]*")),/g;
var patnum =
/^\s*(([+-]?[0-9]+(\.[0-9]*)?(e[+-]?[0-9]+)?)|([+-]?[0-9]*(\.[0-9]+)?(e[+-]?[0-9]+)?))\s*$/;
var stripper = function (n) {
return n.substr(0, n.length - 1);
};
var count = 0;
for (k = 0; k < foo.length; k++) {
var bar = (foo[k] + ",").match(pat),
baz;
if (bar.length > 0) {
ret[count] = [];
for (j = 0; j < bar.length; j++) {
baz = stripper(bar[j]);
if (patnum.test(baz)) {
ret[count][j] = parseFloat(baz);
} else ret[count][j] = baz;
}
count++;
}
}
return ret;
};
numeric.toCSV = function toCSV(A) {
var s = numeric.dim(A);
var i, j, m, n, row, ret;
m = s[0];
n = s[1];
ret = [];
for (i = 0; i < m; i++) {
row = [];
for (j = 0; j < m; j++) {
row[j] = A[i][j].toString();
}
ret[i] = row.join(", ");
}
return ret.join("\n") + "\n";
};
numeric.getURL = function getURL(url) {
var client = new XMLHttpRequest();
client.open("GET", url, false);
client.send();
return client;
};
numeric.imageURL = function imageURL(img) {
function base64(A) {
var n = A.length,
i,
x,
y,
z,
p,
q,
r,
s;
var key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var ret = "";
for (i = 0; i < n; i += 3) {
x = A[i];
y = A[i + 1];
z = A[i + 2];
p = x >> 2;
q = ((x & 3) << 4) + (y >> 4);
r = ((y & 15) << 2) + (z >> 6);
s = z & 63;
if (i + 1 >= n) {
r = s = 64;
} else if (i + 2 >= n) {
s = 64;
}
ret += key.charAt(p) + key.charAt(q) + key.charAt(r) + key.charAt(s);
}
return ret;
}
function crc32Array(a, from, to) {
if (typeof from === "undefined") {
from = 0;
}
if (typeof to === "undefined") {
to = a.length;
}
var table = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535,
0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd,
0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d,
0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac,
0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab,
0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb,
0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea,
0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce,
0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409,
0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739,
0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268,
0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0,
0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8,
0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703,
0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7,
0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae,
0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6,
0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d,
0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5,
0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
];
var crc = -1,
y = 0,
n = a.length,
i;
for (i = from; i < to; i++) {
y = (crc ^ a[i]) & 0xff;
crc = (crc >>> 8) ^ table[y];
}
return crc ^ -1;
}
var h = img[0].length,
w = img[0][0].length,
s1,
s2,
next,
k,
length,
a,
b,
i,
j,
adler32,
crc32;
var stream = [
137,
80,
78,
71,
13,
10,
26,
10, // 0: PNG signature
0,
0,
0,
13, // 8: IHDR Chunk length
73,
72,
68,
82, // 12: "IHDR"
(w >> 24) & 255,
(w >> 16) & 255,
(w >> 8) & 255,
w & 255, // 16: Width
(h >> 24) & 255,
(h >> 16) & 255,
(h >> 8) & 255,
h & 255, // 20: Height
8, // 24: bit depth
2, // 25: RGB
0, // 26: deflate
0, // 27: no filter
0, // 28: no interlace
-1,
-2,
-3,
-4, // 29: CRC
-5,
-6,
-7,
-8, // 33: IDAT Chunk length
73,
68,
65,
84, // 37: "IDAT"
// RFC 1950 header starts here
8, // 41: RFC1950 CMF
29, // 42: RFC1950 FLG
];
crc32 = crc32Array(stream, 12, 29);
stream[29] = (crc32 >> 24) & 255;
stream[30] = (crc32 >> 16) & 255;
stream[31] = (crc32 >> 8) & 255;
stream[32] = crc32 & 255;
s1 = 1;
s2 = 0;
for (i = 0; i < h; i++) {
if (i < h - 1) {
stream.push(0);
} else {
stream.push(1);
}
a = (3 * w + 1 + (i === 0)) & 255;
b = ((3 * w + 1 + (i === 0)) >> 8) & 255;
stream.push(a);
stream.push(b);
stream.push(~a & 255);
stream.push(~b & 255);
if (i === 0) stream.push(0);
for (j = 0; j < w; j++) {
for (k = 0; k < 3; k++) {
a = img[k][i][j];
if (a > 255) a = 255;
else if (a < 0) a = 0;
else a = Math.round(a);
s1 = (s1 + a) % 65521;
s2 = (s2 + s1) % 65521;
stream.push(a);
}
}
stream.push(0);
}
adler32 = (s2 << 16) + s1;
stream.push((adler32 >> 24) & 255);
stream.push((adler32 >> 16) & 255);
stream.push((adler32 >> 8) & 255);
stream.push(adler32 & 255);
length = stream.length - 41;
stream[33] = (length >> 24) & 255;
stream[34] = (length >> 16) & 255;
stream[35] = (length >> 8) & 255;
stream[36] = length & 255;
crc32 = crc32Array(stream, 37);
stream.push((crc32 >> 24) & 255);
stream.push((crc32 >> 16) & 255);
stream.push((crc32 >> 8) & 255);
stream.push(crc32 & 255);
stream.push(0);
stream.push(0);
stream.push(0);
stream.push(0);
// a = stream.length;
stream.push(73); // I
stream.push(69); // E
stream.push(78); // N
stream.push(68); // D
stream.push(174); // CRC1
stream.push(66); // CRC2
stream.push(96); // CRC3
stream.push(130); // CRC4
return "data:image/png;base64," + base64(stream);
};
// 2. Linear algebra with Arrays.
numeric._dim = function _dim(x) {
var ret = [];
while (typeof x === "object") {
ret.push(x.length);
x = x[0];
}
return ret;
};
numeric.dim = function dim(x) {
var y, z;
if (typeof x === "object") {
y = x[0];
if (typeof y === "object") {
z = y[0];
if (typeof z === "object") {
return numeric._dim(x);
}
return [x.length, y.length];
}
return [x.length];
}
return [];
};
numeric.mapreduce = function mapreduce(body, init) {
return Function(
"x",
"accum",
"_s",
"_k",
'if(typeof accum === "undefined") accum = ' +
init +
";\n" +
'if(typeof x === "number") { var xi = x; ' +
body +
"; return accum; }\n" +
'if(typeof _s === "undefined") _s = numeric.dim(x);\n' +
'if(typeof _k === "undefined") _k = 0;\n' +
"var _n = _s[_k];\n" +
"var i,xi;\n" +
"if(_k < _s.length-1) {\n" +
" for(i=_n-1;i>=0;i--) {\n" +
" accum = arguments.callee(x[i],accum,_s,_k+1);\n" +
" }" +
" return accum;\n" +
"}\n" +
"for(i=_n-1;i>=1;i-=2) { \n" +
" xi = x[i];\n" +
" " +
body +
";\n" +
" xi = x[i-1];\n" +
" " +
body +
";\n" +
"}\n" +
"if(i === 0) {\n" +
" xi = x[i];\n" +
" " +
body +
"\n" +
"}\n" +
"return accum;"
);
};
numeric.mapreduce2 = function mapreduce2(body, setup) {
return Function(
"x",
"var n = x.length;\n" +
"var i,xi;\n" +
setup +
";\n" +
"for(i=n-1;i!==-1;--i) { \n" +
" xi = x[i];\n" +
" " +
body +
";\n" +
"}\n" +
"return accum;"
);
};
numeric.same = function same(x, y) {
var i, n;
if (!(x instanceof Array) || !(y instanceof Array)) {
return false;
}
n = x.length;
if (n !== y.length) {
return false;
}
for (i = 0; i < n; i++) {
if (x[i] === y[i]) {
continue;
}
if (typeof x[i] === "object") {
if (!same(x[i], y[i])) return false;
} else {
return false;
}
}
return true;
};
numeric.rep = function rep(s, v, k) {
if (typeof k === "undefined") {
k = 0;
}
var n = s[k],
ret = Array(n),
i;
if (k === s.length - 1) {
for (i = n - 2; i >= 0; i -= 2) {
ret[i + 1] = v;
ret[i] = v;
}
if (i === -1) {
ret[0] = v;
}
return ret;
}
for (i = n - 1; i >= 0; i--) {
ret[i] = numeric.rep(s, v, k + 1);
}
return ret;
};
numeric.dotMMsmall = function dotMMsmall(x, y) {
var i, j, k, p, q, r, ret, foo, bar, woo, i0, k0, p0, r0;
p = x.length;
q = y.length;
r = y[0].length;
ret = Array(p);
for (i = p - 1; i >= 0; i--) {
foo = Array(r);
bar = x[i];
for (k = r - 1; k >= 0; k--) {
woo = bar[q - 1] * y[q - 1][k];
for (j = q - 2; j >= 1; j -= 2) {
i0 = j - 1;
woo += bar[j] * y[j][k] + bar[i0] * y[i0][k];
}
if (j === 0) {
woo += bar[0] * y[0][k];
}
foo[k] = woo;
}
ret[i] = foo;
}
return ret;
};
numeric._getCol = function _getCol(A, j, x) {
var n = A.length,
i;
for (i = n - 1; i > 0; --i) {
x[i] = A[i][j];
--i;
x[i] = A[i][j];
}
if (i === 0) x[0] = A[0][j];
};
numeric.dotMMbig = function dotMMbig(x, y) {
var gc = numeric._getCol,
p = y.length,
v = Array(p);
var m = x.length,
n = y[0].length,
A = new Array(m),
xj;
var VV = numeric.dotVV;
var i, j, k, z;
--p;
--m;
for (i = m; i !== -1; --i) A[i] = Array(n);
--n;
for (i = n; i !== -1; --i) {
gc(y, i, v);
for (j = m; j !== -1; --j) {
z = 0;
xj = x[j];
A[j][i] = VV(xj, v);
}
}
return A;
};
numeric.dotMV = function dotMV(x, y) {
var p = x.length,
q = y.length,
i;
var ret = Array(p),
dotVV = numeric.dotVV;
for (i = p - 1; i >= 0; i--) {
ret[i] = dotVV(x[i], y);
}
return ret;
};
numeric.dotVM = function dotVM(x, y) {
var i, j, k, p, q, r, ret, foo, bar, woo, i0, k0, p0, r0, s1, s2, s3, baz, accum;
p = x.length;
q = y[0].length;
ret = Array(q);
for (k = q - 1; k >= 0; k--) {
woo = x[p - 1] * y[p - 1][k];
for (j = p - 2; j >= 1; j -= 2) {
i0 = j - 1;
woo += x[j] * y[j][k] + x[i0] * y[i0][k];
}
if (j === 0) {
woo += x[0] * y[0][k];
}
ret[k] = woo;
}
return ret;
};
numeric.dotVV = function dotVV(x, y) {
var i,
n = x.length,
i1,
ret = x[n - 1] * y[n - 1];
for (i = n - 2; i >= 1; i -= 2) {
i1 = i - 1;
ret += x[i] * y[i] + x[i1] * y[i1];
}
if (i === 0) {
ret += x[0] * y[0];
}
return ret;
};
numeric.dot = function dot(x, y) {
var d = numeric.dim;
switch (d(x).length * 1000 + d(y).length) {
case 2002:
if (y.length < 10) return numeric.dotMMsmall(x, y);
else return numeric.dotMMbig(x, y);
case 2001:
return numeric.dotMV(x, y);
case 1002:
return numeric.dotVM(x, y);
case 1001:
return numeric.dotVV(x, y);
case 1000:
return numeric.mulVS(x, y);
case 1:
return numeric.mulSV(x, y);
case 0:
return x * y;
default:
throw new Error("numeric.dot only works on vectors and matrices");
}
};
numeric.diag = function diag(d) {
var i,
i1,
j,
n = d.length,
A = Array(n),
Ai;
for (i = n - 1; i >= 0; i--) {
Ai = Array(n);
i1 = i + 2;
for (j = n - 1; j >= i1; j -= 2) {
Ai[j] = 0;
Ai[j - 1] = 0;
}
if (j > i) {
Ai[j] = 0;
}
Ai[i] = d[i];
for (j = i - 1; j >= 1; j -= 2) {
Ai[j] = 0;
Ai[j - 1] = 0;
}
if (j === 0) {
Ai[0] = 0;
}
A[i] = Ai;
}
return A;
};
numeric.getDiag = function (A) {
var n = Math.min(A.length, A[0].length),
i,
ret = Array(n);
for (i = n - 1; i >= 1; --i) {
ret[i] = A[i][i];
--i;
ret[i] = A[i][i];
}
if (i === 0) {
ret[0] = A[0][0];
}
return ret;
};
numeric.identity = function identity(n) {
return numeric.diag(numeric.rep([n], 1));
};
numeric.pointwise = function pointwise(params, body, setup) {
if (typeof setup === "undefined") {
setup = "";
}
var fun = [];
var k;
var avec = /\[i\]$/,
p,
thevec = "";
var haveret = false;
for (k = 0; k < params.length; k++) {
if (avec.test(params[k])) {
p = params[k].substring(0, params[k].length - 3);
thevec = p;
} else {
p = params[k];
}
if (p === "ret") haveret = true;
fun.push(p);
}
fun[params.length] = "_s";
fun[params.length + 1] = "_k";
fun[params.length + 2] =
'if(typeof _s === "undefined") _s = numeric.dim(' +
thevec +
");\n" +
'if(typeof _k === "undefined") _k = 0;\n' +
"var _n = _s[_k];\n" +
"var i" +
(haveret ? "" : ", ret = Array(_n)") +
";\n" +
"if(_k < _s.length-1) {\n" +
" for(i=_n-1;i>=0;i--) ret[i] = arguments.callee(" +
params.join(",") +
",_s,_k+1);\n" +
" return ret;\n" +
"}\n" +
setup +
"\n" +
"for(i=_n-1;i!==-1;--i) {\n" +
" " +
body +
"\n" +
"}\n" +
"return ret;";
return Function.apply(null, fun);
};
numeric.pointwise2 = function pointwise2(params, body, setup) {
if (typeof setup === "undefined") {
setup = "";
}
var fun = [];
var k;
var avec = /\[i\]$/,
p,
thevec = "";
var haveret = false;
for (k = 0; k < params.length; k++) {
if (avec.test(params[k])) {
p = params[k].substring(0, params[k].length - 3);
thevec = p;
} else {
p = params[k];
}
if (p === "ret") haveret = true;
fun.push(p);
}
fun[params.length] =
"var _n = " +
thevec +
".length;\n" +
"var i" +
(haveret ? "" : ", ret = Array(_n)") +
";\n" +
setup +
"\n" +
"for(i=_n-1;i!==-1;--i) {\n" +
body +
"\n" +
"}\n" +
"return ret;";
return Function.apply(null, fun);
};
numeric._biforeach = function _biforeach(x, y, s, k, f) {
if (k === s.length - 1) {
f(x, y);
return;
}
var i,
n = s[k];
for (i = n - 1; i >= 0; i--) {
_biforeach(
typeof x === "object" ? x[i] : x,
typeof y === "object" ? y[i] : y,
s,
k + 1,
f
);
}
};
numeric._biforeach2 = function _biforeach2(x, y, s, k, f) {
if (k === s.length - 1) {
return f(x, y);
}
var i,
n = s[k],
ret = Array(n);
for (i = n - 1; i >= 0; --i) {
ret[i] = _biforeach2(
typeof x === "object" ? x[i] : x,
typeof y === "object" ? y[i] : y,
s,
k + 1,
f
);
}
return ret;
};
numeric._foreach = function _foreach(x, s, k, f) {
if (k === s.length - 1) {
f(x);
return;
}
var i,
n = s[k];
for (i = n - 1; i >= 0; i--) {
_foreach(x[i], s, k + 1, f);
}
};
numeric._foreach2 = function _foreach2(x, s, k, f) {
if (k === s.length - 1) {
return f(x);
}
var i,
n = s[k],
ret = Array(n);
for (i = n - 1; i >= 0; i--) {
ret[i] = _foreach2(x[i], s, k + 1, f);
}
return ret;
};
/*numeric.anyV = numeric.mapreduce('if(xi) return true;','false');
numeric.allV = numeric.mapreduce('if(!xi) return false;','true');
numeric.any = function(x) { if(typeof x.length === "undefined") return x; return numeric.anyV(x); }
numeric.all = function(x) { if(typeof x.length === "undefined") return x; return numeric.allV(x); }*/
numeric.ops2 = {
add: "+",
sub: "-",
mul: "*",
div: "/",
mod: "%",
and: "&&",
or: "||",
eq: "===",
neq: "!==",
lt: "<",
gt: ">",
leq: "<=",
geq: ">=",
band: "&",
bor: "|",
bxor: "^",
lshift: "<<",
rshift: ">>",
rrshift: ">>>",
};
numeric.opseq = {
addeq: "+=",
subeq: "-=",
muleq: "*=",
diveq: "/=",
modeq: "%=",
lshifteq: "<<=",
rshifteq: ">>=",
rrshifteq: ">>>=",
bandeq: "&=",
boreq: "|=",
bxoreq: "^=",
};
numeric.mathfuns = [
"abs",
"acos",
"asin",
"atan",
"ceil",
"cos",
"exp",
"floor",
"log",
"round",
"sin",
"sqrt",
"tan",
"isNaN",
"isFinite",
];
numeric.mathfuns2 = ["atan2", "pow", "max", "min"];
numeric.ops1 = {
neg: "-",
not: "!",
bnot: "~",
clone: "",
};
numeric.mapreducers = {
any: ["if(xi) return true;", "var accum = false;"],
all: ["if(!xi) return false;", "var accum = true;"],
sum: ["accum += xi;", "var accum = 0;"],
prod: ["accum *= xi;", "var accum = 1;"],
norm2Squared: ["accum += xi*xi;", "var accum = 0;"],
norminf: [
"accum = max(accum,abs(xi));",
"var accum = 0, max = Math.max, abs = Math.abs;",
],
norm1: ["accum += abs(xi)", "var accum = 0, abs = Math.abs;"],
sup: ["accum = max(accum,xi);", "var accum = -Infinity, max = Math.max;"],
inf: ["accum = min(accum,xi);", "var accum = Infinity, min = Math.min;"],
};
(function () {
var i, o;
for (i = 0; i < numeric.mathfuns2.length; ++i) {
o = numeric.mathfuns2[i];
numeric.ops2[o] = o;
}
for (i in numeric.ops2) {
if (numeric.ops2.hasOwnProperty(i)) {
o = numeric.ops2[i];
var code,
codeeq,
setup = "";
if (numeric.myIndexOf.call(numeric.mathfuns2, i) !== -1) {
setup = "var " + o + " = Math." + o + ";\n";
code = function (r, x, y) {
return r + " = " + o + "(" + x + "," + y + ")";
};
codeeq = function (x, y) {
return x + " = " + o + "(" + x + "," + y + ")";
};
} else {
code = function (r, x, y) {
return r + " = " + x + " " + o + " " + y;
};
if (numeric.opseq.hasOwnProperty(i + "eq")) {
codeeq = function (x, y) {
return x + " " + o + "= " + y;
};
} else {
codeeq = function (x, y) {
return x + " = " + x + " " + o + " " + y;
};
}
}
numeric[i + "VV"] = numeric.pointwise2(
["x[i]", "y[i]"],
code("ret[i]", "x[i]", "y[i]"),
setup
);
numeric[i + "SV"] = numeric.pointwise2(
["x", "y[i]"],
code("ret[i]", "x", "y[i]"),
setup
);
numeric[i + "VS"] = numeric.pointwise2(
["x[i]", "y"],
code("ret[i]", "x[i]", "y"),
setup
);
numeric[i] = Function(
"var n = arguments.length, i, x = arguments[0], y;\n" +
"var VV = numeric." +
i +
"VV, VS = numeric." +
i +
"VS, SV = numeric." +
i +
"SV;\n" +
"var dim = numeric.dim;\n" +
"for(i=1;i!==n;++i) { \n" +
" y = arguments[i];\n" +
' if(typeof x === "object") {\n' +
' if(typeof y === "object") x = numeric._biforeach2(x,y,dim(x),0,VV);\n' +
" else x = numeric._biforeach2(x,y,dim(x),0,VS);\n" +
' } else if(typeof y === "object") x = numeric._biforeach2(x,y,dim(y),0,SV);\n' +
" else " +
codeeq("x", "y") +
"\n" +
"}\nreturn x;\n"
);
numeric[o] = numeric[i];
numeric[i + "eqV"] = numeric.pointwise2(
["ret[i]", "x[i]"],
codeeq("ret[i]", "x[i]"),
setup
);
numeric[i + "eqS"] = numeric.pointwise2(
["ret[i]", "x"],
codeeq("ret[i]", "x"),
setup
);
numeric[i + "eq"] = Function(
"var n = arguments.length, i, x = arguments[0], y;\n" +
"var V = numeric." +
i +
"eqV, S = numeric." +
i +
"eqS\n" +
"var s = numeric.dim(x);\n" +
"for(i=1;i!==n;++i) { \n" +
" y = arguments[i];\n" +
' if(typeof y === "object") numeric._biforeach(x,y,s,0,V);\n' +
" else numeric._biforeach(x,y,s,0,S);\n" +
"}\nreturn x;\n"
);
}
}
for (i = 0; i < numeric.mathfuns2.length; ++i) {
o = numeric.mathfuns2[i];
delete numeric.ops2[o];
}
for (i = 0; i < numeric.mathfuns.length; ++i) {
o = numeric.mathfuns[i];
numeric.ops1[o] = o;
}
for (i in numeric.ops1) {
if (numeric.ops1.hasOwnProperty(i)) {
setup = "";
o = numeric.ops1[i];
if (numeric.myIndexOf.call(numeric.mathfuns, i) !== -1) {
if (Math.hasOwnProperty(o)) setup = "var " + o + " = Math." + o + ";\n";
}
numeric[i + "eqV"] = numeric.pointwise2(
["ret[i]"],
"ret[i] = " + o + "(ret[i]);",
setup
);
numeric[i + "eq"] = Function(
"x",
'if(typeof x !== "object") return ' +
o +
"x\n" +
"var i;\n" +
"var V = numeric." +
i +
"eqV;\n" +
"var s = numeric.dim(x);\n" +
"numeric._foreach(x,s,0,V);\n" +
"return x;\n"
);
numeric[i + "V"] = numeric.pointwise2(["x[i]"], "ret[i] = " + o + "(x[i]);", setup);
numeric[i] = Function(
"x",
'if(typeof x !== "object") return ' +
o +
"(x)\n" +
"var i;\n" +
"var V = numeric." +
i +
"V;\n" +
"var s = numeric.dim(x);\n" +
"return numeric._foreach2(x,s,0,V);\n"
);
}
}
for (i = 0; i < numeric.mathfuns.length; ++i) {
o = numeric.mathfuns[i];
delete numeric.ops1[o];
}
for (i in numeric.mapreducers) {
if (numeric.mapreducers.hasOwnProperty(i)) {
o = numeric.mapreducers[i];
numeric[i + "V"] = numeric.mapreduce2(o[0], o[1]);
numeric[i] = Function(
"x",
"s",
"k",
o[1] +
'if(typeof x !== "object") {' +
" xi = x;\n" +
o[0] +
";\n" +
" return accum;\n" +
"}" +
'if(typeof s === "undefined") s = numeric.dim(x);\n' +
'if(typeof k === "undefined") k = 0;\n' +
"if(k === s.length-1) return numeric." +
i +
"V(x);\n" +
"var xi;\n" +
"var n = x.length, i;\n" +
"for(i=n-1;i!==-1;--i) {\n" +
" xi = arguments.callee(x[i]);\n" +
o[0] +
";\n" +
"}\n" +
"return accum;\n"
);
}
}
})();
numeric.truncVV = numeric.pointwise(
["x[i]", "y[i]"],
"ret[i] = round(x[i]/y[i])*y[i];",
"var round = Math.round;"
);
numeric.truncVS = numeric.pointwise(
["x[i]", "y"],
"ret[i] = round(x[i]/y)*y;",
"var round = Math.round;"
);
numeric.truncSV = numeric.pointwise(
["x", "y[i]"],
"ret[i] = round(x/y[i])*y[i];",
"var round = Math.round;"
);
numeric.trunc = function trunc(x, y) {
if (typeof x === "object") {
if (typeof y === "object") return numeric.truncVV(x, y);
return numeric.truncVS(x, y);
}
if (typeof y === "object") return numeric.truncSV(x, y);
return Math.round(x / y) * y;
};
numeric.inv = function inv(x) {
var s = numeric.dim(x),
abs = Math.abs,
m = s[0],
n = s[1];
var A = numeric.clone(x),
Ai,
Aj;
var I = numeric.identity(m),
Ii,
Ij;
var i, j, k, x;
for (j = 0; j < n; ++j) {
var i0 = -1;
var v0 = -1;
for (i = j; i !== m; ++i) {
k = abs(A[i][j]);
if (k > v0) {
i0 = i;
v0 = k;
}
}
Aj = A[i0];
A[i0] = A[j];
A[j] = Aj;
Ij = I[i0];
I[i0] = I[j];
I[j] = Ij;
x = Aj[j];
for (k = j; k !== n; ++k) Aj[k] /= x;
for (k = n - 1; k !== -1; --k) Ij[k] /= x;
for (i = m - 1; i !== -1; --i) {
if (i !== j) {
Ai = A[i];
Ii = I[i];
x = Ai[j];
for (k = j + 1; k !== n; ++k) Ai[k] -= Aj[k] * x;
for (k = n - 1; k > 0; --k) {
Ii[k] -= Ij[k] * x;
--k;
Ii[k] -= Ij[k] * x;
}
if (k === 0) Ii[0] -= Ij[0] * x;
}
}
}
return I;
};
numeric.det = function det(x) {
var s = numeric.dim(x);
if (s.length !== 2 || s[0] !== s[1]) {
throw new Error("numeric: det() only works on square matrices");
}
var n = s[0],
ret = 1,
i,
j,
k,
A = numeric.clone(x),
Aj,
Ai,
alpha,
temp,
k1,
k2,
k3;
for (j = 0; j < n - 1; j++) {
k = j;
for (i = j + 1; i < n; i++) {
if (Math.abs(A[i][j]) > Math.abs(A[k][j])) {
k = i;
}
}
if (k !== j) {
temp = A[k];
A[k] = A[j];
A[j] = temp;
ret *= -1;
}
Aj = A[j];
for (i = j + 1; i < n; i++) {
Ai = A[i];
alpha = Ai[j] / Aj[j];
for (k = j + 1; k < n - 1; k += 2) {
k1 = k + 1;
Ai[k] -= Aj[k] * alpha;
Ai[k1] -= Aj[k1] * alpha;
}
if (k !== n) {
Ai[k] -= Aj[k] * alpha;
}
}
if (Aj[j] === 0) {
return 0;
}
ret *= Aj[j];
}
return ret * A[j][j];
};
numeric.transpose = function transpose(x) {
var i,
j,
m = x.length,
n = x[0].length,
ret = Array(n),
A0,
A1,
Bj;
for (j = 0; j < n; j++) ret[j] = Array(m);
for (i = m - 1; i >= 1; i -= 2) {
A1 = x[i];
A0 = x[i - 1];
for (j = n - 1; j >= 1; --j) {
Bj = ret[j];
Bj[i] = A1[j];
Bj[i - 1] = A0[j];
--j;
Bj = ret[j];
Bj[i] = A1[j];
Bj[i - 1] = A0[j];
}
if (j === 0) {
Bj = ret[0];
Bj[i] = A1[0];
Bj[i - 1] = A0[0];
}
}
if (i === 0) {
A0 = x[0];
for (j = n - 1; j >= 1; --j) {
ret[j][0] = A0[j];
--j;
ret[j][0] = A0[j];
}
if (j === 0) {
ret[0][0] = A0[0];
}
}
return ret;
};
numeric.negtranspose = function negtranspose(x) {
var i,
j,
m = x.length,
n = x[0].length,
ret = Array(n),
A0,
A1,
Bj;
for (j = 0; j < n; j++) ret[j] = Array(m);
for (i = m - 1; i >= 1; i -= 2) {
A1 = x[i];
A0 = x[i - 1];
for (j = n - 1; j >= 1; --j) {
Bj = ret[j];
Bj[i] = -A1[j];
Bj[i - 1] = -A0[j];
--j;
Bj = ret[j];
Bj[i] = -A1[j];
Bj[i - 1] = -A0[j];
}
if (j === 0) {
Bj = ret[0];
Bj[i] = -A1[0];
Bj[i - 1] = -A0[0];
}
}
if (i === 0) {
A0 = x[0];
for (j = n - 1; j >= 1; --j) {
ret[j][0] = -A0[j];
--j;
ret[j][0] = -A0[j];
}
if (j === 0) {
ret[0][0] = -A0[0];
}
}
return ret;
};
numeric._random = function _random(s, k) {
var i,
n = s[k],
ret = Array(n),
rnd;
if (k === s.length - 1) {
rnd = Math.random;
for (i = n - 1; i >= 1; i -= 2) {
ret[i] = rnd();
ret[i - 1] = rnd();
}
if (i === 0) {
ret[0] = rnd();
}
return ret;
}
for (i = n - 1; i >= 0; i--) ret[i] = _random(s, k + 1);
return ret;
};
numeric.random = function random(s) {
return numeric._random(s, 0);
};
numeric.norm2 = function norm2(x) {
return Math.sqrt(numeric.norm2Squared(x));
};
numeric.linspace = function linspace(a, b, n) {
if (typeof n === "undefined") n = Math.max(Math.round(b - a) + 1, 1);
if (n < 2) {
return n === 1 ? [a] : [];
}
var i,
ret = Array(n);
n--;
for (i = n; i >= 0; i--) {
ret[i] = (i * b + (n - i) * a) / n;
}
return ret;
};
numeric.getBlock = function getBlock(x, from, to) {
var s = numeric.dim(x);
function foo(x, k) {
var i,
a = from[k],
n = to[k] - a,
ret = Array(n);
if (k === s.length - 1) {
for (i = n; i >= 0; i--) {
ret[i] = x[i + a];
}
return ret;
}
for (i = n; i >= 0; i--) {
ret[i] = foo(x[i + a], k + 1);
}
return ret;
}
return foo(x, 0);
};
numeric.setBlock = function setBlock(x, from, to, B) {
var s = numeric.dim(x);
function foo(x, y, k) {
var i,
a = from[k],
n = to[k] - a;
if (k === s.length - 1) {
for (i = n; i >= 0; i--) {
x[i + a] = y[i];
}
}
for (i = n; i >= 0; i--) {
foo(x[i + a], y[i], k + 1);
}
}
foo(x, B, 0);
return x;
};
numeric.getRange = function getRange(A, I, J) {
var m = I.length,
n = J.length;
var i, j;
var B = Array(m),
Bi,
AI;
for (i = m - 1; i !== -1; --i) {
B[i] = Array(n);
Bi = B[i];
AI = A[I[i]];
for (j = n - 1; j !== -1; --j) Bi[j] = AI[J[j]];
}
return B;
};
numeric.blockMatrix = function blockMatrix(X) {
var s = numeric.dim(X);
if (s.length < 4) return numeric.blockMatrix([X]);
var m = s[0],
n = s[1],
M,
N,
i,
j,
Xij;
M = 0;
N = 0;
for (i = 0; i < m; ++i) M += X[i][0].length;
for (j = 0; j < n; ++j) N += X[0][j][0].length;
var Z = Array(M);
for (i = 0; i < M; ++i) Z[i] = Array(N);
var I = 0,
J,
ZI,
k,
l,
Xijk;
for (i = 0; i < m; ++i) {
J = N;
for (j = n - 1; j !== -1; --j) {
Xij = X[i][j];
J -= Xij[0].length;
for (k = Xij.length - 1; k !== -1; --k) {
Xijk = Xij[k];
ZI = Z[I + k];
for (l = Xijk.length - 1; l !== -1; --l) ZI[J + l] = Xijk[l];
}
}
I += X[i][0].length;
}
return Z;
};
numeric.tensor = function tensor(x, y) {
if (typeof x === "number" || typeof y === "number") return numeric.mul(x, y);
var s1 = numeric.dim(x),
s2 = numeric.dim(y);
if (s1.length !== 1 || s2.length !== 1) {
throw new Error("numeric: tensor product is only defined for vectors");
}
var m = s1[0],
n = s2[0],
A = Array(m),
Ai,
i,
j,
xi;
for (i = m - 1; i >= 0; i--) {
Ai = Array(n);
xi = x[i];
for (j = n - 1; j >= 3; --j) {
Ai[j] = xi * y[j];
--j;
Ai[j] = xi * y[j];
--j;
Ai[j] = xi * y[j];
--j;
Ai[j] = xi * y[j];
}
while (j >= 0) {
Ai[j] = xi * y[j];
--j;
}
A[i] = Ai;
}
return A;
};
// 3. The Tensor type T
numeric.T = function T(x, y) {
this.x = x;
this.y = y;
};
numeric.t = function t(x, y) {
return new numeric.T(x, y);
};
numeric.Tbinop = function Tbinop(rr, rc, cr, cc, setup) {
var io = numeric.indexOf;
if (typeof setup !== "string") {
var k;
setup = "";
for (k in numeric) {
if (
numeric.hasOwnProperty(k) &&
(rr.indexOf(k) >= 0 ||
rc.indexOf(k) >= 0 ||
cr.indexOf(k) >= 0 ||
cc.indexOf(k) >= 0) &&
k.length > 1
) {
setup += "var " + k + " = numeric." + k + ";\n";
}
}
}
return Function(
["y"],
"var x = this;\n" +
"if(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n" +
setup +
"\n" +
"if(x.y) {" +
" if(y.y) {" +
" return new numeric.T(" +
cc +
");\n" +
" }\n" +
" return new numeric.T(" +
cr +
");\n" +
"}\n" +
"if(y.y) {\n" +
" return new numeric.T(" +
rc +
");\n" +
"}\n" +
"return new numeric.T(" +
rr +
");\n"
);
};
numeric.T.prototype.add = numeric.Tbinop(
"add(x.x,y.x)",
"add(x.x,y.x),y.y",
"add(x.x,y.x),x.y",
"add(x.x,y.x),add(x.y,y.y)"
);
numeric.T.prototype.sub = numeric.Tbinop(
"sub(x.x,y.x)",
"sub(x.x,y.x),neg(y.y)",
"sub(x.x,y.x),x.y",
"sub(x.x,y.x),sub(x.y,y.y)"
);
numeric.T.prototype.mul = numeric.Tbinop(
"mul(x.x,y.x)",
"mul(x.x,y.x),mul(x.x,y.y)",
"mul(x.x,y.x),mul(x.y,y.x)",
"sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"
);
numeric.T.prototype.reciprocal = function reciprocal() {
var mul = numeric.mul,
div = numeric.div;
if (this.y) {
var d = numeric.add(mul(this.x, this.x), mul(this.y, this.y));
return new numeric.T(div(this.x, d), div(numeric.neg(this.y), d));
}
return new T(div(1, this.x));
};
numeric.T.prototype.div = function div(y) {
if (!(y instanceof numeric.T)) y = new numeric.T(y);
if (y.y) {
return this.mul(y.reciprocal());
}
var div = numeric.div;
if (this.y) {
return new numeric.T(div(this.x, y.x), div(this.y, y.x));
}
return new numeric.T(div(this.x, y.x));
};
numeric.T.prototype.dot = numeric.Tbinop(
"dot(x.x,y.x)",
"dot(x.x,y.x),dot(x.x,y.y)",
"dot(x.x,y.x),dot(x.y,y.x)",
"sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"
);
numeric.T.prototype.transpose = function transpose() {
var t = numeric.transpose,
x = this.x,
y = this.y;
if (y) {
return new numeric.T(t(x), t(y));
}
return new numeric.T(t(x));
};
numeric.T.prototype.transjugate = function transjugate() {
var t = numeric.transpose,
x = this.x,
y = this.y;
if (y) {
return new numeric.T(t(x), numeric.negtranspose(y));
}
return new numeric.T(t(x));
};
numeric.Tunop = function Tunop(r, c, s) {
if (typeof s !== "string") {
s = "";
}
return Function(
"var x = this;\n" + s + "\n" + "if(x.y) {" + " " + c + ";\n" + "}\n" + r + ";\n"
);
};
numeric.T.prototype.exp = numeric.Tunop(
"return new numeric.T(ex)",
"return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))",
"var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"
);
numeric.T.prototype.conj = numeric.Tunop(
"return new numeric.T(x.x);",
"return new numeric.T(x.x,numeric.neg(x.y));"
);
numeric.T.prototype.neg = numeric.Tunop(
"return new numeric.T(neg(x.x));",
"return new numeric.T(neg(x.x),neg(x.y));",
"var neg = numeric.neg;"
);
numeric.T.prototype.sin = numeric.Tunop(
"return new numeric.T(numeric.sin(x.x))",
"return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"
);
numeric.T.prototype.cos = numeric.Tunop(
"return new numeric.T(numeric.cos(x.x))",
"return x.exp().add(x.neg().exp()).div(2);"
);
numeric.T.prototype.abs = numeric.Tunop(
"return new numeric.T(numeric.abs(x.x));",
"return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));",
"var mul = numeric.mul;"
);
numeric.T.prototype.log = numeric.Tunop(
"return new numeric.T(numeric.log(x.x));",
"var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\n" +
"return new numeric.T(numeric.log(r.x),theta.x);"
);
numeric.T.prototype.norm2 = numeric.Tunop(
"return numeric.norm2(x.x);",
"var f = numeric.norm2Squared;\n" + "return Math.sqrt(f(x.x)+f(x.y));"
);
numeric.T.prototype.inv = function inv() {
var A = this;
if (typeof A.y === "undefined") {
return new numeric.T(numeric.inv(A.x));
}
var n = A.x.length,
i,
j,
k;
var Rx = numeric.identity(n),
Ry = numeric.rep([n, n], 0);
var Ax = numeric.clone(A.x),
Ay = numeric.clone(A.y);
var Aix, Aiy, Ajx, Ajy, Rix, Riy, Rjx, Rjy;
var i, j, k, d, d1, ax, ay, bx, by, temp;
for (i = 0; i < n; i++) {
ax = Ax[i][i];
ay = Ay[i][i];
d = ax * ax + ay * ay;
k = i;
for (j = i + 1; j < n; j++) {
ax = Ax[j][i];
ay = Ay[j][i];
d1 = ax * ax + ay * ay;
if (d1 > d) {
k = j;
d = d1;
}
}
if (k !== i) {
temp = Ax[i];
Ax[i] = Ax[k];
Ax[k] = temp;
temp = Ay[i];
Ay[i] = Ay[k];
Ay[k] = temp;
temp = Rx[i];
Rx[i] = Rx[k];
Rx[k] = temp;
temp = Ry[i];
Ry[i] = Ry[k];
Ry[k] = temp;
}
Aix = Ax[i];
Aiy = Ay[i];
Rix = Rx[i];
Riy = Ry[i];
ax = Aix[i];
ay = Aiy[i];
for (j = i + 1; j < n; j++) {
bx = Aix[j];
by = Aiy[j];
Aix[j] = (bx * ax + by * ay) / d;
Aiy[j] = (by * ax - bx * ay) / d;
}
for (j = 0; j < n; j++) {
bx = Rix[j];
by = Riy[j];
Rix[j] = (bx * ax + by * ay) / d;
Riy[j] = (by * ax - bx * ay) / d;
}
for (j = i + 1; j < n; j++) {
Ajx = Ax[j];
Ajy = Ay[j];
Rjx = Rx[j];
Rjy = Ry[j];
ax = Ajx[i];
ay = Ajy[i];
for (k = i + 1; k < n; k++) {
bx = Aix[k];
by = Aiy[k];
Ajx[k] -= bx * ax - by * ay;
Ajy[k] -= by * ax + bx * ay;
}
for (k = 0; k < n; k++) {
bx = Rix[k];
by = Riy[k];
Rjx[k] -= bx * ax - by * ay;
Rjy[k] -= by * ax + bx * ay;
}
}
}
for (i = n - 1; i > 0; i--) {
Rix = Rx[i];
Riy = Ry[i];
for (j = i - 1; j >= 0; j--) {
Rjx = Rx[j];
Rjy = Ry[j];
ax = Ax[j][i];
ay = Ay[j][i];
for (k = n - 1; k >= 0; k--) {
bx = Rix[k];
by = Riy[k];
Rjx[k] -= ax * bx - ay * by;
Rjy[k] -= ax * by + ay * bx;
}
}
}
return new numeric.T(Rx, Ry);
};
numeric.T.prototype.get = function get(i) {
var x = this.x,
y = this.y,
k = 0,
ik,
n = i.length;
if (y) {
while (k < n) {
ik = i[k];
x = x[ik];
y = y[ik];
k++;
}
return new numeric.T(x, y);
}
while (k < n) {
ik = i[k];
x = x[ik];
k++;
}
return new numeric.T(x);
};
numeric.T.prototype.set = function set(i, v) {
var x = this.x,
y = this.y,
k = 0,
ik,
n = i.length,
vx = v.x,
vy = v.y;
if (n === 0) {
if (vy) {
this.y = vy;
} else if (y) {
this.y = undefined;
}
this.x = x;
return this;
}
if (vy) {
if (y) {
/* ok */
} else {
y = numeric.rep(numeric.dim(x), 0);
this.y = y;
}
while (k < n - 1) {
ik = i[k];
x = x[ik];
y = y[ik];
k++;
}
ik = i[k];
x[ik] = vx;
y[ik] = vy;
return this;
}
if (y) {
while (k < n - 1) {
ik = i[k];
x = x[ik];
y = y[ik];
k++;
}
ik = i[k];
x[ik] = vx;
if (vx instanceof Array) y[ik] = numeric.rep(numeric.dim(vx), 0);
else y[ik] = 0;
return this;
}
while (k < n - 1) {
ik = i[k];
x = x[ik];
k++;
}
ik = i[k];
x[ik] = vx;
return this;
};
numeric.T.prototype.getRows = function getRows(i0, i1) {
var n = i1 - i0 + 1,
j;
var rx = Array(n),
ry,
x = this.x,
y = this.y;
for (j = i0; j <= i1; j++) {
rx[j - i0] = x[j];
}
if (y) {
ry = Array(n);
for (j = i0; j <= i1; j++) {
ry[j - i0] = y[j];
}
return new numeric.T(rx, ry);
}
return new numeric.T(rx);
};
numeric.T.prototype.setRows = function setRows(i0, i1, A) {
var j;
var rx = this.x,
ry = this.y,
x = A.x,
y = A.y;
for (j = i0; j <= i1; j++) {
rx[j] = x[j - i0];
}
if (y) {
if (!ry) {
ry = numeric.rep(numeric.dim(rx), 0);
this.y = ry;
}
for (j = i0; j <= i1; j++) {
ry[j] = y[j - i0];
}
} else if (ry) {
for (j = i0; j <= i1; j++) {
ry[j] = numeric.rep([x[j - i0].length], 0);
}
}
return this;
};
numeric.T.prototype.getRow = function getRow(k) {
var x = this.x,
y = this.y;
if (y) {
return new numeric.T(x[k], y[k]);
}
return new numeric.T(x[k]);
};
numeric.T.prototype.setRow = function setRow(i, v) {
var rx = this.x,
ry = this.y,
x = v.x,
y = v.y;
rx[i] = x;
if (y) {
if (!ry) {
ry = numeric.rep(numeric.dim(rx), 0);
this.y = ry;
}
ry[i] = y;
} else if (ry) {
ry = numeric.rep([x.length], 0);
}
return this;
};
numeric.T.prototype.getBlock = function getBlock(from, to) {
var x = this.x,
y = this.y,
b = numeric.getBlock;
if (y) {
return new numeric.T(b(x, from, to), b(y, from, to));
}
return new numeric.T(b(x, from, to));
};
numeric.T.prototype.setBlock = function setBlock(from, to, A) {
if (!(A instanceof numeric.T)) A = new numeric.T(A);
var x = this.x,
y = this.y,
b = numeric.setBlock,
Ax = A.x,
Ay = A.y;
if (Ay) {
if (!y) {
this.y = numeric.rep(numeric.dim(this), 0);
y = this.y;
}
b(x, from, to, Ax);
b(y, from, to, Ay);
return this;
}
b(x, from, to, Ax);
if (y) b(y, from, to, numeric.rep(numeric.dim(Ax), 0));
};
numeric.T.rep = function rep(s, v) {
var T = numeric.T;
if (!(v instanceof T)) v = new T(v);
var x = v.x,
y = v.y,
r = numeric.rep;
if (y) return new T(r(s, x), r(s, y));
return new T(r(s, x));
};
numeric.T.diag = function diag(d) {
if (!(d instanceof numeric.T)) d = new numeric.T(d);
var x = d.x,
y = d.y,
diag = numeric.diag;
if (y) return new numeric.T(diag(x), diag(y));
return new numeric.T(diag(x));
};
numeric.T.eig = function eig() {
if (this.y) {
throw new Error("eig: not implemented for complex matrices.");
}
return numeric.eig(this.x);
};
numeric.T.identity = function identity(n) {
return new numeric.T(numeric.identity(n));
};
numeric.T.prototype.getDiag = function getDiag() {
var n = numeric;
var x = this.x,
y = this.y;
if (y) {
return new n.T(n.getDiag(x), n.getDiag(y));
}
return new n.T(n.getDiag(x));
};
// 4. Eigenvalues of real matrices
numeric.house = function house(x) {
var v = numeric.clone(x);
var s = x[0] >= 0 ? 1 : -1;
var alpha = s * numeric.norm2(x);
v[0] += alpha;
var foo = numeric.norm2(v);
if (foo === 0) {
/* this should not happen */ throw new Error("eig: internal error");
}
return numeric.div(v, foo);
};
numeric.toUpperHessenberg = function toUpperHessenberg(me) {
var s = numeric.dim(me);
if (s.length !== 2 || s[0] !== s[1]) {
throw new Error("numeric: toUpperHessenberg() only works on square matrices");
}
var m = s[0],
i,
j,
k,
x,
v,
A = numeric.clone(me),
B,
C,
Ai,
Ci,
Q = numeric.identity(m),
Qi;
for (j = 0; j < m - 2; j++) {
x = Array(m - j - 1);
for (i = j + 1; i < m; i++) {
x[i - j - 1] = A[i][j];
}
if (numeric.norm2(x) > 0) {
v = numeric.house(x);
B = numeric.getBlock(A, [j + 1, j], [m - 1, m - 1]);
C = numeric.tensor(v, numeric.dot(v, B));
for (i = j + 1; i < m; i++) {
Ai = A[i];
Ci = C[i - j - 1];
for (k = j; k < m; k++) Ai[k] -= 2 * Ci[k - j];
}
B = numeric.getBlock(A, [0, j + 1], [m - 1, m - 1]);
C = numeric.tensor(numeric.dot(B, v), v);
for (i = 0; i < m; i++) {
Ai = A[i];
Ci = C[i];
for (k = j + 1; k < m; k++) Ai[k] -= 2 * Ci[k - j - 1];
}
B = Array(m - j - 1);
for (i = j + 1; i < m; i++) B[i - j - 1] = Q[i];
C = numeric.tensor(v, numeric.dot(v, B));
for (i = j + 1; i < m; i++) {
Qi = Q[i];
Ci = C[i - j - 1];
for (k = 0; k < m; k++) Qi[k] -= 2 * Ci[k];
}
}
}
return { H: A, Q: Q };
};
numeric.epsilon = 2.220446049250313e-16;
numeric.QRFrancis = function (H, maxiter) {
if (typeof maxiter === "undefined") {
maxiter = 10000;
}
H = numeric.clone(H);
var H0 = numeric.clone(H);
var s = numeric.dim(H),
m = s[0],
x,
v,
a,
b,
c,
d,
det,
tr,
Hloc,
Q = numeric.identity(m),
Qi,
Hi,
B,
C,
Ci,
i,
j,
k,
iter;
if (m < 3) {
return { Q: Q, B: [[0, m - 1]] };
}
var epsilon = numeric.epsilon;
for (iter = 0; iter < maxiter; iter++) {
for (j = 0; j < m - 1; j++) {
if (
Math.abs(H[j + 1][j]) <
epsilon * (Math.abs(H[j][j]) + Math.abs(H[j + 1][j + 1]))
) {
var QH1 = numeric.QRFrancis(numeric.getBlock(H, [0, 0], [j, j]), maxiter);
var QH2 = numeric.QRFrancis(
numeric.getBlock(H, [j + 1, j + 1], [m - 1, m - 1]),
maxiter
);
B = Array(j + 1);
for (i = 0; i <= j; i++) {
B[i] = Q[i];
}
C = numeric.dot(QH1.Q, B);
for (i = 0; i <= j; i++) {
Q[i] = C[i];
}
B = Array(m - j - 1);
for (i = j + 1; i < m; i++) {
B[i - j - 1] = Q[i];
}
C = numeric.dot(QH2.Q, B);
for (i = j + 1; i < m; i++) {
Q[i] = C[i - j - 1];
}
return { Q: Q, B: QH1.B.concat(numeric.add(QH2.B, j + 1)) };
}
}
a = H[m - 2][m - 2];
b = H[m - 2][m - 1];
c = H[m - 1][m - 2];
d = H[m - 1][m - 1];
tr = a + d;
det = a * d - b * c;
Hloc = numeric.getBlock(H, [0, 0], [2, 2]);
if (tr * tr >= 4 * det) {
var s1, s2;
s1 = 0.5 * (tr + Math.sqrt(tr * tr - 4 * det));
s2 = 0.5 * (tr - Math.sqrt(tr * tr - 4 * det));
Hloc = numeric.add(
numeric.sub(numeric.dot(Hloc, Hloc), numeric.mul(Hloc, s1 + s2)),
numeric.diag(numeric.rep([3], s1 * s2))
);
} else {
Hloc = numeric.add(
numeric.sub(numeric.dot(Hloc, Hloc), numeric.mul(Hloc, tr)),
numeric.diag(numeric.rep([3], det))
);
}
x = [Hloc[0][0], Hloc[1][0], Hloc[2][0]];
v = numeric.house(x);
B = [H[0], H[1], H[2]];
C = numeric.tensor(v, numeric.dot(v, B));
for (i = 0; i < 3; i++) {
Hi = H[i];
Ci = C[i];
for (k = 0; k < m; k++) Hi[k] -= 2 * Ci[k];
}
B = numeric.getBlock(H, [0, 0], [m - 1, 2]);
C = numeric.tensor(numeric.dot(B, v), v);
for (i = 0; i < m; i++) {
Hi = H[i];
Ci = C[i];
for (k = 0; k < 3; k++) Hi[k] -= 2 * Ci[k];
}
B = [Q[0], Q[1], Q[2]];
C = numeric.tensor(v, numeric.dot(v, B));
for (i = 0; i < 3; i++) {
Qi = Q[i];
Ci = C[i];
for (k = 0; k < m; k++) Qi[k] -= 2 * Ci[k];
}
var J;
for (j = 0; j < m - 2; j++) {
for (k = j; k <= j + 1; k++) {
if (
Math.abs(H[k + 1][k]) <
epsilon * (Math.abs(H[k][k]) + Math.abs(H[k + 1][k + 1]))
) {
var QH1 = numeric.QRFrancis(numeric.getBlock(H, [0, 0], [k, k]), maxiter);
var QH2 = numeric.QRFrancis(
numeric.getBlock(H, [k + 1, k + 1], [m - 1, m - 1]),
maxiter
);
B = Array(k + 1);
for (i = 0; i <= k; i++) {
B[i] = Q[i];
}
C = numeric.dot(QH1.Q, B);
for (i = 0; i <= k; i++) {
Q[i] = C[i];
}
B = Array(m - k - 1);
for (i = k + 1; i < m; i++) {
B[i - k - 1] = Q[i];
}
C = numeric.dot(QH2.Q, B);
for (i = k + 1; i < m; i++) {
Q[i] = C[i - k - 1];
}
return { Q: Q, B: QH1.B.concat(numeric.add(QH2.B, k + 1)) };
}
}
J = Math.min(m - 1, j + 3);
x = Array(J - j);
for (i = j + 1; i <= J; i++) {
x[i - j - 1] = H[i][j];
}
v = numeric.house(x);
B = numeric.getBlock(H, [j + 1, j], [J, m - 1]);
C = numeric.tensor(v, numeric.dot(v, B));
for (i = j + 1; i <= J; i++) {
Hi = H[i];
Ci = C[i - j - 1];
for (k = j; k < m; k++) Hi[k] -= 2 * Ci[k - j];
}
B = numeric.getBlock(H, [0, j + 1], [m - 1, J]);
C = numeric.tensor(numeric.dot(B, v), v);
for (i = 0; i < m; i++) {
Hi = H[i];
Ci = C[i];
for (k = j + 1; k <= J; k++) Hi[k] -= 2 * Ci[k - j - 1];
}
B = Array(J - j);
for (i = j + 1; i <= J; i++) B[i - j - 1] = Q[i];
C = numeric.tensor(v, numeric.dot(v, B));
for (i = j + 1; i <= J; i++) {
Qi = Q[i];
Ci = C[i - j - 1];
for (k = 0; k < m; k++) Qi[k] -= 2 * Ci[k];
}
}
}
throw new Error("numeric: eigenvalue iteration does not converge -- increase maxiter?");
};
numeric.eig = function eig(A, maxiter) {
var QH = numeric.toUpperHessenberg(A);
var QB = numeric.QRFrancis(QH.H, maxiter);
var T = numeric.T;
var n = A.length,
i,
k,
flag = false,
B = QB.B,
H = numeric.dot(QB.Q, numeric.dot(QH.H, numeric.transpose(QB.Q)));
var Q = new T(numeric.dot(QB.Q, QH.Q)),
Q0;
var m = B.length,
j;
var a, b, c, d, p1, p2, disc, x, y, p, q, n1, n2;
var sqrt = Math.sqrt;
for (k = 0; k < m; k++) {
i = B[k][0];
if (i === B[k][1]) {
// nothing
} else {
j = i + 1;
a = H[i][i];
b = H[i][j];
c = H[j][i];
d = H[j][j];
if (b === 0 && c === 0) continue;
p1 = -a - d;
p2 = a * d - b * c;
disc = p1 * p1 - 4 * p2;
if (disc >= 0) {
if (p1 < 0) x = -0.5 * (p1 - sqrt(disc));
else x = -0.5 * (p1 + sqrt(disc));
n1 = (a - x) * (a - x) + b * b;
n2 = c * c + (d - x) * (d - x);
if (n1 > n2) {
n1 = sqrt(n1);
p = (a - x) / n1;
q = b / n1;
} else {
n2 = sqrt(n2);
p = c / n2;
q = (d - x) / n2;
}
Q0 = new T([
[q, -p],
[p, q],
]);
Q.setRows(i, j, Q0.dot(Q.getRows(i, j)));
} else {
x = -0.5 * p1;
y = 0.5 * sqrt(-disc);
n1 = (a - x) * (a - x) + b * b;
n2 = c * c + (d - x) * (d - x);
if (n1 > n2) {
n1 = sqrt(n1 + y * y);
p = (a - x) / n1;
q = b / n1;
x = 0;
y /= n1;
} else {
n2 = sqrt(n2 + y * y);
p = c / n2;
q = (d - x) / n2;
x = y / n2;
y = 0;
}
Q0 = new T(
[
[q, -p],
[p, q],
],
[
[x, y],
[y, -x],
]
);
Q.setRows(i, j, Q0.dot(Q.getRows(i, j)));
}
}
}
var R = Q.dot(A).dot(Q.transjugate()),
n = A.length,
E = numeric.T.identity(n);
for (j = 0; j < n; j++) {
if (j > 0) {
for (k = j - 1; k >= 0; k--) {
var Rk = R.get([k, k]),
Rj = R.get([j, j]);
if (numeric.neq(Rk.x, Rj.x) || numeric.neq(Rk.y, Rj.y)) {
x = R.getRow(k).getBlock([k], [j - 1]);
y = E.getRow(j).getBlock([k], [j - 1]);
E.set([j, k], R.get([k, j]).neg().sub(x.dot(y)).div(Rk.sub(Rj)));
} else {
E.setRow(j, E.getRow(k));
continue;
}
}
}
}
for (j = 0; j < n; j++) {
x = E.getRow(j);
E.setRow(j, x.div(x.norm2()));
}
E = E.transpose();
E = Q.transjugate().dot(E);
return { lambda: R.getDiag(), E: E };
};
// 5. Compressed Column Storage matrices
numeric.ccsSparse = function ccsSparse(A) {
var m = A.length,
n,
foo,
i,
j,
counts = [];
for (i = m - 1; i !== -1; --i) {
foo = A[i];
for (j in foo) {
j = parseInt(j);
while (j >= counts.length) counts[counts.length] = 0;
if (foo[j] !== 0) counts[j]++;
}
}
var n = counts.length;
var Ai = Array(n + 1);
Ai[0] = 0;
for (i = 0; i < n; ++i) Ai[i + 1] = Ai[i] + counts[i];
var Aj = Array(Ai[n]),
Av = Array(Ai[n]);
for (i = m - 1; i !== -1; --i) {
foo = A[i];
for (j in foo) {
if (foo[j] !== 0) {
counts[j]--;
Aj[Ai[j] + counts[j]] = i;
Av[Ai[j] + counts[j]] = foo[j];
}
}
}
return [Ai, Aj, Av];
};
numeric.ccsFull = function ccsFull(A) {
var Ai = A[0],
Aj = A[1],
Av = A[2],
s = numeric.ccsDim(A),
m = s[0],
n = s[1],
i,
j,
j0,
j1,
k;
var B = numeric.rep([m, n], 0);
for (i = 0; i < n; i++) {
j0 = Ai[i];
j1 = Ai[i + 1];
for (j = j0; j < j1; ++j) {
B[Aj[j]][i] = Av[j];
}
}
return B;
};
numeric.ccsTSolve = function ccsTSolve(A, b, x, bj, xj) {
var Ai = A[0],
Aj = A[1],
Av = A[2],
m = Ai.length - 1,
max = Math.max,
n = 0;
if (typeof bj === "undefined") x = numeric.rep([m], 0);
if (typeof bj === "undefined") bj = numeric.linspace(0, x.length - 1);
if (typeof xj === "undefined") xj = [];
function dfs(j) {
var k;
if (x[j] !== 0) return;
x[j] = 1;
for (k = Ai[j]; k < Ai[j + 1]; ++k) dfs(Aj[k]);
xj[n] = j;
++n;
}
var i, j, j0, j1, k, l, l0, l1, a;
for (i = bj.length - 1; i !== -1; --i) {
dfs(bj[i]);
}
xj.length = n;
for (i = xj.length - 1; i !== -1; --i) {
x[xj[i]] = 0;
}
for (i = bj.length - 1; i !== -1; --i) {
j = bj[i];
x[j] = b[j];
}
for (i = xj.length - 1; i !== -1; --i) {
j = xj[i];
j0 = Ai[j];
j1 = max(Ai[j + 1], j0);
for (k = j0; k !== j1; ++k) {
if (Aj[k] === j) {
x[j] /= Av[k];
break;
}
}
a = x[j];
for (k = j0; k !== j1; ++k) {
l = Aj[k];
if (l !== j) x[l] -= a * Av[k];
}
}
return x;
};
numeric.ccsDFS = function ccsDFS(n) {
this.k = Array(n);
this.k1 = Array(n);
this.j = Array(n);
};
numeric.ccsDFS.prototype.dfs = function dfs(J, Ai, Aj, x, xj, Pinv) {
var m = 0,
foo,
n = xj.length;
var k = this.k,
k1 = this.k1,
j = this.j,
km,
k11;
if (x[J] !== 0) return;
x[J] = 1;
j[0] = J;
k[0] = km = Ai[J];
k1[0] = k11 = Ai[J + 1];
while (1) {
if (km >= k11) {
xj[n] = j[m];
if (m === 0) return;
++n;
--m;
km = k[m];
k11 = k1[m];
} else {
foo = Pinv[Aj[km]];
if (x[foo] === 0) {
x[foo] = 1;
k[m] = km;
++m;
j[m] = foo;
km = Ai[foo];
k1[m] = k11 = Ai[foo + 1];
} else ++km;
}
}
};
numeric.ccsLPSolve = function ccsLPSolve(A, B, x, xj, I, Pinv, dfs) {
var Ai = A[0],
Aj = A[1],
Av = A[2],
m = Ai.length - 1,
n = 0;
var Bi = B[0],
Bj = B[1],
Bv = B[2];
var i, i0, i1, j, J, j0, j1, k, l, l0, l1, a;
i0 = Bi[I];
i1 = Bi[I + 1];
xj.length = 0;
for (i = i0; i < i1; ++i) {
dfs.dfs(Pinv[Bj[i]], Ai, Aj, x, xj, Pinv);
}
for (i = xj.length - 1; i !== -1; --i) {
x[xj[i]] = 0;
}
for (i = i0; i !== i1; ++i) {
j = Pinv[Bj[i]];
x[j] = Bv[i];
}
for (i = xj.length - 1; i !== -1; --i) {
j = xj[i];
j0 = Ai[j];
j1 = Ai[j + 1];
for (k = j0; k < j1; ++k) {
if (Pinv[Aj[k]] === j) {
x[j] /= Av[k];
break;
}
}
a = x[j];
for (k = j0; k < j1; ++k) {
l = Pinv[Aj[k]];
if (l !== j) x[l] -= a * Av[k];
}
}
return x;
};
numeric.ccsLUP1 = function ccsLUP1(A, threshold) {
var m = A[0].length - 1;
var L = [numeric.rep([m + 1], 0), [], []],
U = [numeric.rep([m + 1], 0), [], []];
var Li = L[0],
Lj = L[1],
Lv = L[2],
Ui = U[0],
Uj = U[1],
Uv = U[2];
var x = numeric.rep([m], 0),
xj = numeric.rep([m], 0);
var i, j, k, j0, j1, a, e, c, d, K;
var sol = numeric.ccsLPSolve,
max = Math.max,
abs = Math.abs;
var P = numeric.linspace(0, m - 1),
Pinv = numeric.linspace(0, m - 1);
var dfs = new numeric.ccsDFS(m);
if (typeof threshold === "undefined") {
threshold = 1;
}
for (i = 0; i < m; ++i) {
sol(L, A, x, xj, i, Pinv, dfs);
a = -1;
e = -1;
for (j = xj.length - 1; j !== -1; --j) {
k = xj[j];
if (k <= i) continue;
c = abs(x[k]);
if (c > a) {
e = k;
a = c;
}
}
if (abs(x[i]) < threshold * a) {
j = P[i];
a = P[e];
P[i] = a;
Pinv[a] = i;
P[e] = j;
Pinv[j] = e;
a = x[i];
x[i] = x[e];
x[e] = a;
}
a = Li[i];
e = Ui[i];
d = x[i];
Lj[a] = P[i];
Lv[a] = 1;
++a;
for (j = xj.length - 1; j !== -1; --j) {
k = xj[j];
c = x[k];
xj[j] = 0;
x[k] = 0;
if (k <= i) {
Uj[e] = k;
Uv[e] = c;
++e;
} else {
Lj[a] = P[k];
Lv[a] = c / d;
++a;
}
}
Li[i + 1] = a;
Ui[i + 1] = e;
}
for (j = Lj.length - 1; j !== -1; --j) {
Lj[j] = Pinv[Lj[j]];
}
return { L: L, U: U, P: P, Pinv: Pinv };
};
numeric.ccsDFS0 = function ccsDFS0(n) {
this.k = Array(n);
this.k1 = Array(n);
this.j = Array(n);
};
numeric.ccsDFS0.prototype.dfs = function dfs(J, Ai, Aj, x, xj, Pinv, P) {
var m = 0,
foo,
n = xj.length;
var k = this.k,
k1 = this.k1,
j = this.j,
km,
k11;
if (x[J] !== 0) return;
x[J] = 1;
j[0] = J;
k[0] = km = Ai[Pinv[J]];
k1[0] = k11 = Ai[Pinv[J] + 1];
while (1) {
if (isNaN(km)) throw new Error("Ow!");
if (km >= k11) {
xj[n] = Pinv[j[m]];
if (m === 0) return;
++n;
--m;
km = k[m];
k11 = k1[m];
} else {
foo = Aj[km];
if (x[foo] === 0) {
x[foo] = 1;
k[m] = km;
++m;
j[m] = foo;
foo = Pinv[foo];
km = Ai[foo];
k1[m] = k11 = Ai[foo + 1];
} else ++km;
}
}
};
numeric.ccsLPSolve0 = function ccsLPSolve0(A, B, y, xj, I, Pinv, P, dfs) {
var Ai = A[0],
Aj = A[1],
Av = A[2],
m = Ai.length - 1,
n = 0;
var Bi = B[0],
Bj = B[1],
Bv = B[2];
var i, i0, i1, j, J, j0, j1, k, l, l0, l1, a;
i0 = Bi[I];
i1 = Bi[I + 1];
xj.length = 0;
for (i = i0; i < i1; ++i) {
dfs.dfs(Bj[i], Ai, Aj, y, xj, Pinv, P);
}
for (i = xj.length - 1; i !== -1; --i) {
j = xj[i];
y[P[j]] = 0;
}
for (i = i0; i !== i1; ++i) {
j = Bj[i];
y[j] = Bv[i];
}
for (i = xj.length - 1; i !== -1; --i) {
j = xj[i];
l = P[j];
j0 = Ai[j];
j1 = Ai[j + 1];
for (k = j0; k < j1; ++k) {
if (Aj[k] === l) {
y[l] /= Av[k];
break;
}
}
a = y[l];
for (k = j0; k < j1; ++k) y[Aj[k]] -= a * Av[k];
y[l] = a;
}
};
numeric.ccsLUP0 = function ccsLUP0(A, threshold) {
var m = A[0].length - 1;
var L = [numeric.rep([m + 1], 0), [], []],
U = [numeric.rep([m + 1], 0), [], []];
var Li = L[0],
Lj = L[1],
Lv = L[2],
Ui = U[0],
Uj = U[1],
Uv = U[2];
var y = numeric.rep([m], 0),
xj = numeric.rep([m], 0);
var i, j, k, j0, j1, a, e, c, d, K;
var sol = numeric.ccsLPSolve0,
max = Math.max,
abs = Math.abs;
var P = numeric.linspace(0, m - 1),
Pinv = numeric.linspace(0, m - 1);
var dfs = new numeric.ccsDFS0(m);
if (typeof threshold === "undefined") {
threshold = 1;
}
for (i = 0; i < m; ++i) {
sol(L, A, y, xj, i, Pinv, P, dfs);
a = -1;
e = -1;
for (j = xj.length - 1; j !== -1; --j) {
k = xj[j];
if (k <= i) continue;
c = abs(y[P[k]]);
if (c > a) {
e = k;
a = c;
}
}
if (abs(y[P[i]]) < threshold * a) {
j = P[i];
a = P[e];
P[i] = a;
Pinv[a] = i;
P[e] = j;
Pinv[j] = e;
}
a = Li[i];
e = Ui[i];
d = y[P[i]];
Lj[a] = P[i];
Lv[a] = 1;
++a;
for (j = xj.length - 1; j !== -1; --j) {
k = xj[j];
c = y[P[k]];
xj[j] = 0;
y[P[k]] = 0;
if (k <= i) {
Uj[e] = k;
Uv[e] = c;
++e;
} else {
Lj[a] = P[k];
Lv[a] = c / d;
++a;
}
}
Li[i + 1] = a;
Ui[i + 1] = e;
}
for (j = Lj.length - 1; j !== -1; --j) {
Lj[j] = Pinv[Lj[j]];
}
return { L: L, U: U, P: P, Pinv: Pinv };
};
numeric.ccsLUP = numeric.ccsLUP0;
numeric.ccsDim = function ccsDim(A) {
return [numeric.sup(A[1]) + 1, A[0].length - 1];
};
numeric.ccsGetBlock = function ccsGetBlock(A, i, j) {
var s = numeric.ccsDim(A),
m = s[0],
n = s[1];
if (typeof i === "undefined") {
i = numeric.linspace(0, m - 1);
} else if (typeof i === "number") {
i = [i];
}
if (typeof j === "undefined") {
j = numeric.linspace(0, n - 1);
} else if (typeof j === "number") {
j = [j];
}
var p,
p0,
p1,
P = i.length,
q,
Q = j.length,
r,
jq,
ip;
var Bi = numeric.rep([n], 0),
Bj = [],
Bv = [],
B = [Bi, Bj, Bv];
var Ai = A[0],
Aj = A[1],
Av = A[2];
var x = numeric.rep([m], 0),
count = 0,
flags = numeric.rep([m], 0);
for (q = 0; q < Q; ++q) {
jq = j[q];
var q0 = Ai[jq];
var q1 = Ai[jq + 1];
for (p = q0; p < q1; ++p) {
r = Aj[p];
flags[r] = 1;
x[r] = Av[p];
}
for (p = 0; p < P; ++p) {
ip = i[p];
if (flags[ip]) {
Bj[count] = p;
Bv[count] = x[i[p]];
++count;
}
}
for (p = q0; p < q1; ++p) {
r = Aj[p];
flags[r] = 0;
}
Bi[q + 1] = count;
}
return B;
};
numeric.ccsDot = function ccsDot(A, B) {
var Ai = A[0],
Aj = A[1],
Av = A[2];
var Bi = B[0],
Bj = B[1],
Bv = B[2];
var sA = numeric.ccsDim(A),
sB = numeric.ccsDim(B);
var m = sA[0],
n = sA[1],
o = sB[1];
var x = numeric.rep([m], 0),
flags = numeric.rep([m], 0),
xj = Array(m);
var Ci = numeric.rep([o], 0),
Cj = [],
Cv = [],
C = [Ci, Cj, Cv];
var i, j, k, j0, j1, i0, i1, l, p, a, b;
for (k = 0; k !== o; ++k) {
j0 = Bi[k];
j1 = Bi[k + 1];
p = 0;
for (j = j0; j < j1; ++j) {
a = Bj[j];
b = Bv[j];
i0 = Ai[a];
i1 = Ai[a + 1];
for (i = i0; i < i1; ++i) {
l = Aj[i];
if (flags[l] === 0) {
xj[p] = l;
flags[l] = 1;
p = p + 1;
}
x[l] = x[l] + Av[i] * b;
}
}
j0 = Ci[k];
j1 = j0 + p;
Ci[k + 1] = j1;
for (j = p - 1; j !== -1; --j) {
b = j0 + j;
i = xj[j];
Cj[b] = i;
Cv[b] = x[i];
flags[i] = 0;
x[i] = 0;
}
Ci[k + 1] = Ci[k] + p;
}
return C;
};
numeric.ccsLUPSolve = function ccsLUPSolve(LUP, B) {
var L = LUP.L,
U = LUP.U,
P = LUP.P;
var Bi = B[0];
var flag = false;
if (typeof Bi !== "object") {
B = [[0, B.length], numeric.linspace(0, B.length - 1), B];
Bi = B[0];
flag = true;
}
var Bj = B[1],
Bv = B[2];
var n = L[0].length - 1,
m = Bi.length - 1;
var x = numeric.rep([n], 0),
xj = Array(n);
var b = numeric.rep([n], 0),
bj = Array(n);
var Xi = numeric.rep([m + 1], 0),
Xj = [],
Xv = [];
var sol = numeric.ccsTSolve;
var i,
j,
j0,
j1,
k,
J,
N = 0;
for (i = 0; i < m; ++i) {
k = 0;
j0 = Bi[i];
j1 = Bi[i + 1];
for (j = j0; j < j1; ++j) {
J = LUP.Pinv[Bj[j]];
bj[k] = J;
b[J] = Bv[j];
++k;
}
bj.length = k;
sol(L, b, x, bj, xj);
for (j = bj.length - 1; j !== -1; --j) b[bj[j]] = 0;
sol(U, x, b, xj, bj);
if (flag) return b;
for (j = xj.length - 1; j !== -1; --j) x[xj[j]] = 0;
for (j = bj.length - 1; j !== -1; --j) {
J = bj[j];
Xj[N] = J;
Xv[N] = b[J];
b[J] = 0;
++N;
}
Xi[i + 1] = N;
}
return [Xi, Xj, Xv];
};
numeric.ccsbinop = function ccsbinop(body, setup) {
if (typeof setup === "undefined") setup = "";
return Function(
"X",
"Y",
"var Xi = X[0], Xj = X[1], Xv = X[2];\n" +
"var Yi = Y[0], Yj = Y[1], Yv = Y[2];\n" +
"var n = Xi.length-1,m = Math.max(numeric.sup(Xj),numeric.sup(Yj))+1;\n" +
"var Zi = numeric.rep([n+1],0), Zj = [], Zv = [];\n" +
"var x = numeric.rep([m],0),y = numeric.rep([m],0);\n" +
"var xk,yk,zk;\n" +
"var i,j,j0,j1,k,p=0;\n" +
setup +
"for(i=0;i<n;++i) {\n" +
" j0 = Xi[i]; j1 = Xi[i+1];\n" +
" for(j=j0;j!==j1;++j) {\n" +
" k = Xj[j];\n" +
" x[k] = 1;\n" +
" Zj[p] = k;\n" +
" ++p;\n" +
" }\n" +
" j0 = Yi[i]; j1 = Yi[i+1];\n" +
" for(j=j0;j!==j1;++j) {\n" +
" k = Yj[j];\n" +
" y[k] = Yv[j];\n" +
" if(x[k] === 0) {\n" +
" Zj[p] = k;\n" +
" ++p;\n" +
" }\n" +
" }\n" +
" Zi[i+1] = p;\n" +
" j0 = Xi[i]; j1 = Xi[i+1];\n" +
" for(j=j0;j!==j1;++j) x[Xj[j]] = Xv[j];\n" +
" j0 = Zi[i]; j1 = Zi[i+1];\n" +
" for(j=j0;j!==j1;++j) {\n" +
" k = Zj[j];\n" +
" xk = x[k];\n" +
" yk = y[k];\n" +
body +
"\n" +
" Zv[j] = zk;\n" +
" }\n" +
" j0 = Xi[i]; j1 = Xi[i+1];\n" +
" for(j=j0;j!==j1;++j) x[Xj[j]] = 0;\n" +
" j0 = Yi[i]; j1 = Yi[i+1];\n" +
" for(j=j0;j!==j1;++j) y[Yj[j]] = 0;\n" +
"}\n" +
"return [Zi,Zj,Zv];"
);
};
(function () {
var k, A, B, C;
for (k in numeric.ops2) {
if (isFinite(eval("1" + numeric.ops2[k] + "0")))
A = "[Y[0],Y[1],numeric." + k + "(X,Y[2])]";
else A = "NaN";
if (isFinite(eval("0" + numeric.ops2[k] + "1")))
B = "[X[0],X[1],numeric." + k + "(X[2],Y)]";
else B = "NaN";
if (
isFinite(eval("1" + numeric.ops2[k] + "0")) &&
isFinite(eval("0" + numeric.ops2[k] + "1"))
)
C = "numeric.ccs" + k + "MM(X,Y)";
else C = "NaN";
numeric["ccs" + k + "MM"] = numeric.ccsbinop("zk = xk " + numeric.ops2[k] + "yk;");
numeric["ccs" + k] = Function(
"X",
"Y",
'if(typeof X === "number") return ' +
A +
";\n" +
'if(typeof Y === "number") return ' +
B +
";\n" +
"return " +
C +
";\n"
);
}
})();
numeric.ccsScatter = function ccsScatter(A) {
var Ai = A[0],
Aj = A[1],
Av = A[2];
var n = numeric.sup(Aj) + 1,
m = Ai.length;
var Ri = numeric.rep([n], 0),
Rj = Array(m),
Rv = Array(m);
var counts = numeric.rep([n], 0),
i;
for (i = 0; i < m; ++i) counts[Aj[i]]++;
for (i = 0; i < n; ++i) Ri[i + 1] = Ri[i] + counts[i];
var ptr = Ri.slice(0),
k,
Aii;
for (i = 0; i < m; ++i) {
Aii = Aj[i];
k = ptr[Aii];
Rj[k] = Ai[i];
Rv[k] = Av[i];
ptr[Aii] = ptr[Aii] + 1;
}
return [Ri, Rj, Rv];
};
numeric.ccsGather = function ccsGather(A) {
var Ai = A[0],
Aj = A[1],
Av = A[2];
var n = Ai.length - 1,
m = Aj.length;
var Ri = Array(m),
Rj = Array(m),
Rv = Array(m);
var i, j, j0, j1, p;
p = 0;
for (i = 0; i < n; ++i) {
j0 = Ai[i];
j1 = Ai[i + 1];
for (j = j0; j !== j1; ++j) {
Rj[p] = i;
Ri[p] = Aj[j];
Rv[p] = Av[j];
++p;
}
}
return [Ri, Rj, Rv];
};
// The following sparse linear algebra routines are deprecated.
numeric.sdim = function dim(A, ret, k) {
if (typeof ret === "undefined") {
ret = [];
}
if (typeof A !== "object") return ret;
if (typeof k === "undefined") {
k = 0;
}
if (!(k in ret)) {
ret[k] = 0;
}
if (A.length > ret[k]) ret[k] = A.length;
var i;
for (i in A) {
if (A.hasOwnProperty(i)) dim(A[i], ret, k + 1);
}
return ret;
};
numeric.sclone = function clone(A, k, n) {
if (typeof k === "undefined") {
k = 0;
}
if (typeof n === "undefined") {
n = numeric.sdim(A).length;
}
var i,
ret = Array(A.length);
if (k === n - 1) {
for (i in A) {
if (A.hasOwnProperty(i)) ret[i] = A[i];
}
return ret;
}
for (i in A) {
if (A.hasOwnProperty(i)) ret[i] = clone(A[i], k + 1, n);
}
return ret;
};
numeric.sdiag = function diag(d) {
var n = d.length,
i,
ret = Array(n),
i1,
i2,
i3;
for (i = n - 1; i >= 1; i -= 2) {
i1 = i - 1;
ret[i] = [];
ret[i][i] = d[i];
ret[i1] = [];
ret[i1][i1] = d[i1];
}
if (i === 0) {
ret[0] = [];
ret[0][0] = d[i];
}
return ret;
};
numeric.sidentity = function identity(n) {
return numeric.sdiag(numeric.rep([n], 1));
};
numeric.stranspose = function transpose(A) {
var ret = [],
n = A.length,
i,
j,
Ai;
for (i in A) {
if (!A.hasOwnProperty(i)) continue;
Ai = A[i];
for (j in Ai) {
if (!Ai.hasOwnProperty(j)) continue;
if (typeof ret[j] !== "object") {
ret[j] = [];
}
ret[j][i] = Ai[j];
}
}
return ret;
};
numeric.sLUP = function LUP(A, tol) {
throw new Error(
"The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead."
);
};
numeric.sdotMM = function dotMM(A, B) {
var p = A.length,
q = B.length,
BT = numeric.stranspose(B),
r = BT.length,
Ai,
BTk;
var i, j, k, accum;
var ret = Array(p),
reti;
for (i = p - 1; i >= 0; i--) {
reti = [];
Ai = A[i];
for (k = r - 1; k >= 0; k--) {
accum = 0;
BTk = BT[k];
for (j in Ai) {
if (!Ai.hasOwnProperty(j)) continue;
if (j in BTk) {
accum += Ai[j] * BTk[j];
}
}
if (accum) reti[k] = accum;
}
ret[i] = reti;
}
return ret;
};
numeric.sdotMV = function dotMV(A, x) {
var p = A.length,
Ai,
i,
j;
var ret = Array(p),
accum;
for (i = p - 1; i >= 0; i--) {
Ai = A[i];
accum = 0;
for (j in Ai) {
if (!Ai.hasOwnProperty(j)) continue;
if (x[j]) accum += Ai[j] * x[j];
}
if (accum) ret[i] = accum;
}
return ret;
};
numeric.sdotVM = function dotMV(x, A) {
var i, j, Ai, alpha;
var ret = [],
accum;
for (i in x) {
if (!x.hasOwnProperty(i)) continue;
Ai = A[i];
alpha = x[i];
for (j in Ai) {
if (!Ai.hasOwnProperty(j)) continue;
if (!ret[j]) {
ret[j] = 0;
}
ret[j] += alpha * Ai[j];
}
}
return ret;
};
numeric.sdotVV = function dotVV(x, y) {
var i,
ret = 0;
for (i in x) {
if (x[i] && y[i]) ret += x[i] * y[i];
}
return ret;
};
numeric.sdot = function dot(A, B) {
var m = numeric.sdim(A).length,
n = numeric.sdim(B).length;
var k = m * 1000 + n;
switch (k) {
case 0:
return A * B;
case 1001:
return numeric.sdotVV(A, B);
case 2001:
return numeric.sdotMV(A, B);
case 1002:
return numeric.sdotVM(A, B);
case 2002:
return numeric.sdotMM(A, B);
default:
throw new Error(
"numeric.sdot not implemented for tensors of order " + m + " and " + n
);
}
};
numeric.sscatter = function scatter(V) {
var n = V[0].length,
Vij,
i,
j,
m = V.length,
A = [],
Aj;
for (i = n - 1; i >= 0; --i) {
if (!V[m - 1][i]) continue;
Aj = A;
for (j = 0; j < m - 2; j++) {
Vij = V[j][i];
if (!Aj[Vij]) Aj[Vij] = [];
Aj = Aj[Vij];
}
Aj[V[j][i]] = V[j + 1][i];
}
return A;
};
numeric.sgather = function gather(A, ret, k) {
if (typeof ret === "undefined") ret = [];
if (typeof k === "undefined") k = [];
var n, i, Ai;
n = k.length;
for (i in A) {
if (A.hasOwnProperty(i)) {
k[n] = parseInt(i);
Ai = A[i];
if (typeof Ai === "number") {
if (Ai) {
if (ret.length === 0) {
for (i = n + 1; i >= 0; --i) ret[i] = [];
}
for (i = n; i >= 0; --i) ret[i].push(k[i]);
ret[n + 1].push(Ai);
}
} else gather(Ai, ret, k);
}
}
if (k.length > n) k.pop();
return ret;
};
// 6. Coordinate matrices
numeric.cLU = function LU(A) {
var I = A[0],
J = A[1],
V = A[2];
var p = I.length,
m = 0,
i,
j,
k,
a,
b,
c;
for (i = 0; i < p; i++) if (I[i] > m) m = I[i];
m++;
var L = Array(m),
U = Array(m),
left = numeric.rep([m], Infinity),
right = numeric.rep([m], -Infinity);
var Ui, Uj, alpha;
for (k = 0; k < p; k++) {
i = I[k];
j = J[k];
if (j < left[i]) left[i] = j;
if (j > right[i]) right[i] = j;
}
for (i = 0; i < m - 1; i++) {
if (right[i] > right[i + 1]) right[i + 1] = right[i];
}
for (i = m - 1; i >= 1; i--) {
if (left[i] < left[i - 1]) left[i - 1] = left[i];
}
var countL = 0,
countU = 0;
for (i = 0; i < m; i++) {
U[i] = numeric.rep([right[i] - left[i] + 1], 0);
L[i] = numeric.rep([i - left[i]], 0);
countL += i - left[i] + 1;
countU += right[i] - i + 1;
}
for (k = 0; k < p; k++) {
i = I[k];
U[i][J[k] - left[i]] = V[k];
}
for (i = 0; i < m - 1; i++) {
a = i - left[i];
Ui = U[i];
for (j = i + 1; left[j] <= i && j < m; j++) {
b = i - left[j];
c = right[i] - i;
Uj = U[j];
alpha = Uj[b] / Ui[a];
if (alpha) {
for (k = 1; k <= c; k++) {
Uj[k + b] -= alpha * Ui[k + a];
}
L[j][i - left[j]] = alpha;
}
}
}
var Ui = [],
Uj = [],
Uv = [],
Li = [],
Lj = [],
Lv = [];
var p, q, foo;
p = 0;
q = 0;
for (i = 0; i < m; i++) {
a = left[i];
b = right[i];
foo = U[i];
for (j = i; j <= b; j++) {
if (foo[j - a]) {
Ui[p] = i;
Uj[p] = j;
Uv[p] = foo[j - a];
p++;
}
}
foo = L[i];
for (j = a; j < i; j++) {
if (foo[j - a]) {
Li[q] = i;
Lj[q] = j;
Lv[q] = foo[j - a];
q++;
}
}
Li[q] = i;
Lj[q] = i;
Lv[q] = 1;
q++;
}
return { U: [Ui, Uj, Uv], L: [Li, Lj, Lv] };
};
numeric.cLUsolve = function LUsolve(lu, b) {
var L = lu.L,
U = lu.U,
ret = numeric.clone(b);
var Li = L[0],
Lj = L[1],
Lv = L[2];
var Ui = U[0],
Uj = U[1],
Uv = U[2];
var p = Ui.length,
q = Li.length;
var m = ret.length,
i,
j,
k;
k = 0;
for (i = 0; i < m; i++) {
while (Lj[k] < i) {
ret[i] -= Lv[k] * ret[Lj[k]];
k++;
}
k++;
}
k = p - 1;
for (i = m - 1; i >= 0; i--) {
while (Uj[k] > i) {
ret[i] -= Uv[k] * ret[Uj[k]];
k--;
}
ret[i] /= Uv[k];
k--;
}
return ret;
};
numeric.cgrid = function grid(n, shape) {
if (typeof n === "number") n = [n, n];
var ret = numeric.rep(n, -1);
var i, j, count;
if (typeof shape !== "function") {
switch (shape) {
case "L":
shape = function (i, j) {
return i >= n[0] / 2 || j < n[1] / 2;
};
break;
default:
shape = function (i, j) {
return true;
};
break;
}
}
count = 0;
for (i = 1; i < n[0] - 1; i++)
for (j = 1; j < n[1] - 1; j++)
if (shape(i, j)) {
ret[i][j] = count;
count++;
}
return ret;
};
numeric.cdelsq = function delsq(g) {
var dir = [
[-1, 0],
[0, -1],
[0, 1],
[1, 0],
];
var s = numeric.dim(g),
m = s[0],
n = s[1],
i,
j,
k,
p,
q;
var Li = [],
Lj = [],
Lv = [];
for (i = 1; i < m - 1; i++)
for (j = 1; j < n - 1; j++) {
if (g[i][j] < 0) continue;
for (k = 0; k < 4; k++) {
p = i + dir[k][0];
q = j + dir[k][1];
if (g[p][q] < 0) continue;
Li.push(g[i][j]);
Lj.push(g[p][q]);
Lv.push(-1);
}
Li.push(g[i][j]);
Lj.push(g[i][j]);
Lv.push(4);
}
return [Li, Lj, Lv];
};
numeric.cdotMV = function dotMV(A, x) {
var ret,
Ai = A[0],
Aj = A[1],
Av = A[2],
k,
p = Ai.length,
N;
N = 0;
for (k = 0; k < p; k++) {
if (Ai[k] > N) N = Ai[k];
}
N++;
ret = numeric.rep([N], 0);
for (k = 0; k < p; k++) {
ret[Ai[k]] += Av[k] * x[Aj[k]];
}
return ret;
};
// 7. Splines
numeric.Spline = function Spline(x, yl, yr, kl, kr) {
this.x = x;
this.yl = yl;
this.yr = yr;
this.kl = kl;
this.kr = kr;
};
numeric.Spline.prototype._at = function _at(x1, p) {
var x = this.x;
var yl = this.yl;
var yr = this.yr;
var kl = this.kl;
var kr = this.kr;
var x1, a, b, t;
var add = numeric.add,
sub = numeric.sub,
mul = numeric.mul;
a = sub(mul(kl[p], x[p + 1] - x[p]), sub(yr[p + 1], yl[p]));
b = add(mul(kr[p + 1], x[p] - x[p + 1]), sub(yr[p + 1], yl[p]));
t = (x1 - x[p]) / (x[p + 1] - x[p]);
var s = t * (1 - t);
return add(
add(add(mul(1 - t, yl[p]), mul(t, yr[p + 1])), mul(a, s * (1 - t))),
mul(b, s * t)
);
};
numeric.Spline.prototype.at = function at(x0) {
if (typeof x0 === "number") {
var x = this.x;
var n = x.length;
var p,
q,
mid,
floor = Math.floor,
a,
b,
t;
p = 0;
q = n - 1;
while (q - p > 1) {
mid = floor((p + q) / 2);
if (x[mid] <= x0) p = mid;
else q = mid;
}
return this._at(x0, p);
}
var n = x0.length,
i,
ret = Array(n);
for (i = n - 1; i !== -1; --i) ret[i] = this.at(x0[i]);
return ret;
};
numeric.Spline.prototype.diff = function diff() {
var x = this.x;
var yl = this.yl;
var yr = this.yr;
var kl = this.kl;
var kr = this.kr;
var n = yl.length;
var i, dx, dy;
var zl = kl,
zr = kr,
pl = Array(n),
pr = Array(n);
var add = numeric.add,
mul = numeric.mul,
div = numeric.div,
sub = numeric.sub;
for (i = n - 1; i !== -1; --i) {
dx = x[i + 1] - x[i];
dy = sub(yr[i + 1], yl[i]);
pl[i] = div(add(mul(dy, 6), mul(kl[i], -4 * dx), mul(kr[i + 1], -2 * dx)), dx * dx);
pr[i + 1] = div(add(mul(dy, -6), mul(kl[i], 2 * dx), mul(kr[i + 1], 4 * dx)), dx * dx);
}
return new numeric.Spline(x, zl, zr, pl, pr);
};
numeric.Spline.prototype.roots = function roots() {
function sqr(x) {
return x * x;
}
function heval(y0, y1, k0, k1, x) {
var A = k0 * 2 - (y1 - y0);
var B = -k1 * 2 + (y1 - y0);
var t = (x + 1) * 0.5;
var s = t * (1 - t);
return (1 - t) * y0 + t * y1 + A * s * (1 - t) + B * s * t;
}
var ret = [];
var x = this.x,
yl = this.yl,
yr = this.yr,
kl = this.kl,
kr = this.kr;
if (typeof yl[0] === "number") {
yl = [yl];
yr = [yr];
kl = [kl];
kr = [kr];
}
var m = yl.length,
n = x.length - 1,
i,
j,
k,
y,
s,
t;
var ai,
bi,
ci,
di,
ret = Array(m),
ri,
k0,
k1,
y0,
y1,
A,
B,
D,
dx,
cx,
stops,
z0,
z1,
zm,
t0,
t1,
tm;
var sqrt = Math.sqrt;
for (i = 0; i !== m; ++i) {
ai = yl[i];
bi = yr[i];
ci = kl[i];
di = kr[i];
ri = [];
for (j = 0; j !== n; j++) {
if (j > 0 && bi[j] * ai[j] < 0) ri.push(x[j]);
dx = x[j + 1] - x[j];
cx = x[j];
y0 = ai[j];
y1 = bi[j + 1];
k0 = ci[j] / dx;
k1 = di[j + 1] / dx;
D = sqr(k0 - k1 + 3 * (y0 - y1)) + 12 * k1 * y0;
A = k1 + 3 * y0 + 2 * k0 - 3 * y1;
B = 3 * (k1 + k0 + 2 * (y0 - y1));
if (D <= 0) {
z0 = A / B;
if (z0 > x[j] && z0 < x[j + 1]) stops = [x[j], z0, x[j + 1]];
else stops = [x[j], x[j + 1]];
} else {
z0 = (A - sqrt(D)) / B;
z1 = (A + sqrt(D)) / B;
stops = [x[j]];
if (z0 > x[j] && z0 < x[j + 1]) stops.push(z0);
if (z1 > x[j] && z1 < x[j + 1]) stops.push(z1);
stops.push(x[j + 1]);
}
t0 = stops[0];
z0 = this._at(t0, j);
for (k = 0; k < stops.length - 1; k++) {
t1 = stops[k + 1];
z1 = this._at(t1, j);
if (z0 === 0) {
ri.push(t0);
t0 = t1;
z0 = z1;
continue;
}
if (z1 === 0 || z0 * z1 > 0) {
t0 = t1;
z0 = z1;
continue;
}
var side = 0;
while (1) {
tm = (z0 * t1 - z1 * t0) / (z0 - z1);
if (tm <= t0 || tm >= t1) {
break;
}
zm = this._at(tm, j);
if (zm * z1 > 0) {
t1 = tm;
z1 = zm;
if (side === -1) z0 *= 0.5;
side = -1;
} else if (zm * z0 > 0) {
t0 = tm;
z0 = zm;
if (side === 1) z1 *= 0.5;
side = 1;
} else break;
}
ri.push(tm);
t0 = stops[k + 1];
z0 = this._at(t0, j);
}
if (z1 === 0) ri.push(t1);
}
ret[i] = ri;
}
if (typeof this.yl[0] === "number") return ret[0];
return ret;
};
numeric.spline = function spline(x, y, k1, kn) {
var n = x.length,
b = [],
dx = [],
dy = [];
var i;
var sub = numeric.sub,
mul = numeric.mul,
add = numeric.add;
for (i = n - 2; i >= 0; i--) {
dx[i] = x[i + 1] - x[i];
dy[i] = sub(y[i + 1], y[i]);
}
if (typeof k1 === "string" || typeof kn === "string") {
k1 = kn = "periodic";
}
// Build sparse tridiagonal system
var T = [[], [], []];
switch (typeof k1) {
case "undefined":
b[0] = mul(3 / (dx[0] * dx[0]), dy[0]);
T[0].push(0, 0);
T[1].push(0, 1);
T[2].push(2 / dx[0], 1 / dx[0]);
break;
case "string":
b[0] = add(
mul(3 / (dx[n - 2] * dx[n - 2]), dy[n - 2]),
mul(3 / (dx[0] * dx[0]), dy[0])
);
T[0].push(0, 0, 0);
T[1].push(n - 2, 0, 1);
T[2].push(1 / dx[n - 2], 2 / dx[n - 2] + 2 / dx[0], 1 / dx[0]);
break;
default:
b[0] = k1;
T[0].push(0);
T[1].push(0);
T[2].push(1);
break;
}
for (i = 1; i < n - 1; i++) {
b[i] = add(
mul(3 / (dx[i - 1] * dx[i - 1]), dy[i - 1]),
mul(3 / (dx[i] * dx[i]), dy[i])
);
T[0].push(i, i, i);
T[1].push(i - 1, i, i + 1);
T[2].push(1 / dx[i - 1], 2 / dx[i - 1] + 2 / dx[i], 1 / dx[i]);
}
switch (typeof kn) {
case "undefined":
b[n - 1] = mul(3 / (dx[n - 2] * dx[n - 2]), dy[n - 2]);
T[0].push(n - 1, n - 1);
T[1].push(n - 2, n - 1);
T[2].push(1 / dx[n - 2], 2 / dx[n - 2]);
break;
case "string":
T[1][T[1].length - 1] = 0;
break;
default:
b[n - 1] = kn;
T[0].push(n - 1);
T[1].push(n - 1);
T[2].push(1);
break;
}
if (typeof b[0] !== "number") b = numeric.transpose(b);
else b = [b];
var k = Array(b.length);
if (typeof k1 === "string") {
for (i = k.length - 1; i !== -1; --i) {
k[i] = numeric.ccsLUPSolve(numeric.ccsLUP(numeric.ccsScatter(T)), b[i]);
k[i][n - 1] = k[i][0];
}
} else {
for (i = k.length - 1; i !== -1; --i) {
k[i] = numeric.cLUsolve(numeric.cLU(T), b[i]);
}
}
if (typeof y[0] === "number") k = k[0];
else k = numeric.transpose(k);
return new numeric.Spline(x, y, y, k, k);
};
// 8. FFT
numeric.fftpow2 = function fftpow2(x, y) {
var n = x.length;
if (n === 1) return;
var cos = Math.cos,
sin = Math.sin,
i,
j;
var xe = Array(n / 2),
ye = Array(n / 2),
xo = Array(n / 2),
yo = Array(n / 2);
j = n / 2;
for (i = n - 1; i !== -1; --i) {
--j;
xo[j] = x[i];
yo[j] = y[i];
--i;
xe[j] = x[i];
ye[j] = y[i];
}
fftpow2(xe, ye);
fftpow2(xo, yo);
j = n / 2;
var t,
k = -6.2831853071795864769252867665590057683943387987502116419 / n,
ci,
si;
for (i = n - 1; i !== -1; --i) {
--j;
if (j === -1) j = n / 2 - 1;
t = k * i;
ci = cos(t);
si = sin(t);
x[i] = xe[j] + ci * xo[j] - si * yo[j];
y[i] = ye[j] + ci * yo[j] + si * xo[j];
}
};
numeric._ifftpow2 = function _ifftpow2(x, y) {
var n = x.length;
if (n === 1) return;
var cos = Math.cos,
sin = Math.sin,
i,
j;
var xe = Array(n / 2),
ye = Array(n / 2),
xo = Array(n / 2),
yo = Array(n / 2);
j = n / 2;
for (i = n - 1; i !== -1; --i) {
--j;
xo[j] = x[i];
yo[j] = y[i];
--i;
xe[j] = x[i];
ye[j] = y[i];
}
_ifftpow2(xe, ye);
_ifftpow2(xo, yo);
j = n / 2;
var t,
k = 6.2831853071795864769252867665590057683943387987502116419 / n,
ci,
si;
for (i = n - 1; i !== -1; --i) {
--j;
if (j === -1) j = n / 2 - 1;
t = k * i;
ci = cos(t);
si = sin(t);
x[i] = xe[j] + ci * xo[j] - si * yo[j];
y[i] = ye[j] + ci * yo[j] + si * xo[j];
}
};
numeric.ifftpow2 = function ifftpow2(x, y) {
numeric._ifftpow2(x, y);
numeric.diveq(x, x.length);
numeric.diveq(y, y.length);
};
numeric.convpow2 = function convpow2(ax, ay, bx, by) {
numeric.fftpow2(ax, ay);
numeric.fftpow2(bx, by);
var i,
n = ax.length,
axi,
bxi,
ayi,
byi;
for (i = n - 1; i !== -1; --i) {
axi = ax[i];
ayi = ay[i];
bxi = bx[i];
byi = by[i];
ax[i] = axi * bxi - ayi * byi;
ay[i] = axi * byi + ayi * bxi;
}
numeric.ifftpow2(ax, ay);
};
numeric.T.prototype.fft = function fft() {
var x = this.x,
y = this.y;
var n = x.length,
log = Math.log,
log2 = log(2),
p = Math.ceil(log(2 * n - 1) / log2),
m = Math.pow(2, p);
var cx = numeric.rep([m], 0),
cy = numeric.rep([m], 0),
cos = Math.cos,
sin = Math.sin;
var k,
c = -3.14159265358979323846264338327950288419716939937510582 / n,
t;
var a = numeric.rep([m], 0),
b = numeric.rep([m], 0),
nhalf = Math.floor(n / 2);
for (k = 0; k < n; k++) a[k] = x[k];
if (typeof y !== "undefined") for (k = 0; k < n; k++) b[k] = y[k];
cx[0] = 1;
for (k = 1; k <= m / 2; k++) {
t = c * k * k;
cx[k] = cos(t);
cy[k] = sin(t);
cx[m - k] = cos(t);
cy[m - k] = sin(t);
}
var X = new numeric.T(a, b),
Y = new numeric.T(cx, cy);
X = X.mul(Y);
numeric.convpow2(X.x, X.y, numeric.clone(Y.x), numeric.neg(Y.y));
X = X.mul(Y);
X.x.length = n;
X.y.length = n;
return X;
};
numeric.T.prototype.ifft = function ifft() {
var x = this.x,
y = this.y;
var n = x.length,
log = Math.log,
log2 = log(2),
p = Math.ceil(log(2 * n - 1) / log2),
m = Math.pow(2, p);
var cx = numeric.rep([m], 0),
cy = numeric.rep([m], 0),
cos = Math.cos,
sin = Math.sin;
var k,
c = 3.14159265358979323846264338327950288419716939937510582 / n,
t;
var a = numeric.rep([m], 0),
b = numeric.rep([m], 0),
nhalf = Math.floor(n / 2);
for (k = 0; k < n; k++) a[k] = x[k];
if (typeof y !== "undefined") for (k = 0; k < n; k++) b[k] = y[k];
cx[0] = 1;
for (k = 1; k <= m / 2; k++) {
t = c * k * k;
cx[k] = cos(t);
cy[k] = sin(t);
cx[m - k] = cos(t);
cy[m - k] = sin(t);
}
var X = new numeric.T(a, b),
Y = new numeric.T(cx, cy);
X = X.mul(Y);
numeric.convpow2(X.x, X.y, numeric.clone(Y.x), numeric.neg(Y.y));
X = X.mul(Y);
X.x.length = n;
X.y.length = n;
return X.div(n);
};
//9. Unconstrained optimization
numeric.gradient = function gradient(f, x) {
var n = x.length;
var f0 = f(x);
if (isNaN(f0)) throw new Error("gradient: f(x) is a NaN!");
var max = Math.max;
var i,
x0 = numeric.clone(x),
f1,
f2,
J = Array(n);
var div = numeric.div,
sub = numeric.sub,
errest,
roundoff,
max = Math.max,
eps = 1e-3,
abs = Math.abs,
min = Math.min;
var t0,
t1,
t2,
it = 0,
d1,
d2,
N;
for (i = 0; i < n; i++) {
var h = max(1e-6 * f0, 1e-8);
while (1) {
++it;
if (it > 20) {
throw new Error("Numerical gradient fails");
}
x0[i] = x[i] + h;
f1 = f(x0);
x0[i] = x[i] - h;
f2 = f(x0);
x0[i] = x[i];
if (isNaN(f1) || isNaN(f2)) {
h /= 16;
continue;
}
J[i] = (f1 - f2) / (2 * h);
t0 = x[i] - h;
t1 = x[i];
t2 = x[i] + h;
d1 = (f1 - f0) / h;
d2 = (f0 - f2) / h;
N = max(abs(J[i]), abs(f0), abs(f1), abs(f2), abs(t0), abs(t1), abs(t2), 1e-8);
errest = min(max(abs(d1 - J[i]), abs(d2 - J[i]), abs(d1 - d2)) / N, h / N);
if (errest > eps) {
h /= 16;
} else break;
}
}
return J;
};
numeric.uncmin = function uncmin(f, x0, tol, gradient, maxit, callback, options) {
var grad = numeric.gradient;
if (typeof options === "undefined") {
options = {};
}
if (typeof tol === "undefined") {
tol = 1e-8;
}
if (typeof gradient === "undefined") {
gradient = function (x) {
return grad(f, x);
};
}
if (typeof maxit === "undefined") maxit = 1000;
x0 = numeric.clone(x0);
var n = x0.length;
var f0 = f(x0),
f1,
df0;
if (isNaN(f0)) throw new Error("uncmin: f(x0) is a NaN!");
var max = Math.max,
norm2 = numeric.norm2;
tol = max(tol, numeric.epsilon);
var step,
g0,
g1,
H1 = options.Hinv || numeric.identity(n);
var dot = numeric.dot,
inv = numeric.inv,
sub = numeric.sub,
add = numeric.add,
ten = numeric.tensor,
div = numeric.div,
mul = numeric.mul;
var all = numeric.all,
isfinite = numeric.isFinite,
neg = numeric.neg;
var it = 0,
i,
s,
x1,
y,
Hy,
Hs,
ys,
i0,
t,
nstep,
t1,
t2;
var msg = "";
g0 = gradient(x0);
while (it < maxit) {
if (typeof callback === "function") {
if (callback(it, x0, f0, g0, H1)) {
msg = "Callback returned true";
break;
}
}
if (!all(isfinite(g0))) {
msg = "Gradient has Infinity or NaN";
break;
}
step = neg(dot(H1, g0));
if (!all(isfinite(step))) {
msg = "Search direction has Infinity or NaN";
break;
}
nstep = norm2(step);
if (nstep < tol) {
msg = "Newton step smaller than tol";
break;
}
t = 1;
df0 = dot(g0, step);
// line search
x1 = x0;
while (it < maxit) {
if (t * nstep < tol) {
break;
}
s = mul(step, t);
x1 = add(x0, s);
f1 = f(x1);
if (f1 - f0 >= 0.1 * t * df0 || isNaN(f1)) {
t *= 0.5;
++it;
continue;
}
break;
}
if (t * nstep < tol) {
msg = "Line search step size smaller than tol";
break;
}
if (it === maxit) {
msg = "maxit reached during line search";
break;
}
g1 = gradient(x1);
y = sub(g1, g0);
ys = dot(y, s);
Hy = dot(H1, y);
H1 = sub(
add(H1, mul((ys + dot(y, Hy)) / (ys * ys), ten(s, s))),
div(add(ten(Hy, s), ten(s, Hy)), ys)
);
x0 = x1;
f0 = f1;
g0 = g1;
++it;
}
return {
solution: x0,
f: f0,
gradient: g0,
invHessian: H1,
iterations: it,
message: msg,
};
};
// 10. Ode solver (Dormand-Prince)
numeric.Dopri = function Dopri(x, y, f, ymid, iterations, msg, events) {
this.x = x;
this.y = y;
this.f = f;
this.ymid = ymid;
this.iterations = iterations;
this.events = events;
this.message = msg;
};
numeric.Dopri.prototype._at = function _at(xi, j) {
function sqr(x) {
return x * x;
}
var sol = this;
var xs = sol.x;
var ys = sol.y;
var k1 = sol.f;
var ymid = sol.ymid;
var n = xs.length;
var x0, x1, xh, y0, y1, yh, xi;
var floor = Math.floor,
h;
var c = 0.5;
var add = numeric.add,
mul = numeric.mul,
sub = numeric.sub,
p,
q,
w;
x0 = xs[j];
x1 = xs[j + 1];
y0 = ys[j];
y1 = ys[j + 1];
h = x1 - x0;
xh = x0 + c * h;
yh = ymid[j];
p = sub(k1[j], mul(y0, 1 / (x0 - xh) + 2 / (x0 - x1)));
q = sub(k1[j + 1], mul(y1, 1 / (x1 - xh) + 2 / (x1 - x0)));
w = [
(sqr(xi - x1) * (xi - xh)) / sqr(x0 - x1) / (x0 - xh),
(sqr(xi - x0) * sqr(xi - x1)) / sqr(x0 - xh) / sqr(x1 - xh),
(sqr(xi - x0) * (xi - xh)) / sqr(x1 - x0) / (x1 - xh),
((xi - x0) * sqr(xi - x1) * (xi - xh)) / sqr(x0 - x1) / (x0 - xh),
((xi - x1) * sqr(xi - x0) * (xi - xh)) / sqr(x0 - x1) / (x1 - xh),
];
return add(
add(add(add(mul(y0, w[0]), mul(yh, w[1])), mul(y1, w[2])), mul(p, w[3])),
mul(q, w[4])
);
};
numeric.Dopri.prototype.at = function at(x) {
var i,
j,
k,
floor = Math.floor;
if (typeof x !== "number") {
var n = x.length,
ret = Array(n);
for (i = n - 1; i !== -1; --i) {
ret[i] = this.at(x[i]);
}
return ret;
}
var x0 = this.x;
i = 0;
j = x0.length - 1;
while (j - i > 1) {
k = floor(0.5 * (i + j));
if (x0[k] <= x) i = k;
else j = k;
}
return this._at(x, i);
};
numeric.dopri = function dopri(x0, x1, y0, f, tol, maxit, event) {
if (typeof tol === "undefined") {
tol = 1e-6;
}
if (typeof maxit === "undefined") {
maxit = 1000;
}
var xs = [x0],
ys = [y0],
k1 = [f(x0, y0)],
k2,
k3,
k4,
k5,
k6,
k7,
ymid = [];
var A2 = 1 / 5;
var A3 = [3 / 40, 9 / 40];
var A4 = [44 / 45, -56 / 15, 32 / 9];
var A5 = [19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729];
var A6 = [9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656];
var b = [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84];
var bm = [
(0.5 * 6025192743) / 30085553152,
0,
(0.5 * 51252292925) / 65400821598,
(0.5 * -2691868925) / 45128329728,
(0.5 * 187940372067) / 1594534317056,
(0.5 * -1776094331) / 19743644256,
(0.5 * 11237099) / 235043384,
];
var c = [1 / 5, 3 / 10, 4 / 5, 8 / 9, 1, 1];
var e = [-71 / 57600, 0, 71 / 16695, -71 / 1920, 17253 / 339200, -22 / 525, 1 / 40];
var i = 0,
er,
j;
var h = (x1 - x0) / 10;
var it = 0;
var add = numeric.add,
mul = numeric.mul,
y1,
erinf;
var max = Math.max,
min = Math.min,
abs = Math.abs,
norminf = numeric.norminf,
pow = Math.pow;
var any = numeric.any,
lt = numeric.lt,
and = numeric.and,
sub = numeric.sub;
var e0, e1, ev;
var ret = new numeric.Dopri(xs, ys, k1, ymid, -1, "");
if (typeof event === "function") e0 = event(x0, y0);
while (x0 < x1 && it < maxit) {
++it;
if (x0 + h > x1) h = x1 - x0;
k2 = f(x0 + c[0] * h, add(y0, mul(A2 * h, k1[i])));
k3 = f(x0 + c[1] * h, add(add(y0, mul(A3[0] * h, k1[i])), mul(A3[1] * h, k2)));
k4 = f(
x0 + c[2] * h,
add(add(add(y0, mul(A4[0] * h, k1[i])), mul(A4[1] * h, k2)), mul(A4[2] * h, k3))
);
k5 = f(
x0 + c[3] * h,
add(
add(add(add(y0, mul(A5[0] * h, k1[i])), mul(A5[1] * h, k2)), mul(A5[2] * h, k3)),
mul(A5[3] * h, k4)
)
);
k6 = f(
x0 + c[4] * h,
add(
add(
add(add(add(y0, mul(A6[0] * h, k1[i])), mul(A6[1] * h, k2)), mul(A6[2] * h, k3)),
mul(A6[3] * h, k4)
),
mul(A6[4] * h, k5)
)
);
y1 = add(
add(
add(add(add(y0, mul(k1[i], h * b[0])), mul(k3, h * b[2])), mul(k4, h * b[3])),
mul(k5, h * b[4])
),
mul(k6, h * b[5])
);
k7 = f(x0 + h, y1);
er = add(
add(
add(
add(add(mul(k1[i], h * e[0]), mul(k3, h * e[2])), mul(k4, h * e[3])),
mul(k5, h * e[4])
),
mul(k6, h * e[5])
),
mul(k7, h * e[6])
);
if (typeof er === "number") erinf = abs(er);
else erinf = norminf(er);
if (erinf > tol) {
// reject
h = 0.2 * h * pow(tol / erinf, 0.25);
if (x0 + h === x0) {
ret.msg = "Step size became too small";
break;
}
continue;
}
ymid[i] = add(
add(
add(
add(add(add(y0, mul(k1[i], h * bm[0])), mul(k3, h * bm[2])), mul(k4, h * bm[3])),
mul(k5, h * bm[4])
),
mul(k6, h * bm[5])
),
mul(k7, h * bm[6])
);
++i;
xs[i] = x0 + h;
ys[i] = y1;
k1[i] = k7;
if (typeof event === "function") {
var yi,
xl = x0,
xr = x0 + 0.5 * h,
xi;
e1 = event(xr, ymid[i - 1]);
ev = and(lt(e0, 0), lt(0, e1));
if (!any(ev)) {
xl = xr;
xr = x0 + h;
e0 = e1;
e1 = event(xr, y1);
ev = and(lt(e0, 0), lt(0, e1));
}
if (any(ev)) {
var xc, yc, en, ei;
var side = 0,
sl = 1.0,
sr = 1.0;
while (1) {
if (typeof e0 === "number")
xi = (sr * e1 * xl - sl * e0 * xr) / (sr * e1 - sl * e0);
else {
xi = xr;
for (j = e0.length - 1; j !== -1; --j) {
if (e0[j] < 0 && e1[j] > 0)
xi = min(
xi,
(sr * e1[j] * xl - sl * e0[j] * xr) / (sr * e1[j] - sl * e0[j])
);
}
}
if (xi <= xl || xi >= xr) break;
yi = ret._at(xi, i - 1);
ei = event(xi, yi);
en = and(lt(e0, 0), lt(0, ei));
if (any(en)) {
xr = xi;
e1 = ei;
ev = en;
sr = 1.0;
if (side === -1) sl *= 0.5;
else sl = 1.0;
side = -1;
} else {
xl = xi;
e0 = ei;
sl = 1.0;
if (side === 1) sr *= 0.5;
else sr = 1.0;
side = 1;
}
}
y1 = ret._at(0.5 * (x0 + xi), i - 1);
ret.f[i] = f(xi, yi);
ret.x[i] = xi;
ret.y[i] = yi;
ret.ymid[i - 1] = y1;
ret.events = ev;
ret.iterations = it;
return ret;
}
}
x0 += h;
y0 = y1;
e0 = e1;
h = min(0.8 * h * pow(tol / erinf, 0.25), 4 * h);
}
ret.iterations = it;
return ret;
};
// 11. Ax = b
numeric.LU = function (A, fast) {
fast = fast || false;
var abs = Math.abs;
var i, j, k, absAjk, Akk, Ak, Pk, Ai;
var max;
var n = A.length,
n1 = n - 1;
var P = new Array(n);
if (!fast) A = numeric.clone(A);
for (k = 0; k < n; ++k) {
Pk = k;
Ak = A[k];
max = abs(Ak[k]);
for (j = k + 1; j < n; ++j) {
absAjk = abs(A[j][k]);
if (max < absAjk) {
max = absAjk;
Pk = j;
}
}
P[k] = Pk;
if (Pk != k) {
A[k] = A[Pk];
A[Pk] = Ak;
Ak = A[k];
}
Akk = Ak[k];
for (i = k + 1; i < n; ++i) {
A[i][k] /= Akk;
}
for (i = k + 1; i < n; ++i) {
Ai = A[i];
for (j = k + 1; j < n1; ++j) {
Ai[j] -= Ai[k] * Ak[j];
++j;
Ai[j] -= Ai[k] * Ak[j];
}
if (j === n1) Ai[j] -= Ai[k] * Ak[j];
}
}
return {
LU: A,
P: P,
};
};
numeric.LUsolve = function LUsolve(LUP, b) {
var i, j;
var LU = LUP.LU;
var n = LU.length;
var x = numeric.clone(b);
var P = LUP.P;
var Pi, LUi, LUii, tmp;
for (i = n - 1; i !== -1; --i) x[i] = b[i];
for (i = 0; i < n; ++i) {
Pi = P[i];
if (P[i] !== i) {
tmp = x[i];
x[i] = x[Pi];
x[Pi] = tmp;
}
LUi = LU[i];
for (j = 0; j < i; ++j) {
x[i] -= x[j] * LUi[j];
}
}
for (i = n - 1; i >= 0; --i) {
LUi = LU[i];
for (j = i + 1; j < n; ++j) {
x[i] -= x[j] * LUi[j];
}
x[i] /= LUi[i];
}
return x;
};
numeric.solve = function solve(A, b, fast) {
return numeric.LUsolve(numeric.LU(A, fast), b);
};
// 12. Linear programming
numeric.echelonize = function echelonize(A) {
var s = numeric.dim(A),
m = s[0],
n = s[1];
var I = numeric.identity(m);
var P = Array(m);
var i, j, k, l, Ai, Ii, Z, a;
var abs = Math.abs;
var diveq = numeric.diveq;
A = numeric.clone(A);
for (i = 0; i < m; ++i) {
k = 0;
Ai = A[i];
Ii = I[i];
for (j = 1; j < n; ++j) if (abs(Ai[k]) < abs(Ai[j])) k = j;
P[i] = k;
diveq(Ii, Ai[k]);
diveq(Ai, Ai[k]);
for (j = 0; j < m; ++j)
if (j !== i) {
Z = A[j];
a = Z[k];
for (l = n - 1; l !== -1; --l) Z[l] -= Ai[l] * a;
Z = I[j];
for (l = m - 1; l !== -1; --l) Z[l] -= Ii[l] * a;
}
}
return { I: I, A: A, P: P };
};
numeric.__solveLP = function __solveLP(c, A, b, tol, maxit, x, flag) {
var sum = numeric.sum,
log = numeric.log,
mul = numeric.mul,
sub = numeric.sub,
dot = numeric.dot,
div = numeric.div,
add = numeric.add;
var m = c.length,
n = b.length,
y;
var unbounded = false,
cb,
i0 = 0;
var alpha = 1.0;
var f0,
df0,
AT = numeric.transpose(A),
svd = numeric.svd,
transpose = numeric.transpose,
leq = numeric.leq,
sqrt = Math.sqrt,
abs = Math.abs;
var muleq = numeric.muleq;
var norm = numeric.norminf,
any = numeric.any,
min = Math.min;
var all = numeric.all,
gt = numeric.gt;
var p = Array(m),
A0 = Array(n),
e = numeric.rep([n], 1),
H;
var solve = numeric.solve,
z = sub(b, dot(A, x)),
count;
var dotcc = dot(c, c);
var g;
for (count = i0; count < maxit; ++count) {
var i, j, d;
for (i = n - 1; i !== -1; --i) A0[i] = div(A[i], z[i]);
var A1 = transpose(A0);
for (i = m - 1; i !== -1; --i) p[i] = /*x[i]+*/ sum(A1[i]);
alpha = 0.25 * abs(dotcc / dot(c, p));
var a1 = 100 * sqrt(dotcc / dot(p, p));
if (!isFinite(alpha) || alpha > a1) alpha = a1;
g = add(c, mul(alpha, p));
H = dot(A1, A0);
for (i = m - 1; i !== -1; --i) H[i][i] += 1;
d = solve(H, div(g, alpha), true);
var t0 = div(z, dot(A, d));
var t = 1.0;
for (i = n - 1; i !== -1; --i) if (t0[i] < 0) t = min(t, -0.999 * t0[i]);
y = sub(x, mul(d, t));
z = sub(b, dot(A, y));
if (!all(gt(z, 0))) return { solution: x, message: "", iterations: count };
x = y;
if (alpha < tol) return { solution: y, message: "", iterations: count };
if (flag) {
var s = dot(c, g),
Ag = dot(A, g);
unbounded = true;
for (i = n - 1; i !== -1; --i)
if (s * Ag[i] < 0) {
unbounded = false;
break;
}
} else {
if (x[m - 1] >= 0) unbounded = false;
else unbounded = true;
}
if (unbounded) return { solution: y, message: "Unbounded", iterations: count };
}
return { solution: x, message: "maximum iteration count exceeded", iterations: count };
};
numeric._solveLP = function _solveLP(c, A, b, tol, maxit) {
var m = c.length,
n = b.length,
y;
var sum = numeric.sum,
log = numeric.log,
mul = numeric.mul,
sub = numeric.sub,
dot = numeric.dot,
div = numeric.div,
add = numeric.add;
var c0 = numeric.rep([m], 0).concat([1]);
var J = numeric.rep([n, 1], -1);
var A0 = numeric.blockMatrix([[A, J]]);
var b0 = b;
var y = numeric.rep([m], 0).concat(Math.max(0, numeric.sup(numeric.neg(b))) + 1);
var x0 = numeric.__solveLP(c0, A0, b0, tol, maxit, y, false);
var x = numeric.clone(x0.solution);
x.length = m;
var foo = numeric.inf(sub(b, dot(A, x)));
if (foo < 0) {
return { solution: NaN, message: "Infeasible", iterations: x0.iterations };
}
var ret = numeric.__solveLP(c, A, b, tol, maxit - x0.iterations, x, true);
ret.iterations += x0.iterations;
return ret;
};
numeric.solveLP = function solveLP(c, A, b, Aeq, beq, tol, maxit) {
if (typeof maxit === "undefined") maxit = 1000;
if (typeof tol === "undefined") tol = numeric.epsilon;
if (typeof Aeq === "undefined") return numeric._solveLP(c, A, b, tol, maxit);
var m = Aeq.length,
n = Aeq[0].length,
o = A.length;
var B = numeric.echelonize(Aeq);
var flags = numeric.rep([n], 0);
var P = B.P;
var Q = [];
var i;
for (i = P.length - 1; i !== -1; --i) flags[P[i]] = 1;
for (i = n - 1; i !== -1; --i) if (flags[i] === 0) Q.push(i);
var g = numeric.getRange;
var I = numeric.linspace(0, m - 1),
J = numeric.linspace(0, o - 1);
var Aeq2 = g(Aeq, I, Q),
A1 = g(A, J, P),
A2 = g(A, J, Q),
dot = numeric.dot,
sub = numeric.sub;
var A3 = dot(A1, B.I);
var A4 = sub(A2, dot(A3, Aeq2)),
b4 = sub(b, dot(A3, beq));
var c1 = Array(P.length),
c2 = Array(Q.length);
for (i = P.length - 1; i !== -1; --i) c1[i] = c[P[i]];
for (i = Q.length - 1; i !== -1; --i) c2[i] = c[Q[i]];
var c4 = sub(c2, dot(c1, dot(B.I, Aeq2)));
var S = numeric._solveLP(c4, A4, b4, tol, maxit);
var x2 = S.solution;
if (x2 !== x2) return S;
var x1 = dot(B.I, sub(beq, dot(Aeq2, x2)));
var x = Array(c.length);
for (i = P.length - 1; i !== -1; --i) x[P[i]] = x1[i];
for (i = Q.length - 1; i !== -1; --i) x[Q[i]] = x2[i];
return { solution: x, message: S.message, iterations: S.iterations };
};
numeric.MPStoLP = function MPStoLP(MPS) {
if (MPS instanceof String) {
MPS.split("\n");
}
var state = 0;
var states = ["Initial state", "NAME", "ROWS", "COLUMNS", "RHS", "BOUNDS", "ENDATA"];
var n = MPS.length;
var i,
j,
z,
N = 0,
rows = {},
sign = [],
rl = 0,
vars = {},
nv = 0;
var name;
var c = [],
A = [],
b = [];
function err(e) {
throw new Error(
"MPStoLP: " +
e +
"\nLine " +
i +
": " +
MPS[i] +
"\nCurrent state: " +
states[state] +
"\n"
);
}
for (i = 0; i < n; ++i) {
z = MPS[i];
var w0 = z.match(/\S*/g);
var w = [];
for (j = 0; j < w0.length; ++j) if (w0[j] !== "") w.push(w0[j]);
if (w.length === 0) continue;
for (j = 0; j < states.length; ++j)
if (z.substr(0, states[j].length) === states[j]) break;
if (j < states.length) {
state = j;
if (j === 1) {
name = w[1];
}
if (j === 6)
return { name: name, c: c, A: numeric.transpose(A), b: b, rows: rows, vars: vars };
continue;
}
switch (state) {
case 0:
case 1:
err("Unexpected line");
case 2:
switch (w[0]) {
case "N":
if (N === 0) N = w[1];
else err("Two or more N rows");
break;
case "L":
rows[w[1]] = rl;
sign[rl] = 1;
b[rl] = 0;
++rl;
break;
case "G":
rows[w[1]] = rl;
sign[rl] = -1;
b[rl] = 0;
++rl;
break;
case "E":
rows[w[1]] = rl;
sign[rl] = 0;
b[rl] = 0;
++rl;
break;
default:
err("Parse error " + numeric.prettyPrint(w));
}
break;
case 3:
if (!vars.hasOwnProperty(w[0])) {
vars[w[0]] = nv;
c[nv] = 0;
A[nv] = numeric.rep([rl], 0);
++nv;
}
var p = vars[w[0]];
for (j = 1; j < w.length; j += 2) {
if (w[j] === N) {
c[p] = parseFloat(w[j + 1]);
continue;
}
var q = rows[w[j]];
A[p][q] = (sign[q] < 0 ? -1 : 1) * parseFloat(w[j + 1]);
}
break;
case 4:
for (j = 1; j < w.length; j += 2)
b[rows[w[j]]] = (sign[rows[w[j]]] < 0 ? -1 : 1) * parseFloat(w[j + 1]);
break;
case 5:
/*FIXME*/ break;
case 6:
err("Internal error");
}
}
err("Reached end of file without ENDATA");
};
// seedrandom.js version 2.0.
// Author: David Bau 4/2/2011
//
// Defines a method Math.seedrandom() that, when called, substitutes
// an explicitly seeded RC4-based algorithm for Math.random(). Also
// supports automatic seeding from local or network sources of entropy.
//
// Usage:
//
// <script src=http://davidbau.com/encode/seedrandom-min.js></script>
//
// Math.seedrandom('yipee'); Sets Math.random to a function that is
// initialized using the given explicit seed.
//
// Math.seedrandom(); Sets Math.random to a function that is
// seeded using the current time, dom state,
// and other accumulated local entropy.
// The generated seed string is returned.
//
// Math.seedrandom('yowza', true);
// Seeds using the given explicit seed mixed
// together with accumulated entropy.
//
// <script src="http://bit.ly/srandom-512"></script>
// Seeds using physical random bits downloaded
// from random.org.
//
// <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom">
// </script> Seeds using urandom bits from call.jsonlib.com,
// which is faster than random.org.
//
// Examples:
//
// Math.seedrandom("hello"); // Use "hello" as the seed.
// document.write(Math.random()); // Always 0.5463663768140734
// document.write(Math.random()); // Always 0.43973793770592234
// var rng1 = Math.random; // Remember the current prng.
//
// var autoseed = Math.seedrandom(); // New prng with an automatic seed.
// document.write(Math.random()); // Pretty much unpredictable.
//
// Math.random = rng1; // Continue "hello" prng sequence.
// document.write(Math.random()); // Always 0.554769432473455
//
// Math.seedrandom(autoseed); // Restart at the previous seed.
// document.write(Math.random()); // Repeat the 'unpredictable' value.
//
// Notes:
//
// Each time seedrandom('arg') is called, entropy from the passed seed
// is accumulated in a pool to help generate future seeds for the
// zero-argument form of Math.seedrandom, so entropy can be injected over
// time by calling seedrandom with explicit data repeatedly.
//
// On speed - This javascript implementation of Math.random() is about
// 3-10x slower than the built-in Math.random() because it is not native
// code, but this is typically fast enough anyway. Seeding is more expensive,
// especially if you use auto-seeding. Some details (timings on Chrome 4):
//
// Our Math.random() - avg less than 0.002 milliseconds per call
// seedrandom('explicit') - avg less than 0.5 milliseconds per call
// seedrandom('explicit', true) - avg less than 2 milliseconds per call
// seedrandom() - avg about 38 milliseconds per call
//
// LICENSE (BSD):
//
// Copyright 2010 David Bau, all rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of this module nor the names of its contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
/**
* All code is in an anonymous closure to keep the global namespace clean.
*
* @param {number=} overflow
* @param {number=} startdenom
*/
// Patched by Seb so that seedrandom.js does not pollute the Math object.
// My tests suggest that doing Math.trouble = 1 makes Math lookups about 5%
// slower.
numeric.seedrandom = { pow: Math.pow, random: Math.random };
(function (pool, math, width, chunks, significance, overflow, startdenom) {
//
// seedrandom()
// This is the seedrandom function described above.
//
math["seedrandom"] = function seedrandom(seed, use_entropy) {
var key = [];
var arc4;
// Flatten the seed string or build one from local entropy if needed.
seed = mixkey(
flatten(
use_entropy
? [seed, pool]
: arguments.length
? seed
: [new Date().getTime(), pool, window],
3
),
key
);
// Use the seed to initialize an ARC4 generator.
arc4 = new ARC4(key);
// Mix the randomness into accumulated entropy.
mixkey(arc4.S, pool);
// Override Math.random
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
math["random"] = function random() {
// Closure to return a random double:
var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48
var d = startdenom; // and denominator d = 2 ^ 48.
var x = 0; // and no 'extra last byte'.
while (n < significance) {
// Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) {
// To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
// Return the seed that was used
return seed;
};
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
/** @constructor */
function ARC4(key) {
var t,
u,
me = this,
keylen = key.length;
var i = 0,
j = (me.i = me.j = me.m = 0);
me.S = [];
me.c = [];
// The empty key [] is treated as [0].
if (!keylen) {
key = [keylen++];
}
// Set up S using the standard key scheduling algorithm.
while (i < width) {
me.S[i] = i++;
}
for (i = 0; i < width; i++) {
t = me.S[i];
j = lowbits(j + t + key[i % keylen]);
u = me.S[j];
me.S[i] = u;
me.S[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
me.g = function getnext(count) {
var s = me.S;
var i = lowbits(me.i + 1);
var t = s[i];
var j = lowbits(me.j + t);
var u = s[j];
s[i] = u;
s[j] = t;
var r = s[lowbits(t + u)];
while (--count) {
i = lowbits(i + 1);
t = s[i];
j = lowbits(j + t);
u = s[j];
s[i] = u;
s[j] = t;
r = r * width + s[lowbits(t + u)];
}
me.i = i;
me.j = j;
return r;
};
// For robust unpredictability discard an initial batch of values.
// See http://www.rsa.com/rsalabs/node.asp?id=2009
me.g(width);
}
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
/** @param {Object=} result
* @param {string=} prop
* @param {string=} typ */
function flatten(obj, depth, result, prop, typ) {
result = [];
typ = typeof obj;
if (depth && typ == "object") {
for (prop in obj) {
if (prop.indexOf("S") < 5) {
// Avoid FF3 bug (local/sessionStorage)
try {
result.push(flatten(obj[prop], depth - 1));
} catch (e) {}
}
}
}
return result.length ? result : obj + (typ != "string" ? "\0" : "");
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
/** @param {number=} smear
* @param {number=} j */
function mixkey(seed, key, smear, j) {
seed += ""; // Ensure the seed is a string
smear = 0;
for (j = 0; j < seed.length; j++) {
key[lowbits(j)] = lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j));
}
seed = "";
for (j in key) {
seed += String.fromCharCode(key[j]);
}
return seed;
}
//
// lowbits()
// A quick "n mod width" for width a power of 2.
//
function lowbits(n) {
return n & (width - 1);
}
//
// The following constants are related to IEEE 754 limits.
//
startdenom = math.pow(width, chunks);
significance = math.pow(2, significance);
overflow = significance * 2;
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to intefere with determinstic PRNG state later,
// seedrandom will not call math.random on its own again after
// initialization.
//
mixkey(math.random(), pool);
// End anonymous scope, and pass initial values.
})(
[], // pool: entropy pool starts empty
numeric.seedrandom, // math: package containing random, pow, and seedrandom
256, // width: each RC4 output is 0 <= x < 256
6, // chunks: at least six RC4 outputs for each double
52 // significance: there are 52 significant digits in a double
);
/* This file is a slightly modified version of quadprog.js from Alberto Santini.
* It has been slightly modified by Sébastien Loisel to make sure that it handles
* 0-based Arrays instead of 1-based Arrays.
* License is in resources/LICENSE.quadprog */
(function (exports) {
function base0to1(A) {
if (typeof A !== "object") {
return A;
}
var ret = [],
i,
n = A.length;
for (i = 0; i < n; i++) ret[i + 1] = base0to1(A[i]);
return ret;
}
function base1to0(A) {
if (typeof A !== "object") {
return A;
}
var ret = [],
i,
n = A.length;
for (i = 1; i < n; i++) ret[i - 1] = base1to0(A[i]);
return ret;
}
function dpori(a, lda, n) {
var i, j, k, kp1, t;
for (k = 1; k <= n; k = k + 1) {
a[k][k] = 1 / a[k][k];
t = -a[k][k];
//~ dscal(k - 1, t, a[1][k], 1);
for (i = 1; i < k; i = i + 1) {
a[i][k] = t * a[i][k];
}
kp1 = k + 1;
if (n < kp1) {
break;
}
for (j = kp1; j <= n; j = j + 1) {
t = a[k][j];
a[k][j] = 0;
//~ daxpy(k, t, a[1][k], 1, a[1][j], 1);
for (i = 1; i <= k; i = i + 1) {
a[i][j] = a[i][j] + t * a[i][k];
}
}
}
}
function dposl(a, lda, n, b) {
var i, k, kb, t;
for (k = 1; k <= n; k = k + 1) {
//~ t = ddot(k - 1, a[1][k], 1, b[1], 1);
t = 0;
for (i = 1; i < k; i = i + 1) {
t = t + a[i][k] * b[i];
}
b[k] = (b[k] - t) / a[k][k];
}
for (kb = 1; kb <= n; kb = kb + 1) {
k = n + 1 - kb;
b[k] = b[k] / a[k][k];
t = -b[k];
//~ daxpy(k - 1, t, a[1][k], 1, b[1], 1);
for (i = 1; i < k; i = i + 1) {
b[i] = b[i] + t * a[i][k];
}
}
}
function dpofa(a, lda, n, info) {
var i, j, jm1, k, t, s;
for (j = 1; j <= n; j = j + 1) {
info[1] = j;
s = 0;
jm1 = j - 1;
if (jm1 < 1) {
s = a[j][j] - s;
if (s <= 0) {
break;
}
a[j][j] = Math.sqrt(s);
} else {
for (k = 1; k <= jm1; k = k + 1) {
//~ t = a[k][j] - ddot(k - 1, a[1][k], 1, a[1][j], 1);
t = a[k][j];
for (i = 1; i < k; i = i + 1) {
t = t - a[i][j] * a[i][k];
}
t = t / a[k][k];
a[k][j] = t;
s = s + t * t;
}
s = a[j][j] - s;
if (s <= 0) {
break;
}
a[j][j] = Math.sqrt(s);
}
info[1] = 0;
}
}
function qpgen2(
dmat,
dvec,
fddmat,
n,
sol,
crval,
amat,
bvec,
fdamat,
q,
meq,
iact,
nact,
iter,
work,
ierr
) {
var i,
j,
l,
l1,
info,
it1,
iwzv,
iwrv,
iwrm,
iwsv,
iwuv,
nvl,
r,
iwnbv,
temp,
sum,
t1,
tt,
gc,
gs,
nu,
t1inf,
t2min,
vsmall,
tmpa,
tmpb,
go;
r = Math.min(n, q);
l = 2 * n + (r * (r + 5)) / 2 + 2 * q + 1;
vsmall = 1.0e-60;
do {
vsmall = vsmall + vsmall;
tmpa = 1 + 0.1 * vsmall;
tmpb = 1 + 0.2 * vsmall;
} while (tmpa <= 1 || tmpb <= 1);
for (i = 1; i <= n; i = i + 1) {
work[i] = dvec[i];
}
for (i = n + 1; i <= l; i = i + 1) {
work[i] = 0;
}
for (i = 1; i <= q; i = i + 1) {
iact[i] = 0;
}
info = [];
if (ierr[1] === 0) {
dpofa(dmat, fddmat, n, info);
if (info[1] !== 0) {
ierr[1] = 2;
return;
}
dposl(dmat, fddmat, n, dvec);
dpori(dmat, fddmat, n);
} else {
for (j = 1; j <= n; j = j + 1) {
sol[j] = 0;
for (i = 1; i <= j; i = i + 1) {
sol[j] = sol[j] + dmat[i][j] * dvec[i];
}
}
for (j = 1; j <= n; j = j + 1) {
dvec[j] = 0;
for (i = j; i <= n; i = i + 1) {
dvec[j] = dvec[j] + dmat[j][i] * sol[i];
}
}
}
crval[1] = 0;
for (j = 1; j <= n; j = j + 1) {
sol[j] = dvec[j];
crval[1] = crval[1] + work[j] * sol[j];
work[j] = 0;
for (i = j + 1; i <= n; i = i + 1) {
dmat[i][j] = 0;
}
}
crval[1] = -crval[1] / 2;
ierr[1] = 0;
iwzv = n;
iwrv = iwzv + n;
iwuv = iwrv + r;
iwrm = iwuv + r + 1;
iwsv = iwrm + (r * (r + 1)) / 2;
iwnbv = iwsv + q;
for (i = 1; i <= q; i = i + 1) {
sum = 0;
for (j = 1; j <= n; j = j + 1) {
sum = sum + amat[j][i] * amat[j][i];
}
work[iwnbv + i] = Math.sqrt(sum);
}
nact = 0;
iter[1] = 0;
iter[2] = 0;
function fn_goto_50() {
iter[1] = iter[1] + 1;
l = iwsv;
for (i = 1; i <= q; i = i + 1) {
l = l + 1;
sum = -bvec[i];
for (j = 1; j <= n; j = j + 1) {
sum = sum + amat[j][i] * sol[j];
}
if (Math.abs(sum) < vsmall) {
sum = 0;
}
if (i > meq) {
work[l] = sum;
} else {
work[l] = -Math.abs(sum);
if (sum > 0) {
for (j = 1; j <= n; j = j + 1) {
amat[j][i] = -amat[j][i];
}
bvec[i] = -bvec[i];
}
}
}
for (i = 1; i <= nact; i = i + 1) {
work[iwsv + iact[i]] = 0;
}
nvl = 0;
temp = 0;
for (i = 1; i <= q; i = i + 1) {
if (work[iwsv + i] < temp * work[iwnbv + i]) {
nvl = i;
temp = work[iwsv + i] / work[iwnbv + i];
}
}
if (nvl === 0) {
return 999;
}
return 0;
}
function fn_goto_55() {
for (i = 1; i <= n; i = i + 1) {
sum = 0;
for (j = 1; j <= n; j = j + 1) {
sum = sum + dmat[j][i] * amat[j][nvl];
}
work[i] = sum;
}
l1 = iwzv;
for (i = 1; i <= n; i = i + 1) {
work[l1 + i] = 0;
}
for (j = nact + 1; j <= n; j = j + 1) {
for (i = 1; i <= n; i = i + 1) {
work[l1 + i] = work[l1 + i] + dmat[i][j] * work[j];
}
}
t1inf = true;
for (i = nact; i >= 1; i = i - 1) {
sum = work[i];
l = iwrm + (i * (i + 3)) / 2;
l1 = l - i;
for (j = i + 1; j <= nact; j = j + 1) {
sum = sum - work[l] * work[iwrv + j];
l = l + j;
}
sum = sum / work[l1];
work[iwrv + i] = sum;
if (iact[i] < meq) {
// continue;
break;
}
if (sum < 0) {
// continue;
break;
}
t1inf = false;
it1 = i;
}
if (!t1inf) {
t1 = work[iwuv + it1] / work[iwrv + it1];
for (i = 1; i <= nact; i = i + 1) {
if (iact[i] < meq) {
// continue;
break;
}
if (work[iwrv + i] < 0) {
// continue;
break;
}
temp = work[iwuv + i] / work[iwrv + i];
if (temp < t1) {
t1 = temp;
it1 = i;
}
}
}
sum = 0;
for (i = iwzv + 1; i <= iwzv + n; i = i + 1) {
sum = sum + work[i] * work[i];
}
if (Math.abs(sum) <= vsmall) {
if (t1inf) {
ierr[1] = 1;
// GOTO 999
return 999;
} else {
for (i = 1; i <= nact; i = i + 1) {
work[iwuv + i] = work[iwuv + i] - t1 * work[iwrv + i];
}
work[iwuv + nact + 1] = work[iwuv + nact + 1] + t1;
// GOTO 700
return 700;
}
} else {
sum = 0;
for (i = 1; i <= n; i = i + 1) {
sum = sum + work[iwzv + i] * amat[i][nvl];
}
tt = -work[iwsv + nvl] / sum;
t2min = true;
if (!t1inf) {
if (t1 < tt) {
tt = t1;
t2min = false;
}
}
for (i = 1; i <= n; i = i + 1) {
sol[i] = sol[i] + tt * work[iwzv + i];
if (Math.abs(sol[i]) < vsmall) {
sol[i] = 0;
}
}
crval[1] = crval[1] + tt * sum * (tt / 2 + work[iwuv + nact + 1]);
for (i = 1; i <= nact; i = i + 1) {
work[iwuv + i] = work[iwuv + i] - tt * work[iwrv + i];
}
work[iwuv + nact + 1] = work[iwuv + nact + 1] + tt;
if (t2min) {
nact = nact + 1;
iact[nact] = nvl;
l = iwrm + ((nact - 1) * nact) / 2 + 1;
for (i = 1; i <= nact - 1; i = i + 1) {
work[l] = work[i];
l = l + 1;
}
if (nact === n) {
work[l] = work[n];
} else {
for (i = n; i >= nact + 1; i = i - 1) {
if (work[i] === 0) {
// continue;
break;
}
gc = Math.max(Math.abs(work[i - 1]), Math.abs(work[i]));
gs = Math.min(Math.abs(work[i - 1]), Math.abs(work[i]));
if (work[i - 1] >= 0) {
temp = Math.abs(gc * Math.sqrt(1 + (gs * gs) / (gc * gc)));
} else {
temp = -Math.abs(gc * Math.sqrt(1 + (gs * gs) / (gc * gc)));
}
gc = work[i - 1] / temp;
gs = work[i] / temp;
if (gc === 1) {
// continue;
break;
}
if (gc === 0) {
work[i - 1] = gs * temp;
for (j = 1; j <= n; j = j + 1) {
temp = dmat[j][i - 1];
dmat[j][i - 1] = dmat[j][i];
dmat[j][i] = temp;
}
} else {
work[i - 1] = temp;
nu = gs / (1 + gc);
for (j = 1; j <= n; j = j + 1) {
temp = gc * dmat[j][i - 1] + gs * dmat[j][i];
dmat[j][i] = nu * (dmat[j][i - 1] + temp) - dmat[j][i];
dmat[j][i - 1] = temp;
}
}
}
work[l] = work[nact];
}
} else {
sum = -bvec[nvl];
for (j = 1; j <= n; j = j + 1) {
sum = sum + sol[j] * amat[j][nvl];
}
if (nvl > meq) {
work[iwsv + nvl] = sum;
} else {
work[iwsv + nvl] = -Math.abs(sum);
if (sum > 0) {
for (j = 1; j <= n; j = j + 1) {
amat[j][nvl] = -amat[j][nvl];
}
bvec[nvl] = -bvec[nvl];
}
}
// GOTO 700
return 700;
}
}
return 0;
}
function fn_goto_797() {
l = iwrm + (it1 * (it1 + 1)) / 2 + 1;
l1 = l + it1;
if (work[l1] === 0) {
// GOTO 798
return 798;
}
gc = Math.max(Math.abs(work[l1 - 1]), Math.abs(work[l1]));
gs = Math.min(Math.abs(work[l1 - 1]), Math.abs(work[l1]));
if (work[l1 - 1] >= 0) {
temp = Math.abs(gc * Math.sqrt(1 + (gs * gs) / (gc * gc)));
} else {
temp = -Math.abs(gc * Math.sqrt(1 + (gs * gs) / (gc * gc)));
}
gc = work[l1 - 1] / temp;
gs = work[l1] / temp;
if (gc === 1) {
// GOTO 798
return 798;
}
if (gc === 0) {
for (i = it1 + 1; i <= nact; i = i + 1) {
temp = work[l1 - 1];
work[l1 - 1] = work[l1];
work[l1] = temp;
l1 = l1 + i;
}
for (i = 1; i <= n; i = i + 1) {
temp = dmat[i][it1];
dmat[i][it1] = dmat[i][it1 + 1];
dmat[i][it1 + 1] = temp;
}
} else {
nu = gs / (1 + gc);
for (i = it1 + 1; i <= nact; i = i + 1) {
temp = gc * work[l1 - 1] + gs * work[l1];
work[l1] = nu * (work[l1 - 1] + temp) - work[l1];
work[l1 - 1] = temp;
l1 = l1 + i;
}
for (i = 1; i <= n; i = i + 1) {
temp = gc * dmat[i][it1] + gs * dmat[i][it1 + 1];
dmat[i][it1 + 1] = nu * (dmat[i][it1] + temp) - dmat[i][it1 + 1];
dmat[i][it1] = temp;
}
}
return 0;
}
function fn_goto_798() {
l1 = l - it1;
for (i = 1; i <= it1; i = i + 1) {
work[l1] = work[l];
l = l + 1;
l1 = l1 + 1;
}
work[iwuv + it1] = work[iwuv + it1 + 1];
iact[it1] = iact[it1 + 1];
it1 = it1 + 1;
if (it1 < nact) {
// GOTO 797
return 797;
}
return 0;
}
function fn_goto_799() {
work[iwuv + nact] = work[iwuv + nact + 1];
work[iwuv + nact + 1] = 0;
iact[nact] = 0;
nact = nact - 1;
iter[2] = iter[2] + 1;
return 0;
}
go = 0;
while (true) {
go = fn_goto_50();
if (go === 999) {
return;
}
while (true) {
go = fn_goto_55();
if (go === 0) {
break;
}
if (go === 999) {
return;
}
if (go === 700) {
if (it1 === nact) {
fn_goto_799();
} else {
while (true) {
fn_goto_797();
go = fn_goto_798();
if (go !== 797) {
break;
}
}
fn_goto_799();
}
}
}
}
}
function solveQP(Dmat, dvec, Amat, bvec, meq, factorized) {
Dmat = base0to1(Dmat);
dvec = base0to1(dvec);
Amat = base0to1(Amat);
var i,
n,
q,
nact,
r,
crval = [],
iact = [],
sol = [],
work = [],
iter = [],
message;
meq = meq || 0;
factorized = factorized ? base0to1(factorized) : [undefined, 0];
bvec = bvec ? base0to1(bvec) : [];
// In Fortran the array index starts from 1
n = Dmat.length - 1;
q = Amat[1].length - 1;
if (!bvec) {
for (i = 1; i <= q; i = i + 1) {
bvec[i] = 0;
}
}
for (i = 1; i <= q; i = i + 1) {
iact[i] = 0;
}
nact = 0;
r = Math.min(n, q);
for (i = 1; i <= n; i = i + 1) {
sol[i] = 0;
}
crval[1] = 0;
for (i = 1; i <= 2 * n + (r * (r + 5)) / 2 + 2 * q + 1; i = i + 1) {
work[i] = 0;
}
for (i = 1; i <= 2; i = i + 1) {
iter[i] = 0;
}
qpgen2(
Dmat,
dvec,
n,
n,
sol,
crval,
Amat,
bvec,
n,
q,
meq,
iact,
nact,
iter,
work,
factorized
);
message = "";
if (factorized[1] === 1) {
message = "constraints are inconsistent, no solution!";
}
if (factorized[1] === 2) {
message = "matrix D in quadratic function is not positive definite!";
}
return {
solution: base1to0(sol),
value: base1to0(crval),
unconstrained_solution: base1to0(dvec),
iterations: base1to0(iter),
iact: base1to0(iact),
message: message,
};
}
exports.solveQP = solveQP;
})(numeric);
/*
Shanti Rao sent me this routine by private email. I had to modify it
slightly to work on Arrays instead of using a Matrix object.
It is apparently translated from http://stitchpanorama.sourceforge.net/Python/svd.py
*/
numeric.svd = function svd(A) {
var temp;
//Compute the thin SVD from G. H. Golub and C. Reinsch, Numer. Math. 14, 403-420 (1970)
var prec = numeric.epsilon; //Math.pow(2,-52) // assumes double prec
var tolerance = 1e-64 / prec;
var itmax = 50;
var c = 0;
var i = 0;
var j = 0;
var k = 0;
var l = 0;
var u = numeric.clone(A);
var m = u.length;
var n = u[0].length;
if (m < n) throw "Need more rows than columns";
var e = new Array(n);
var q = new Array(n);
for (i = 0; i < n; i++) e[i] = q[i] = 0.0;
var v = numeric.rep([n, n], 0);
// v.zero();
function pythag(a, b) {
a = Math.abs(a);
b = Math.abs(b);
if (a > b) return a * Math.sqrt(1.0 + (b * b) / a / a);
else if (b == 0.0) return a;
return b * Math.sqrt(1.0 + (a * a) / b / b);
}
//Householder's reduction to bidiagonal form
var f = 0.0;
var g = 0.0;
var h = 0.0;
var x = 0.0;
var y = 0.0;
var z = 0.0;
var s = 0.0;
for (i = 0; i < n; i++) {
e[i] = g;
s = 0.0;
l = i + 1;
for (j = i; j < m; j++) s += u[j][i] * u[j][i];
if (s <= tolerance) g = 0.0;
else {
f = u[i][i];
g = Math.sqrt(s);
if (f >= 0.0) g = -g;
h = f * g - s;
u[i][i] = f - g;
for (j = l; j < n; j++) {
s = 0.0;
for (k = i; k < m; k++) s += u[k][i] * u[k][j];
f = s / h;
for (k = i; k < m; k++) u[k][j] += f * u[k][i];
}
}
q[i] = g;
s = 0.0;
for (j = l; j < n; j++) s = s + u[i][j] * u[i][j];
if (s <= tolerance) g = 0.0;
else {
f = u[i][i + 1];
g = Math.sqrt(s);
if (f >= 0.0) g = -g;
h = f * g - s;
u[i][i + 1] = f - g;
for (j = l; j < n; j++) e[j] = u[i][j] / h;
for (j = l; j < m; j++) {
s = 0.0;
for (k = l; k < n; k++) s += u[j][k] * u[i][k];
for (k = l; k < n; k++) u[j][k] += s * e[k];
}
}
y = Math.abs(q[i]) + Math.abs(e[i]);
if (y > x) x = y;
}
// accumulation of right hand gtransformations
for (i = n - 1; i != -1; i += -1) {
if (g != 0.0) {
h = g * u[i][i + 1];
for (j = l; j < n; j++) v[j][i] = u[i][j] / h;
for (j = l; j < n; j++) {
s = 0.0;
for (k = l; k < n; k++) s += u[i][k] * v[k][j];
for (k = l; k < n; k++) v[k][j] += s * v[k][i];
}
}
for (j = l; j < n; j++) {
v[i][j] = 0;
v[j][i] = 0;
}
v[i][i] = 1;
g = e[i];
l = i;
}
// accumulation of left hand transformations
for (i = n - 1; i != -1; i += -1) {
l = i + 1;
g = q[i];
for (j = l; j < n; j++) u[i][j] = 0;
if (g != 0.0) {
h = u[i][i] * g;
for (j = l; j < n; j++) {
s = 0.0;
for (k = l; k < m; k++) s += u[k][i] * u[k][j];
f = s / h;
for (k = i; k < m; k++) u[k][j] += f * u[k][i];
}
for (j = i; j < m; j++) u[j][i] = u[j][i] / g;
} else for (j = i; j < m; j++) u[j][i] = 0;
u[i][i] += 1;
}
// diagonalization of the bidiagonal form
prec = prec * x;
for (k = n - 1; k != -1; k += -1) {
for (var iteration = 0; iteration < itmax; iteration++) {
// test f splitting
var test_convergence = false;
for (l = k; l != -1; l += -1) {
if (Math.abs(e[l]) <= prec) {
test_convergence = true;
break;
}
if (Math.abs(q[l - 1]) <= prec) break;
}
if (!test_convergence) {
// cancellation of e[l] if l>0
c = 0.0;
s = 1.0;
var l1 = l - 1;
for (i = l; i < k + 1; i++) {
f = s * e[i];
e[i] = c * e[i];
if (Math.abs(f) <= prec) break;
g = q[i];
h = pythag(f, g);
q[i] = h;
c = g / h;
s = -f / h;
for (j = 0; j < m; j++) {
y = u[j][l1];
z = u[j][i];
u[j][l1] = y * c + z * s;
u[j][i] = -y * s + z * c;
}
}
}
// test f convergence
z = q[k];
if (l == k) {
//convergence
if (z < 0.0) {
//q[k] is made non-negative
q[k] = -z;
for (j = 0; j < n; j++) v[j][k] = -v[j][k];
}
break; //break out of iteration loop and move on to next k value
}
if (iteration >= itmax - 1) throw "Error: no convergence.";
// shift from bottom 2x2 minor
x = q[l];
y = q[k - 1];
g = e[k - 1];
h = e[k];
f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2.0 * h * y);
g = pythag(f, 1.0);
if (f < 0.0) f = ((x - z) * (x + z) + h * (y / (f - g) - h)) / x;
else f = ((x - z) * (x + z) + h * (y / (f + g) - h)) / x;
// next QR transformation
c = 1.0;
s = 1.0;
for (i = l + 1; i < k + 1; i++) {
g = e[i];
y = q[i];
h = s * g;
g = c * g;
z = pythag(f, h);
e[i - 1] = z;
c = f / z;
s = h / z;
f = x * c + g * s;
g = -x * s + g * c;
h = y * s;
y = y * c;
for (j = 0; j < n; j++) {
x = v[j][i - 1];
z = v[j][i];
v[j][i - 1] = x * c + z * s;
v[j][i] = -x * s + z * c;
}
z = pythag(f, h);
q[i - 1] = z;
c = f / z;
s = h / z;
f = c * g + s * y;
x = -s * g + c * y;
for (j = 0; j < m; j++) {
y = u[j][i - 1];
z = u[j][i];
u[j][i - 1] = y * c + z * s;
u[j][i] = -y * s + z * c;
}
}
e[l] = 0.0;
e[k] = f;
q[k] = x;
}
}
//vt= transpose(v)
//return (u,q,vt)
for (i = 0; i < q.length; i++) if (q[i] < prec) q[i] = 0;
//sort eigenvalues
for (i = 0; i < n; i++) {
//writeln(q)
for (j = i - 1; j >= 0; j--) {
if (q[j] < q[i]) {
// writeln(i,'-',j)
c = q[j];
q[j] = q[i];
q[i] = c;
for (k = 0; k < u.length; k++) {
temp = u[k][i];
u[k][i] = u[k][j];
u[k][j] = temp;
}
for (k = 0; k < v.length; k++) {
temp = v[k][i];
v[k][i] = v[k][j];
v[k][j] = temp;
}
// u.swapCols(i,j)
// v.swapCols(i,j)
i = j;
}
}
}
return { U: u, S: q, V: v };
};
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(27)));
/***/
},
/* 13 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (Buffer) {
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function () {
return encodeWeights;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function () {
return decodeWeights;
});
/* unused harmony export concatenateTypedArrays */
/* unused harmony export stringByteLength */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return arrayBufferToBase64String;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return base64StringToArrayBuffer;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function () {
return concatenateArrayBuffers;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return basename;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function () {
return getModelArtifactsInfoForJSON;
});
/* unused harmony export getFloat16Decoder */
/* harmony import */ var _ops_complex__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(18);
/* harmony import */ var _ops_tensor_ops__WEBPACK_IMPORTED_MODULE_1__ =
__webpack_require__(8);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(34);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** Number of bytes reserved for the length of the string. (32bit integer). */
const NUM_BYTES_STRING_LENGTH = 4;
/**
* Encode a map from names to weight values as an ArrayBuffer, along with an
* `Array` of `WeightsManifestEntry` as specification of the encoded weights.
*
* This function does not perform sharding.
*
* This function is the reverse of `decodeWeights`.
*
* @param tensors A map ("dict") from names to tensors.
* @param group Group to which the weights belong (optional).
* @returns A `Promise` of
* - A flat `ArrayBuffer` with all the binary values of the `Tensor`s
* concatenated.
* - An `Array` of `WeightManifestEntry`s, carrying information including
* tensor names, `dtype`s and shapes.
* @throws Error: on unsupported tensor `dtype`.
*/
async function encodeWeights(tensors, group) {
// TODO(adarob, cais): Support quantization.
const specs = [];
const dataPromises = [];
const names = Array.isArray(tensors)
? tensors.map((tensor) => tensor.name)
: Object.keys(tensors);
for (let i = 0; i < names.length; ++i) {
const name = names[i];
const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name];
if (
t.dtype !== "float32" &&
t.dtype !== "int32" &&
t.dtype !== "bool" &&
t.dtype !== "string" &&
t.dtype !== "complex64"
) {
throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`);
}
const spec = { name, shape: t.shape, dtype: t.dtype };
if (t.dtype === "string") {
const utf8bytes = new Promise(async (resolve) => {
const vals = await t.bytes();
const totalNumBytes =
vals.reduce((p, c) => p + c.length, 0) + NUM_BYTES_STRING_LENGTH * vals.length;
const bytes = new Uint8Array(totalNumBytes);
let offset = 0;
for (let i = 0; i < vals.length; i++) {
const val = vals[i];
const bytesOfLength = new Uint8Array(new Uint32Array([val.length]).buffer);
bytes.set(bytesOfLength, offset);
offset += NUM_BYTES_STRING_LENGTH;
bytes.set(val, offset);
offset += val.length;
}
resolve(bytes);
});
dataPromises.push(utf8bytes);
} else {
dataPromises.push(t.data());
}
if (group != null) {
spec.group = group;
}
specs.push(spec);
}
const tensorValues = await Promise.all(dataPromises);
return { data: concatenateTypedArrays(tensorValues), specs };
}
/**
* Decode flat ArrayBuffer as weights.
*
* This function does not handle sharding.
*
* This function is the reverse of `encodeWeights`.
*
* @param buffer A flat ArrayBuffer carrying the binary values of the tensors
* concatenated in the order specified in `specs`.
* @param specs Specifications of the names, dtypes and shapes of the tensors
* whose value are encoded by `buffer`.
* @return A map from tensor name to tensor value, with the names corresponding
* to names in `specs`.
* @throws Error, if any of the tensors has unsupported dtype.
*/
function decodeWeights(buffer, specs) {
// TODO(adarob, cais): Support quantization.
const out = {};
let float16Decode;
let offset = 0;
for (const spec of specs) {
const name = spec.name;
const dtype = spec.dtype;
const shape = spec.shape;
const size = Object(_util__WEBPACK_IMPORTED_MODULE_2__["sizeFromShape"])(shape);
let values;
if ("quantization" in spec) {
const quantization = spec.quantization;
if (quantization.dtype === "uint8" || quantization.dtype === "uint16") {
if (!("min" in quantization && "scale" in quantization)) {
throw new Error(
`Weight ${spec.name} with quantization ${quantization.dtype} ` +
`doesn't have corresponding metadata min and scale.`
);
}
} else if (quantization.dtype === "float16") {
if (dtype !== "float32") {
throw new Error(
`Weight ${spec.name} is quantized with ${quantization.dtype} ` +
`which only supports weights of type float32 not ${dtype}.`
);
}
} else {
throw new Error(
`Weight ${spec.name} has unknown ` +
`quantization dtype ${quantization.dtype}. ` +
`Supported quantization dtypes are: ` +
`'uint8', 'uint16', and 'float16'.`
);
}
const quantizationSizeFactor =
_types__WEBPACK_IMPORTED_MODULE_3__[/* DTYPE_VALUE_SIZE_MAP */ "a"][
quantization.dtype
];
const byteBuffer = buffer.slice(offset, offset + size * quantizationSizeFactor);
const quantizedArray =
quantization.dtype === "uint8"
? new Uint8Array(byteBuffer)
: new Uint16Array(byteBuffer);
if (dtype === "float32") {
if (quantization.dtype === "uint8" || quantization.dtype === "uint16") {
values = new Float32Array(quantizedArray.length);
for (let i = 0; i < quantizedArray.length; i++) {
const v = quantizedArray[i];
values[i] = v * quantization.scale + quantization.min;
}
} else if (quantization.dtype === "float16") {
if (float16Decode === undefined) {
float16Decode = getFloat16Decoder();
}
values = float16Decode(quantizedArray);
} else {
throw new Error(
`Unsupported quantization type ${quantization.dtype} ` +
`for weight type float32.`
);
}
} else if (dtype === "int32") {
if (quantization.dtype !== "uint8" && quantization.dtype !== "uint16") {
throw new Error(
`Unsupported quantization type ${quantization.dtype} ` +
`for weight type int32.`
);
}
values = new Int32Array(quantizedArray.length);
for (let i = 0; i < quantizedArray.length; i++) {
const v = quantizedArray[i];
values[i] = Math.round(v * quantization.scale + quantization.min);
}
} else {
throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);
}
offset += size * quantizationSizeFactor;
} else if (dtype === "string") {
const size = Object(_util__WEBPACK_IMPORTED_MODULE_2__["sizeFromShape"])(spec.shape);
values = [];
for (let i = 0; i < size; i++) {
const byteLength = new Uint32Array(
buffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH)
)[0];
offset += NUM_BYTES_STRING_LENGTH;
const bytes = new Uint8Array(buffer.slice(offset, offset + byteLength));
values.push(bytes);
offset += byteLength;
}
} else {
const dtypeFactor =
_types__WEBPACK_IMPORTED_MODULE_3__[/* DTYPE_VALUE_SIZE_MAP */ "a"][dtype];
const byteBuffer = buffer.slice(offset, offset + size * dtypeFactor);
if (dtype === "float32") {
values = new Float32Array(byteBuffer);
} else if (dtype === "int32") {
values = new Int32Array(byteBuffer);
} else if (dtype === "bool") {
values = new Uint8Array(byteBuffer);
} else if (dtype === "complex64") {
values = new Float32Array(byteBuffer);
const real = new Float32Array(values.length / 2);
const image = new Float32Array(values.length / 2);
for (let i = 0; i < real.length; i++) {
real[i] = values[i * 2];
image[i] = values[i * 2 + 1];
}
const realTensor = Object(
_ops_tensor_ops__WEBPACK_IMPORTED_MODULE_1__[/* tensor */ "f"]
)(real, shape, "float32");
const imageTensor = Object(
_ops_tensor_ops__WEBPACK_IMPORTED_MODULE_1__[/* tensor */ "f"]
)(image, shape, "float32");
out[name] = Object(_ops_complex__WEBPACK_IMPORTED_MODULE_0__[/* complex */ "a"])(
realTensor,
imageTensor
);
} else {
throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);
}
offset += size * dtypeFactor;
}
if (dtype !== "complex64") {
out[name] = Object(_ops_tensor_ops__WEBPACK_IMPORTED_MODULE_1__[/* tensor */ "f"])(
values,
shape,
dtype
);
}
}
return out;
}
/**
* Concatenate TypedArrays into an ArrayBuffer.
*/
function concatenateTypedArrays(xs) {
// TODO(adarob, cais): Support quantization.
if (xs === null) {
throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);
}
let totalByteLength = 0;
// `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'
// can have a different byte length from that of the `TypedArray` itself,
// for example, when the `TypedArray` is created from an offset in an
// `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match
// the `TypedArray` in byte length. If an element of `xs` does not show
// this property, a new `TypedArray` that satisfy this property will be
// constructed and pushed into `normalizedXs`.
const normalizedXs = [];
xs.forEach((x) => {
totalByteLength += x.byteLength;
// tslint:disable:no-any
normalizedXs.push(x.byteLength === x.buffer.byteLength ? x : new x.constructor(x));
if (
!(x instanceof Float32Array || x instanceof Int32Array || x instanceof Uint8Array)
) {
throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);
}
// tslint:enable:no-any
});
const y = new Uint8Array(totalByteLength);
let offset = 0;
normalizedXs.forEach((x) => {
y.set(new Uint8Array(x.buffer), offset);
offset += x.byteLength;
});
return y.buffer;
}
// Use Buffer on Node.js instead of Blob/atob/btoa
const useNodeBuffer =
typeof Buffer !== "undefined" &&
(typeof Blob === "undefined" ||
typeof atob === "undefined" ||
typeof btoa === "undefined");
/**
* Calculate the byte length of a JavaScript string.
*
* Note that a JavaScript string can contain wide characters, therefore the
* length of the string is not necessarily equal to the byte length.
*
* @param str Input string.
* @returns Byte length.
*/
function stringByteLength(str) {
if (useNodeBuffer) {
return Buffer.byteLength(str);
}
return new Blob([str]).size;
}
/**
* Encode an ArrayBuffer as a base64 encoded string.
*
* @param buffer `ArrayBuffer` to be converted.
* @returns A string that base64-encodes `buffer`.
*/
function arrayBufferToBase64String(buffer) {
if (useNodeBuffer) {
return Buffer.from(buffer).toString("base64");
}
const buf = new Uint8Array(buffer);
let s = "";
for (let i = 0, l = buf.length; i < l; i++) {
s += String.fromCharCode(buf[i]);
}
return btoa(s);
}
/**
* Decode a base64 string as an ArrayBuffer.
*
* @param str Base64 string.
* @returns Decoded `ArrayBuffer`.
*/
function base64StringToArrayBuffer(str) {
if (useNodeBuffer) {
const buf = Buffer.from(str, "base64");
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
}
const s = atob(str);
const buffer = new Uint8Array(s.length);
for (let i = 0; i < s.length; ++i) {
buffer.set([s.charCodeAt(i)], i);
}
return buffer.buffer;
}
/**
* Concatenate a number of ArrayBuffers into one.
*
* @param buffers A number of array buffers to concatenate.
* @returns Result of concatenating `buffers` in order.
*/
function concatenateArrayBuffers(buffers) {
if (buffers.length === 1) {
return buffers[0];
}
let totalByteLength = 0;
buffers.forEach((buffer) => {
totalByteLength += buffer.byteLength;
});
const temp = new Uint8Array(totalByteLength);
let offset = 0;
buffers.forEach((buffer) => {
temp.set(new Uint8Array(buffer), offset);
offset += buffer.byteLength;
});
return temp.buffer;
}
/**
* Get the basename of a path.
*
* Behaves in a way analogous to Linux's basename command.
*
* @param path
*/
function basename(path) {
const SEPARATOR = "/";
path = path.trim();
while (path.endsWith(SEPARATOR)) {
path = path.slice(0, path.length - 1);
}
const items = path.split(SEPARATOR);
return items[items.length - 1];
}
/**
* Populate ModelArtifactsInfo fields for a model with JSON topology.
* @param modelArtifacts
* @returns A ModelArtifactsInfo object.
*/
function getModelArtifactsInfoForJSON(modelArtifacts) {
if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
throw new Error("Expected JSON model topology, received ArrayBuffer.");
}
return {
dateSaved: new Date(),
modelTopologyType: "JSON",
modelTopologyBytes:
modelArtifacts.modelTopology == null
? 0
: stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),
weightSpecsBytes:
modelArtifacts.weightSpecs == null
? 0
: stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),
weightDataBytes:
modelArtifacts.weightData == null ? 0 : modelArtifacts.weightData.byteLength,
};
}
/**
* Computes mantisa table for casting Float16 to Float32
* See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
*
* @returns Uint32Array, 2048 mantissa lookup values.
*/
function computeFloat16MantisaTable() {
const convertMantissa = (i) => {
let m = i << 13;
let e = 0;
while ((m & 0x00800000) === 0) {
e -= 0x00800000;
m <<= 1;
}
m &= ~0x00800000;
e += 0x38800000;
return m | e;
};
const mantisaTable = new Uint32Array(2048);
mantisaTable[0] = 0;
for (let i = 1; i < 1024; i++) {
mantisaTable[i] = convertMantissa(i);
}
for (let i = 1024; i < 2048; i++) {
mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);
}
return mantisaTable;
}
/**
* Computes exponent table for casting Float16 to Float32
* See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
*
* @returns Uint32Array, 64 exponent lookup values.
*/
function computeFloat16ExponentTable() {
const exponentTable = new Uint32Array(64);
exponentTable[0] = 0;
exponentTable[31] = 0x47800000;
exponentTable[32] = 0x80000000;
exponentTable[63] = 0xc7800000;
for (let i = 1; i < 31; i++) {
exponentTable[i] = i << 23;
}
for (let i = 33; i < 63; i++) {
exponentTable[i] = 0x80000000 + ((i - 32) << 23);
}
return exponentTable;
}
/**
* Computes offset table for casting Float16 to Float32
* See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
*
* @returns Uint32Array, 6d offset values.
*/
function computeFloat16OffsetTable() {
const offsetTable = new Uint32Array(64);
for (let i = 0; i < 64; i++) {
offsetTable[i] = 1024;
}
offsetTable[0] = offsetTable[32] = 0;
return offsetTable;
}
/**
* Retrieve a Float16 decoder which will decode a ByteArray of Float16 values
* to a Float32Array.
*
* @returns Function (buffer: Uint16Array) => Float32Array which decodes
* the Uint16Array of Float16 bytes to a Float32Array.
*/
function getFloat16Decoder() {
// Algorithm is based off of http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
// Cache lookup tables
const mantisaTable = computeFloat16MantisaTable();
const exponentTable = computeFloat16ExponentTable();
const offsetTable = computeFloat16OffsetTable();
return (quantizedArray) => {
const buffer = new ArrayBuffer(4 * quantizedArray.length);
const bufferUint32View = new Uint32Array(buffer);
for (let index = 0; index < quantizedArray.length; index++) {
const float16Bits = quantizedArray[index];
const float32Bits =
mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +
exponentTable[float16Bits >> 10];
bufferUint32View[index] = float32Bits;
}
return new Float32Array(buffer);
};
}
//# sourceMappingURL=io_utils.js.map
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(39).Buffer));
/***/
},
/* 14 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "f", function () {
return /* binding */ iteratorFromItems;
});
__webpack_require__.d(__webpack_exports__, "e", function () {
return /* binding */ iteratorFromFunction;
});
__webpack_require__.d(__webpack_exports__, "d", function () {
return /* binding */ iteratorFromConcatenated;
});
__webpack_require__.d(__webpack_exports__, "g", function () {
return /* binding */ iteratorFromZipped;
});
__webpack_require__.d(__webpack_exports__, "a", function () {
return /* binding */ lazy_iterator_LazyIterator;
});
__webpack_require__.d(__webpack_exports__, "b", function () {
return /* binding */ lazy_iterator_OneToManyIterator;
});
__webpack_require__.d(__webpack_exports__, "c", function () {
return /* binding */ ZipMismatchMode;
});
// UNUSED EXPORTS: iteratorFromIncrementing, iteratorFromConcatenatedFunction, ChainedIterator, PrefetchIterator, ShuffleIterator
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js + 269 modules
var dist = __webpack_require__(0);
// EXTERNAL MODULE: ./node_modules/seedrandom/index.js
var seedrandom = __webpack_require__(20);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-data/dist/util/deep_map.js
var deep_map = __webpack_require__(19);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/util/deep_clone.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
function deepClone(container) {
return Object(deep_map["b" /* deepMap */])(container, cloneIfTensor);
}
// tslint:disable-next-line: no-any
function cloneIfTensor(item) {
if (item instanceof dist["Tensor"]) {
return { value: item.clone(), recurse: false };
} else if (Object(deep_map["e" /* isIterable */])(item)) {
return { value: null, recurse: true };
} else {
return { value: item, recurse: false };
}
}
//# sourceMappingURL=deep_clone.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/util/ring_buffer.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* A ring buffer, providing O(1) FIFO, LIFO, and related operations.
*/
class RingBuffer {
/**
* Constructs a `RingBuffer`.
* @param capacity The number of items that the buffer can accomodate.
*/
constructor(capacity) {
this.capacity = capacity;
// Note we store the indices in the range 0 <= index < 2*capacity.
// This allows us to distinguish the full from the empty case.
// See https://www.snellman.net/blog/archive/2016-12-13-ring-buffers/
this.begin = 0; // inclusive
this.end = 0; // exclusive
if (capacity == null) {
throw new RangeError("Can't create a ring buffer of unknown capacity.");
}
if (capacity < 1) {
throw new RangeError("Can't create ring buffer of capacity < 1.");
}
this.data = new Array(capacity);
this.doubledCapacity = 2 * capacity;
}
/**
* Map any index into the range 0 <= index < 2*capacity.
*/
wrap(index) {
// don't trust % on negative numbers
while (index < 0) {
index += this.doubledCapacity;
}
return index % this.doubledCapacity;
}
get(index) {
if (index < 0) {
throw new RangeError("Can't get item at a negative index.");
}
return this.data[index % this.capacity];
}
set(index, value) {
if (index < 0) {
throw new RangeError("Can't set item at a negative index.");
}
this.data[index % this.capacity] = value;
}
/**
* Returns the current number of items in the buffer.
*/
length() {
let length = this.end - this.begin;
if (length < 0) {
length = this.doubledCapacity + length;
}
return length;
}
/**
* Reports whether the buffer is full.
* @returns true if the number of items in the buffer equals its capacity, and
* false otherwise.
*/
isFull() {
return this.length() === this.capacity;
}
/**
* Reports whether the buffer is empty.
* @returns true if the number of items in the buffer equals zero, and
* false otherwise.
*/
isEmpty() {
return this.length() === 0;
}
/**
* Adds an item to the end of the buffer.
*/
push(value) {
if (this.isFull()) {
throw new RangeError("Ring buffer is full.");
}
this.set(this.end, value);
this.end = this.wrap(this.end + 1);
}
/**
* Adds many items to the end of the buffer, in order.
*/
pushAll(values) {
for (const value of values) {
this.push(value);
}
}
/**
* Removes and returns the last item in the buffer.
*/
pop() {
if (this.isEmpty()) {
throw new RangeError("Ring buffer is empty.");
}
this.end = this.wrap(this.end - 1);
const result = this.get(this.end);
this.set(this.end, undefined);
return result;
}
/**
* Adds an item to the beginning of the buffer.
*/
unshift(value) {
if (this.isFull()) {
throw new RangeError("Ring buffer is full.");
}
this.begin = this.wrap(this.begin - 1);
this.set(this.begin, value);
}
/**
* Removes and returns the first item in the buffer.
*/
shift() {
if (this.isEmpty()) {
throw new RangeError("Ring buffer is empty.");
}
const result = this.get(this.begin);
this.set(this.begin, undefined);
this.begin = this.wrap(this.begin + 1);
return result;
}
/**
* Removes and returns a specific item in the buffer, and moves the last item
* to the vacated slot. This is useful for implementing a shuffling stream.
* Note that this operation necessarily scrambles the original order.
*
* @param relativeIndex: the index of the item to remove, relative to the
* first item in the buffer (e.g., hiding the ring nature of the underlying
* storage).
*/
shuffleExcise(relativeIndex) {
if (this.isEmpty()) {
throw new RangeError("Ring buffer is empty.");
}
const index = this.wrap(this.begin + relativeIndex);
const result = this.get(index);
this.set(index, this.pop());
return result;
}
}
//# sourceMappingURL=ring_buffer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/util/growing_ring_buffer.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
class growing_ring_buffer_GrowingRingBuffer extends RingBuffer {
/**
* Constructs a `GrowingRingBuffer`.
*/
constructor() {
super(growing_ring_buffer_GrowingRingBuffer.INITIAL_CAPACITY);
}
isFull() {
return false;
}
push(value) {
if (super.isFull()) {
this.expand();
}
super.push(value);
}
unshift(value) {
if (super.isFull()) {
this.expand();
}
super.unshift(value);
}
/**
* Doubles the capacity of the buffer.
*/
expand() {
const newCapacity = this.capacity * 2;
const newData = new Array(newCapacity);
const len = this.length();
// Rotate the buffer to start at index 0 again, since we can't just
// allocate more space at the end.
for (let i = 0; i < len; i++) {
newData[i] = this.get(this.wrap(this.begin + i));
}
this.data = newData;
this.capacity = newCapacity;
this.doubledCapacity = 2 * this.capacity;
this.begin = 0;
this.end = len;
}
}
growing_ring_buffer_GrowingRingBuffer.INITIAL_CAPACITY = 32;
//# sourceMappingURL=growing_ring_buffer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/iterators/lazy_iterator.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
// Here we implement a simple asynchronous iterator.
// This lets us avoid using either third-party stream libraries or
// recent TypeScript language support requiring polyfills.
/**
* Create a `LazyIterator` from an array of items.
*/
function iteratorFromItems(items) {
return new lazy_iterator_ArrayIterator(items);
}
/**
* Create a `LazyIterator` of incrementing integers.
*/
function iteratorFromIncrementing(start) {
let i = start;
return iteratorFromFunction(() => ({ value: i++, done: false }));
}
/**
* Create a `LazyIterator` from a function.
*
* ```js
* let i = -1;
* const func = () =>
* ++i < 5 ? {value: i, done: false} : {value: null, done: true};
* const iter = tf.data.iteratorFromFunction(func);
* await iter.forEachAsync(e => console.log(e));
* ```
*
* @param func A function that produces data on each call.
*/
function iteratorFromFunction(func) {
return new FunctionCallIterator(func);
}
/**
* Create a `LazyIterator` by concatenating underlying streams, which are
* themselves provided as a stream.
*
* This can also be thought of as a "stream flatten" operation.
*
* @param baseIterators A stream of streams to be concatenated.
* @param baseErrorHandler An optional function that can intercept `Error`s
* raised during a `next()` call on the base stream. This function can decide
* whether the error should be propagated, whether the error should be
* ignored, or whether the base stream should be terminated.
*/
function iteratorFromConcatenated(baseIterators, baseErrorHandler) {
return new ChainedIterator(baseIterators, baseErrorHandler);
}
/**
* Create a `LazyIterator` by concatenating streams produced by calling a
* stream-generating function a given number of times.
*
* Since a `LazyIterator` is read-once, it cannot be repeated, but this
* function can be used to achieve a similar effect:
*
* LazyIterator.ofConcatenatedFunction(() => new MyIterator(), 6);
*
* @param iteratorFunc: A function that produces a new stream on each call.
* @param count: The number of times to call the function.
* @param baseErrorHandler An optional function that can intercept `Error`s
* raised during a `next()` call on the base stream. This function can decide
* whether the error should be propagated, whether the error should be
* ignored, or whether the base stream should be terminated.
*/
function iteratorFromConcatenatedFunction(iteratorFunc, count, baseErrorHandler) {
return iteratorFromConcatenated(
iteratorFromFunction(iteratorFunc).take(count),
baseErrorHandler
);
}
/**
* Create a `LazyIterator` by zipping together an array, dict, or nested
* structure of `LazyIterator`s (and perhaps additional constants).
*
* The underlying streams must provide elements in a consistent order such
* that they correspond.
*
* Typically, the underlying streams should have the same number of
* elements. If they do not, the behavior is determined by the
* `mismatchMode` argument.
*
* The nested structure of the `iterators` argument determines the
* structure of elements in the resulting iterator.
*
* @param iterators: An array or object containing LazyIterators at the
* leaves.
* @param mismatchMode: Determines what to do when one underlying iterator
* is exhausted before the others. `ZipMismatchMode.FAIL` (the default)
* causes an error to be thrown in this case. `ZipMismatchMode.SHORTEST`
* causes the zipped iterator to terminate with the furst underlying
* streams, so elements remaining on the longer streams are ignored.
* `ZipMismatchMode.LONGEST` causes the zipped stream to continue, filling
* in nulls for the exhausted streams, until all streams are exhausted.
*/
function iteratorFromZipped(iterators, mismatchMode = ZipMismatchMode.FAIL) {
return new lazy_iterator_ZipIterator(iterators, mismatchMode);
}
/**
* An asynchronous iterator, providing lazy access to a potentially
* unbounded stream of elements.
*
* Iterator can be obtained from a dataset:
* `const iter = await dataset.iterator();`
*/
class lazy_iterator_LazyIterator {
/**
* Collect all remaining elements of a bounded stream into an array.
* Obviously this will succeed only for small streams that fit in memory.
* Useful for testing.
*
* @returns A Promise for an array of stream elements, which will resolve
* when the stream is exhausted.
*/
async toArray() {
const result = [];
let x = await this.next();
while (!x.done) {
result.push(x.value);
x = await this.next();
}
return result;
}
/**
* Collect all elements of this dataset into an array with prefetching 100
* elements. This is useful for testing, because the prefetch changes the
* order in which the Promises are resolved along the processing pipeline.
* This may help expose bugs where results are dependent on the order of
* Promise resolution rather than on the logical order of the stream (i.e.,
* due to hidden mutable state).
*
* @returns A Promise for an array of stream elements, which will resolve
* when the stream is exhausted.
*/
async toArrayForTest() {
const stream = this.prefetch(100);
const result = [];
let x = await stream.next();
while (!x.done) {
result.push(x.value);
x = await stream.next();
}
return result;
}
/**
* Draw items from the stream until it is exhausted.
*
* This can be useful when the stream has side effects but no output. In
* that case, calling this function guarantees that the stream will be
* fully processed.
*/
async resolveFully() {
let x = await this.next();
while (!x.done) {
x = await this.next();
}
}
/**
* Draw items from the stream until it is exhausted, or a predicate fails.
*
* This can be useful when the stream has side effects but no output. In
* that case, calling this function guarantees that the stream will be
* fully processed.
*/
async resolveWhile(predicate) {
let x = await this.next();
let shouldContinue = predicate(x.value);
while (!x.done && shouldContinue) {
x = await this.next();
shouldContinue = predicate(x.value);
}
}
/**
* Handles errors thrown on this stream using a provided handler function.
*
* @param handler A function that handles any `Error` thrown during a `next()`
* call and returns true if the stream should continue (dropping the failed
* call) or false if the stream should quietly terminate. If the handler
* itself throws (or rethrows) an `Error`, that will be propagated.
*
* @returns A `LazyIterator` of elements passed through from upstream,
* possibly filtering or terminating on upstream `next()` calls that
* throw an `Error`.
*/
handleErrors(handler) {
return new ErrorHandlingLazyIterator(this, handler);
}
// TODO(soergel): Implement reduce() etc.
/**
* Filters this stream according to `predicate`.
*
* @param predicate A function mapping a stream element to a boolean or a
* `Promise` for one.
*
* @returns A `LazyIterator` of elements for which the predicate was true.
*/
filter(predicate) {
return new lazy_iterator_FilterIterator(this, predicate);
}
/**
* Maps this stream through a 1-to-1 transform.
*
* @param transform A function mapping a stream element to a transformed
* element.
*
* @returns A `LazyIterator` of transformed elements.
*/
map(transform) {
return new lazy_iterator_MapIterator(this, transform);
}
/**
* Maps this stream through an async 1-to-1 transform.
*
* @param transform A function mapping a stream element to a `Promise` for a
* transformed stream element.
*
* @returns A `LazyIterator` of transformed elements.
*/
mapAsync(transform) {
return new lazy_iterator_AsyncMapIterator(this, transform);
}
/**
* Maps this stream through a 1-to-1 transform, forcing serial execution.
*
* @param transform A function mapping a stream element to a transformed
* element.
*
* @returns A `LazyIterator` of transformed elements.
*/
serialMapAsync(transform) {
return new lazy_iterator_AsyncMapIterator(this, transform).serial();
}
/**
* Maps this stream through a 1-to-many transform.
*
* @param transform A function mapping a stream element to an array of
* transformed elements.
*
* @returns A `DataStream` of transformed elements.
*/
flatmap(transform) {
return new lazy_iterator_FlatmapIterator(this, transform);
}
/**
* Apply a function to every element of the stream.
*
* @param f A function to apply to each stream element.
*/
async forEachAsync(f) {
return this.map(f).resolveFully();
}
/**
* Apply a function to every element of the stream, forcing serial execution.
*
* @param f A function to apply to each stream element. Should return 'true'
* to indicate that the stream should continue, or 'false' to cause it to
* terminate.
*/
async serialForEach(f) {
return this.serialMapAsync(f).resolveWhile((x) => x === true);
}
/**
* Groups elements into batches, represented as arrays of elements.
*
* We can think of the elements of this iterator as 'rows' (even if they are
* nested structures). By the same token, consecutive values for a given
* key within the elements form a 'column'. This matches the usual sense of
* 'row' and 'column' when processing tabular data (e.g., parsing a CSV).
*
* Thus, "Row-major" means that the resulting batch is simply a collection of
* rows: `[row1, row2, row3, ...]`. This is contrast to the column-major
* form, which is needed for vectorized computation.
*
* @param batchSize The number of elements desired per batch.
* @param smallLastBatch Whether to emit the final batch when it has fewer
* than batchSize elements. Default true.
* @returns A `LazyIterator` of batches of elements, represented as arrays
* of the original element type.
*/
rowMajorBatch(batchSize, smallLastBatch = true) {
return new RowMajorBatchIterator(this, batchSize, smallLastBatch);
}
/**
* Groups elements into batches, represented in column-major form.
*
* We can think of the elements of this iterator as 'rows' (even if they are
* nested structures). By the same token, consecutive values for a given
* key within the elements form a 'column'. This matches the usual sense of
* 'row' and 'column' when processing tabular data (e.g., parsing a CSV).
*
* Thus, "column-major" means that the resulting batch is a (potentially
* nested) structure representing the columns. Each column entry, then,
* contains a collection of the values found in that column for a range of
* input elements. This representation allows for vectorized computation, in
* contrast to the row-major form.
*
* The inputs should all have the same nested structure (i.e., of arrays and
* dicts). The result is a single object with the same nested structure,
* where the leaves are arrays collecting the values of the inputs at that
* location (or, optionally, the result of a custom function applied to those
* arrays).
*
* @param batchSize The number of elements desired per batch.
* @param smallLastBatch Whether to emit the final batch when it has fewer
* than batchSize elements. Default true.
* @param zipFn: (optional) A function that expects an array of elements at a
* single node of the object tree, and returns a `DeepMapResult`. The
* `DeepMapResult` either provides a result value for that node (i.e.,
* representing the subtree), or indicates that the node should be processed
* recursively. The default zipFn recurses as far as possible and places
* arrays at the leaves.
* @returns A `LazyIterator` of batches of elements, represented as an object
* with collections at the leaves.
*/
columnMajorBatch(
batchSize,
smallLastBatch = true,
// tslint:disable-next-line:no-any
zipFn = deep_map["f" /* zipToList */]
) {
// First collect the desired number of input elements as a row-major batch.
const rowBatches = this.rowMajorBatch(batchSize, smallLastBatch);
// Now 'rotate' or 'pivot' the data, collecting all values from each column
// in the batch (i.e., for each key within the elements) into an array.
return rowBatches.map((x) => Object(deep_map["d" /* deepZip */])(x, zipFn));
}
/**
* Concatenate this `LazyIterator` with another.
*
* @param iterator A `LazyIterator` to be concatenated onto this one.
* @param baseErrorHandler An optional function that can intercept `Error`s
* raised during a `next()` call on the base stream. This function can
* decide whether the error should be propagated, whether the error should
* be ignored, or whether the base stream should be terminated.
* @returns A `LazyIterator`.
*/
concatenate(iterator, baseErrorHandler) {
return new ChainedIterator(iteratorFromItems([this, iterator]), baseErrorHandler);
}
/**
* Limits this stream to return at most `count` items.
*
* @param count The maximum number of items to provide from the stream. If
* a negative or undefined value is given, the entire stream is returned
* unaltered.
*/
take(count) {
if (count < 0 || count == null) {
return this;
}
return new TakeIterator(this, count);
}
/**
* Skips the first `count` items in this stream.
*
* @param count The number of items to skip. If a negative or undefined
* value is given, the entire stream is returned unaltered.
*/
skip(count) {
if (count < 0 || count == null) {
return this;
}
return new lazy_iterator_SkipIterator(this, count);
}
/**
* Prefetch the first `bufferSize` items in this stream.
*
* Note this prefetches Promises, but makes no guarantees about when those
* Promises resolve.
*
* @param bufferSize: An integer specifying the number of elements to be
* prefetched.
*/
prefetch(bufferSize) {
return new lazy_iterator_PrefetchIterator(this, bufferSize);
}
// TODO(soergel): deep sharded shuffle, where supported
/**
* Randomly shuffles the elements of this stream.
*
* @param bufferSize: An integer specifying the number of elements from
* this stream from which the new stream will sample.
* @param seed: (Optional.) An integer specifying the random seed that
* will be used to create the distribution.
*/
shuffle(windowSize, seed) {
return new lazy_iterator_ShuffleIterator(this, windowSize, seed);
}
/**
* Force an iterator to execute serially: each next() call will await the
* prior one, so that they cannot execute concurrently.
*/
serial() {
return new SerialIterator(this);
}
}
// ============================================================================
// The following private classes serve to implement the chainable methods
// on LazyIterator. Unfortunately they can't be placed in separate files,
// due to resulting trouble with circular imports.
// ============================================================================
// Iterators that just extend LazyIterator directly
// ============================================================================
class lazy_iterator_ArrayIterator extends lazy_iterator_LazyIterator {
constructor(items) {
super();
this.items = items;
this.trav = 0;
}
summary() {
return `Array of ${this.items.length} items`;
}
async next() {
if (this.trav >= this.items.length) {
return { value: null, done: true };
}
const item = this.items[this.trav];
this.trav++;
return { value: deepClone(item), done: false };
}
}
class FunctionCallIterator extends lazy_iterator_LazyIterator {
constructor(nextFn) {
super();
this.nextFn = nextFn;
}
summary() {
return `Function call`;
}
async next() {
try {
return this.nextFn();
} catch (e) {
// Modify the error message but leave the stack trace intact
e.message = `Error thrown while iterating through a dataset: ${e.message}`;
throw e;
}
}
}
class SerialIterator extends lazy_iterator_LazyIterator {
constructor(upstream) {
super();
this.upstream = upstream;
this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Serial`;
}
async next() {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
async serialNext() {
return this.upstream.next();
}
}
class lazy_iterator_SkipIterator extends lazy_iterator_LazyIterator {
constructor(upstream, maxCount) {
super();
this.upstream = upstream;
this.maxCount = maxCount;
// Local state that should not be clobbered by out-of-order execution.
this.count = 0;
this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Skip`;
}
async next() {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
async serialNext() {
// TODO(soergel): consider tradeoffs of reading in parallel, eg.
// collecting next() promises in an Array and then waiting for
// Promise.all() of those. Benefit: pseudo-parallel execution. Drawback:
// maybe delayed GC.
while (this.count++ < this.maxCount) {
const skipped = await this.upstream.next();
// short-circuit if upstream is already empty
if (skipped.done) {
return skipped;
}
dist["dispose"](skipped.value);
}
return this.upstream.next();
}
}
class TakeIterator extends lazy_iterator_LazyIterator {
constructor(upstream, maxCount) {
super();
this.upstream = upstream;
this.maxCount = maxCount;
this.count = 0;
}
summary() {
return `${this.upstream.summary()} -> Take`;
}
async next() {
if (this.count++ >= this.maxCount) {
return { value: null, done: true };
}
return this.upstream.next();
}
}
// Note this batch just groups items into row-wise element arrays.
// Rotating these to a column-wise representation happens only at the dataset
// level.
class RowMajorBatchIterator extends lazy_iterator_LazyIterator {
constructor(upstream, batchSize, enableSmallLastBatch = true) {
super();
this.upstream = upstream;
this.batchSize = batchSize;
this.enableSmallLastBatch = enableSmallLastBatch;
this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> RowMajorBatch`;
}
async next() {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
async serialNext() {
const batch = [];
while (batch.length < this.batchSize) {
const item = await this.upstream.next();
if (item.done) {
if (this.enableSmallLastBatch && batch.length > 0) {
return { value: batch, done: false };
}
return { value: null, done: true };
}
batch.push(item.value);
}
return { value: batch, done: false };
}
}
class lazy_iterator_FilterIterator extends lazy_iterator_LazyIterator {
constructor(upstream, predicate) {
super();
this.upstream = upstream;
this.predicate = predicate;
this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Filter`;
}
async next() {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
async serialNext() {
while (true) {
const item = await this.upstream.next();
if (item.done || this.predicate(item.value)) {
return item;
}
dist["dispose"](item.value);
}
}
}
class lazy_iterator_MapIterator extends lazy_iterator_LazyIterator {
constructor(upstream, transform) {
super();
this.upstream = upstream;
this.transform = transform;
}
summary() {
return `${this.upstream.summary()} -> Map`;
}
async next() {
const item = await this.upstream.next();
if (item.done) {
return { value: null, done: true };
}
const inputTensors = dist["tensor_util"].getTensorsInContainer(item.value);
// Careful: the transform may mutate the item in place.
// That's why we have to remember the input Tensors above, and then
// below dispose only those that were not passed through to the output.
// Note too that the transform function is responsible for tidying
// any intermediate Tensors. Here we are concerned only about the
// inputs.
const mapped = this.transform(item.value);
const outputTensors = dist["tensor_util"].getTensorsInContainer(mapped);
// TODO(soergel) faster intersection
// TODO(soergel) move to tf.disposeExcept(in, out)?
for (const t of inputTensors) {
if (!dist["tensor_util"].isTensorInList(t, outputTensors)) {
t.dispose();
}
}
return { value: mapped, done: false };
}
}
class ErrorHandlingLazyIterator extends lazy_iterator_LazyIterator {
constructor(upstream, handler) {
super();
this.upstream = upstream;
this.handler = handler;
this.count = 0;
this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> handleErrors`;
}
async next() {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
async serialNext() {
while (true) {
try {
return await this.upstream.next();
} catch (e) {
if (!this.handler(e)) {
return { value: null, done: true };
}
// If the handler returns true, loop and fetch the next upstream item.
// If the upstream iterator throws an endless stream of errors, and if
// the handler says to ignore them, then we loop forever here. That is
// the correct behavior-- it's up to the handler to decide when to stop.
}
}
}
}
class lazy_iterator_AsyncMapIterator extends lazy_iterator_LazyIterator {
constructor(upstream, transform) {
super();
this.upstream = upstream;
this.transform = transform;
}
summary() {
return `${this.upstream.summary()} -> AsyncMap`;
}
async next() {
const item = await this.upstream.next();
if (item.done) {
return { value: null, done: true };
}
const inputTensors = dist["tensor_util"].getTensorsInContainer(item.value);
// Careful: the transform may mutate the item in place.
// That's why we have to remember the input Tensors above, and then
// below dispose only those that were not passed through to the output.
// Note too that the transform function is responsible for tidying
// any intermediate Tensors. Here we are concerned only about the
// inputs.
const mapped = await this.transform(item.value);
const outputTensors = dist["tensor_util"].getTensorsInContainer(mapped);
// TODO(soergel) faster intersection
// TODO(soergel) move to tf.disposeExcept(in, out)?
for (const t of inputTensors) {
if (!dist["tensor_util"].isTensorInList(t, outputTensors)) {
t.dispose();
}
}
return { value: mapped, done: false };
}
}
// Iterators that maintain a queue of pending items
// ============================================================================
/**
* A base class for transforming streams that operate by maintaining an
* output queue of elements that are ready to return via next(). This is
* commonly required when the transformation is 1-to-many: A call to next()
* may trigger a call to the underlying stream, which will produce many
* mapped elements of this stream-- of which we need to return only one, so
* we have to queue the rest.
*/
class lazy_iterator_OneToManyIterator extends lazy_iterator_LazyIterator {
constructor() {
super();
this.outputQueue = new growing_ring_buffer_GrowingRingBuffer();
this.lastRead = Promise.resolve({ value: null, done: false });
}
async next() {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
async serialNext() {
// Fetch so that the queue contains at least one item if possible.
// If the upstream source is exhausted, AND there are no items left in
// the output queue, then this stream is also exhausted.
while (this.outputQueue.length() === 0) {
// TODO(soergel): consider parallel reads.
if (!(await this.pump())) {
return { value: null, done: true };
}
}
return { value: this.outputQueue.shift(), done: false };
}
}
class lazy_iterator_FlatmapIterator extends lazy_iterator_OneToManyIterator {
constructor(upstream, transform) {
super();
this.upstream = upstream;
this.transform = transform;
}
summary() {
return `${this.upstream.summary()} -> Flatmap`;
}
async pump() {
const item = await this.upstream.next();
if (item.done) {
return false;
}
const inputTensors = dist["tensor_util"].getTensorsInContainer(item.value);
// Careful: the transform may mutate the item in place.
// that's why we have to remember the input Tensors above, and then
// below dispose only those that were not passed through to the output.
// Note too that the transform function is responsible for tidying any
// intermediate Tensors. Here we are concerned only about the inputs.
const mappedArray = this.transform(item.value);
const outputTensors = dist["tensor_util"].getTensorsInContainer(mappedArray);
this.outputQueue.pushAll(mappedArray);
// TODO(soergel) faster intersection, and deduplicate outputTensors
// TODO(soergel) move to tf.disposeExcept(in, out)?
for (const t of inputTensors) {
if (!dist["tensor_util"].isTensorInList(t, outputTensors)) {
t.dispose();
}
}
return true;
}
}
/**
* Provides a `LazyIterator` that concatenates a stream of underlying
* streams.
*
* Doing this in a concurrency-safe way requires some trickery. In
* particular, we want this stream to return the elements from the
* underlying streams in the correct order according to when next() was
* called, even if the resulting Promises resolve in a different order.
*/
class ChainedIterator extends lazy_iterator_LazyIterator {
constructor(iterators, baseErrorHandler) {
super();
this.baseErrorHandler = baseErrorHandler;
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
this.lastRead = null;
// Local state that should not be clobbered by out-of-order execution.
this.iterator = null;
this.moreIterators = iterators;
}
summary() {
const upstreamSummaries = "TODO: fill in upstream of chained summaries";
return `${upstreamSummaries} -> Chained`;
}
async next() {
this.lastRead = this.readFromChain(this.lastRead);
return this.lastRead;
}
async readFromChain(lastRead) {
// Must await on the previous read since the previous read may have advanced
// the stream of streams, from which we need to read.
// This is unfortunate since we can't parallelize reads. Which means
// prefetching of chained streams is a no-op.
// One solution is to prefetch immediately upstream of this.
await lastRead;
if (this.iterator == null) {
const iteratorResult = await this.moreIterators.next();
if (iteratorResult.done) {
// No more streams to stream from.
return { value: null, done: true };
}
this.iterator = iteratorResult.value;
if (this.baseErrorHandler != null) {
this.iterator = this.iterator.handleErrors(this.baseErrorHandler);
}
}
const itemResult = await this.iterator.next();
if (itemResult.done) {
this.iterator = null;
return this.readFromChain(lastRead);
}
return itemResult;
}
}
var ZipMismatchMode;
(function (ZipMismatchMode) {
ZipMismatchMode[(ZipMismatchMode["FAIL"] = 0)] = "FAIL";
ZipMismatchMode[(ZipMismatchMode["SHORTEST"] = 1)] = "SHORTEST";
ZipMismatchMode[(ZipMismatchMode["LONGEST"] = 2)] = "LONGEST"; // use nulls for exhausted streams; use up the longest stream.
})(ZipMismatchMode || (ZipMismatchMode = {}));
/**
* Provides a `LazyIterator` that zips together an array, dict, or nested
* structure of `LazyIterator`s (and perhaps additional constants).
*
* The underlying streams must provide elements in a consistent order such
* that they correspond.
*
* Typically, the underlying streams should have the same number of
* elements. If they do not, the behavior is determined by the
* `mismatchMode` argument.
*
* The nested structure of the `iterators` argument determines the
* structure of elements in the resulting iterator.
*
* Doing this in a concurrency-safe way requires some trickery. In
* particular, we want this stream to return the elements from the
* underlying streams in the correct order according to when next() was
* called, even if the resulting Promises resolve in a different order.
*
* @param iterators: An array or object containing LazyIterators at the
* leaves.
* @param mismatchMode: Determines what to do when one underlying iterator
* is exhausted before the others. `ZipMismatchMode.FAIL` (the default)
* causes an error to be thrown in this case. `ZipMismatchMode.SHORTEST`
* causes the zipped iterator to terminate with the furst underlying
* streams, so elements remaining on the longer streams are ignored.
* `ZipMismatchMode.LONGEST` causes the zipped stream to continue, filling
* in nulls for the exhausted streams, until all streams are exhausted.
*/
class lazy_iterator_ZipIterator extends lazy_iterator_LazyIterator {
constructor(iterators, mismatchMode = ZipMismatchMode.FAIL) {
super();
this.iterators = iterators;
this.mismatchMode = mismatchMode;
this.count = 0;
this.currentPromise = null;
}
summary() {
const upstreamSummaries = "TODO: fill in upstream of zip summaries";
return `{${upstreamSummaries}} -> Zip`;
}
async nextState(afterState) {
// This chaining ensures that the underlying next() are not even called
// before the previous ones have resolved.
await afterState;
// Collect underlying iterator "done" signals as a side effect in
// getNext()
let numIterators = 0;
let iteratorsDone = 0;
function getNext(container) {
if (container instanceof lazy_iterator_LazyIterator) {
const result = container.next();
return {
value: result.then((x) => {
numIterators++;
if (x.done) {
iteratorsDone++;
}
return x.value;
}),
recurse: false,
};
} else {
return { value: null, recurse: true };
}
}
const mapped = await Object(deep_map["c" /* deepMapAndAwaitAll */])(
this.iterators,
getNext
);
if (numIterators === iteratorsDone) {
// The streams have all ended.
return { value: null, done: true };
}
if (iteratorsDone > 0) {
switch (this.mismatchMode) {
case ZipMismatchMode.FAIL:
throw new Error(
"Zipped streams should have the same length. " +
`Mismatched at element ${this.count}.`
);
case ZipMismatchMode.SHORTEST:
return { value: null, done: true };
case ZipMismatchMode.LONGEST:
default:
// Continue. The exhausted streams already produced value: null.
}
}
this.count++;
return { value: mapped, done: false };
}
async next() {
this.currentPromise = this.nextState(this.currentPromise);
return this.currentPromise;
}
}
// Iterators that maintain a ring buffer of pending promises
// ============================================================================
/**
* A stream that prefetches a given number of items from an upstream source,
* returning them in FIFO order.
*
* Note this prefetches Promises, but makes no guarantees about when those
* Promises resolve.
*/
class lazy_iterator_PrefetchIterator extends lazy_iterator_LazyIterator {
constructor(upstream, bufferSize) {
super();
this.upstream = upstream;
this.bufferSize = bufferSize;
this.buffer = new RingBuffer(bufferSize);
}
summary() {
return `${this.upstream.summary()} -> Prefetch`;
}
/**
* Refill the prefetch buffer. Returns only after the buffer is full, or
* the upstream source is exhausted.
*/
refill() {
while (!this.buffer.isFull()) {
const v = this.upstream.next();
this.buffer.push(v);
}
}
next() {
this.refill();
// This shift will never throw an error because the buffer is always
// full after a refill. If the stream is exhausted, the buffer will be
// full of Promises that will resolve to the end-of-stream signal.
return this.buffer.shift();
}
}
/**
* A stream that performs a sliding-window random shuffle on an upstream
* source. This is like a `PrefetchIterator` except that the items are
* returned in randomized order. Mixing naturally improves as the buffer
* size increases.
*/
class lazy_iterator_ShuffleIterator extends lazy_iterator_PrefetchIterator {
constructor(upstream, windowSize, seed) {
super(upstream, windowSize);
this.upstream = upstream;
this.windowSize = windowSize;
// Local state that should not be clobbered by out-of-order execution.
this.upstreamExhausted = false;
this.random = seedrandom["alea"](seed || dist["util"].now().toString());
this.lastRead = Promise.resolve({ value: null, done: false });
}
async next() {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
randomInt(max) {
return Math.floor(this.random() * max);
}
chooseIndex() {
return this.randomInt(this.buffer.length());
}
async serialNext() {
// TODO(soergel): consider performance
if (!this.upstreamExhausted) {
this.refill();
}
while (!this.buffer.isEmpty()) {
const chosenIndex = this.chooseIndex();
const result = await this.buffer.shuffleExcise(chosenIndex);
if (result.done) {
this.upstreamExhausted = true;
} else {
this.refill();
return result;
}
}
return { value: null, done: true };
}
}
//# sourceMappingURL=lazy_iterator.js.map
/***/
},
/* 15 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (Buffer) {
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return OperationMapper;
});
/* unused harmony export decodeBase64 */
/* unused harmony export parseStringParam */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function () {
return getStringParam;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return getBoolParam;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function () {
return getNumberParam;
});
/* unused harmony export parseDtypeParam */
/* unused harmony export getFuncParam */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function () {
return getDtypeParam;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function () {
return getDtypeArrayParam;
});
/* unused harmony export parseTensorShapeParam */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function () {
return getTensorShapeParam;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function () {
return getNumericArrayParam;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function () {
return getStringArrayParam;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function () {
return getTensorShapeArrayParam;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return getBoolArrayParam;
});
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(0);
/* harmony import */ var _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__ =
__webpack_require__(21);
/* harmony import */ var _custom_op_register__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(24);
/* harmony import */ var _executors_utils__WEBPACK_IMPORTED_MODULE_3__ =
__webpack_require__(2);
/* harmony import */ var _op_list_arithmetic__WEBPACK_IMPORTED_MODULE_4__ =
__webpack_require__(41);
/* harmony import */ var _op_list_basic_math__WEBPACK_IMPORTED_MODULE_5__ =
__webpack_require__(42);
/* harmony import */ var _op_list_control__WEBPACK_IMPORTED_MODULE_6__ =
__webpack_require__(43);
/* harmony import */ var _op_list_convolution__WEBPACK_IMPORTED_MODULE_7__ =
__webpack_require__(44);
/* harmony import */ var _op_list_creation__WEBPACK_IMPORTED_MODULE_8__ =
__webpack_require__(45);
/* harmony import */ var _op_list_dynamic__WEBPACK_IMPORTED_MODULE_9__ =
__webpack_require__(46);
/* harmony import */ var _op_list_evaluation__WEBPACK_IMPORTED_MODULE_10__ =
__webpack_require__(47);
/* harmony import */ var _op_list_graph__WEBPACK_IMPORTED_MODULE_11__ =
__webpack_require__(48);
/* harmony import */ var _op_list_image__WEBPACK_IMPORTED_MODULE_12__ =
__webpack_require__(49);
/* harmony import */ var _op_list_logical__WEBPACK_IMPORTED_MODULE_13__ =
__webpack_require__(50);
/* harmony import */ var _op_list_matrices__WEBPACK_IMPORTED_MODULE_14__ =
__webpack_require__(51);
/* harmony import */ var _op_list_normalization__WEBPACK_IMPORTED_MODULE_15__ =
__webpack_require__(52);
/* harmony import */ var _op_list_reduction__WEBPACK_IMPORTED_MODULE_16__ =
__webpack_require__(53);
/* harmony import */ var _op_list_slice_join__WEBPACK_IMPORTED_MODULE_17__ =
__webpack_require__(54);
/* harmony import */ var _op_list_spectral__WEBPACK_IMPORTED_MODULE_18__ =
__webpack_require__(55);
/* harmony import */ var _op_list_transformation__WEBPACK_IMPORTED_MODULE_19__ =
__webpack_require__(56);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class OperationMapper {
// Singleton instance for the mapper
static get Instance() {
return this._instance || (this._instance = new this());
}
// Loads the op mapping from the JSON file.
constructor() {
const ops = [
_op_list_arithmetic__WEBPACK_IMPORTED_MODULE_4__,
_op_list_basic_math__WEBPACK_IMPORTED_MODULE_5__,
_op_list_control__WEBPACK_IMPORTED_MODULE_6__,
_op_list_convolution__WEBPACK_IMPORTED_MODULE_7__,
_op_list_creation__WEBPACK_IMPORTED_MODULE_8__,
_op_list_dynamic__WEBPACK_IMPORTED_MODULE_9__,
_op_list_evaluation__WEBPACK_IMPORTED_MODULE_10__,
_op_list_logical__WEBPACK_IMPORTED_MODULE_13__,
_op_list_image__WEBPACK_IMPORTED_MODULE_12__,
_op_list_graph__WEBPACK_IMPORTED_MODULE_11__,
_op_list_matrices__WEBPACK_IMPORTED_MODULE_14__,
_op_list_normalization__WEBPACK_IMPORTED_MODULE_15__,
_op_list_reduction__WEBPACK_IMPORTED_MODULE_16__,
_op_list_slice_join__WEBPACK_IMPORTED_MODULE_17__,
_op_list_spectral__WEBPACK_IMPORTED_MODULE_18__,
_op_list_transformation__WEBPACK_IMPORTED_MODULE_19__,
];
const mappersJson = [].concat(...ops.map((op) => op.json));
this.opMappers = mappersJson.reduce((map, mapper) => {
map[mapper.tfOpName] = mapper;
return map;
}, {});
}
// Converts the model from Tensorflow GraphDef to local representation for
// TensorFlow.js API
transformGraph(graph, signature = {}) {
const tfNodes = graph.node;
const placeholders = [];
const weights = [];
const nodes = tfNodes.reduce((map, node) => {
map[node.name] = this.mapNode(node);
if (node.op.startsWith("Placeholder")) {
placeholders.push(map[node.name]);
}
if (node.op === "Const") {
weights.push(map[node.name]);
}
return map;
}, {});
let inputs = [];
const outputs = [];
let inputNodeNameToKey = {};
let outputNodeNameToKey = {};
if (signature != null) {
inputNodeNameToKey = this.mapSignatureEntries(signature.inputs);
outputNodeNameToKey = this.mapSignatureEntries(signature.outputs);
}
const allNodes = Object.keys(nodes);
allNodes.forEach((key) => {
const node = nodes[key];
node.inputNames.forEach((name) => {
const [nodeName] = Object(
_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "a"]
)(name);
node.inputs.push(nodes[nodeName]);
nodes[nodeName].children.push(node);
});
});
// if signature has not outputs set, add any node that does not have
// outputs.
if (Object.keys(outputNodeNameToKey).length === 0) {
allNodes.forEach((key) => {
const node = nodes[key];
if (node.children.length === 0) {
outputs.push(node);
}
});
} else {
Object.keys(outputNodeNameToKey).forEach((name) => {
const [nodeName] = Object(
_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "a"]
)(name);
const node = nodes[nodeName];
if (node != null) {
node.signatureKey = outputNodeNameToKey[name];
outputs.push(node);
}
});
}
if (Object.keys(inputNodeNameToKey).length > 0) {
Object.keys(inputNodeNameToKey).forEach((name) => {
const [nodeName] = Object(
_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "a"]
)(name);
const node = nodes[nodeName];
if (node) {
node.signatureKey = inputNodeNameToKey[name];
inputs.push(node);
}
});
} else {
inputs = placeholders;
}
let functions = {};
if (graph.library != null && graph.library.function != null) {
functions = graph.library.function.reduce((functions, func) => {
functions[func.signature.name] = this.mapFunction(func);
return functions;
}, {});
}
return {
nodes,
inputs,
outputs,
weights,
placeholders,
signature,
functions,
};
}
mapSignatureEntries(entries) {
return Object.keys(entries || {}).reduce((prev, curr) => {
prev[entries[curr].name] = curr;
return prev;
}, {});
}
mapNode(node) {
// Unsupported ops will cause an error at run-time (not parse time), since
// they may not be used by the actual execution subgraph.
const mapper =
Object(_custom_op_register__WEBPACK_IMPORTED_MODULE_2__[/* getRegisteredOp */ "b"])(
node.op
) ||
this.opMappers[node.op] ||
{};
if (node.attr == null) {
node.attr = {};
}
const newNode = {
name: node.name,
op: node.op,
category: mapper.category,
inputNames: (node.input || []).map((input) =>
input.startsWith("^") ? input.substr(1) : input
),
inputs: [],
children: [],
inputParams: {},
attrParams: {},
rawAttrs: node.attr,
};
if (mapper.inputs != null) {
newNode.inputParams = mapper.inputs.reduce((map, param) => {
map[param.name] = {
type: param.type,
inputIndexStart: param.start,
inputIndexEnd: param.end,
};
return map;
}, {});
}
if (mapper.attrs != null) {
newNode.attrParams = mapper.attrs.reduce((map, param) => {
const type = param.type;
let value = undefined;
switch (param.type) {
case "string":
value = getStringParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getStringParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case "string[]":
value = getStringArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getStringArrayParam(
node.attr,
param.tfDeprecatedName,
param.defaultValue
);
}
break;
case "number":
value = getNumberParam(node.attr, param.tfName, param.defaultValue || 0);
if (value === undefined && !!param.tfDeprecatedName) {
value = getNumberParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case "number[]":
value = getNumericArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getNumericArrayParam(
node.attr,
param.tfDeprecatedName,
param.defaultValue
);
}
break;
case "bool":
value = getBoolParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getBoolParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case "bool[]":
value = getBoolArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getBoolArrayParam(
node.attr,
param.tfDeprecatedName,
param.defaultValue
);
}
break;
case "shape":
value = getTensorShapeParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getTensorShapeParam(
node.attr,
param.tfDeprecatedName,
param.defaultValue
);
}
break;
case "shape[]":
value = getTensorShapeArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getTensorShapeArrayParam(
node.attr,
param.tfDeprecatedName,
param.defaultValue
);
}
break;
case "dtype":
value = getDtypeParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getDtypeParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case "dtype[]":
value = getDtypeArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getDtypeArrayParam(
node.attr,
param.tfDeprecatedName,
param.defaultValue
);
}
break;
case "func":
value = getFuncParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getFuncParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case "tensor":
case "tensors":
break;
default:
throw new Error(`Unsupported param type: ${param.type} for op: ${node.op}`);
}
map[param.name] = { value, type };
return map;
}, {});
}
return newNode;
}
// map the TFunctionDef to TFJS graph object
mapFunction(functionDef) {
const tfNodes = functionDef.nodeDef;
const placeholders = [];
const weights = [];
let nodes = {};
if (tfNodes != null) {
nodes = tfNodes.reduce((map, node) => {
map[node.name] = this.mapNode(node);
if (node.op === "Const") {
weights.push(map[node.name]);
}
return map;
}, {});
}
const inputs = [];
const outputs = [];
functionDef.signature.inputArg.forEach((arg) => {
const [nodeName] = Object(
_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "a"]
)(arg.name);
const node = {
name: nodeName,
op: "Placeholder",
inputs: [],
inputNames: [],
category: "graph",
inputParams: {},
attrParams: { dtype: { value: parseDtypeParam(arg.type), type: "dtype" } },
children: [],
};
node.signatureKey = arg.name;
inputs.push(node);
nodes[nodeName] = node;
});
const allNodes = Object.keys(nodes);
allNodes.forEach((key) => {
const node = nodes[key];
node.inputNames.forEach((name) => {
const [nodeName] = Object(
_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "a"]
)(name);
node.inputs.push(nodes[nodeName]);
nodes[nodeName].children.push(node);
});
});
const returnNodeMap = functionDef.ret;
functionDef.signature.outputArg.forEach((output) => {
const [nodeName, index] = Object(
_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "a"]
)(returnNodeMap[output.name]);
const node = nodes[nodeName];
if (node != null) {
node.defaultOutput = index;
outputs.push(node);
}
});
const signature = this.mapArgsToSignature(functionDef);
return { nodes, inputs, outputs, weights, placeholders, signature };
}
mapArgsToSignature(functionDef) {
return {
methodName: functionDef.signature.name,
inputs: functionDef.signature.inputArg.reduce((map, arg) => {
map[arg.name] = this.mapArgToTensorInfo(arg);
return map;
}, {}),
outputs: functionDef.signature.outputArg.reduce((map, arg) => {
map[arg.name] = this.mapArgToTensorInfo(arg, functionDef.ret);
return map;
}, {}),
};
}
mapArgToTensorInfo(arg, nameMap) {
let name = arg.name;
if (nameMap != null) {
name = nameMap[name];
}
return { name, dtype: arg.type };
}
}
function decodeBase64(text) {
const global = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().global;
if (typeof global.atob !== "undefined") {
return global.atob(text);
} else if (typeof Buffer !== "undefined") {
return new Buffer(text, "base64").toString();
} else {
throw new Error(
"Unable to decode base64 in this environment. " +
"Missing built-in atob() or Buffer()"
);
}
}
function parseStringParam(s, keepCase) {
const value = Array.isArray(s) ? String.fromCharCode.apply(null, s) : decodeBase64(s);
return keepCase ? value : value.toLowerCase();
}
function getStringParam(attrs, name, def, keepCase = false) {
const param = attrs[name];
if (param != null) {
return parseStringParam(param.s, keepCase);
}
return def;
}
function getBoolParam(attrs, name, def) {
const param = attrs[name];
return param ? param.b : def;
}
function getNumberParam(attrs, name, def) {
const param = attrs[name] || {};
const value = param["i"] != null ? param["i"] : param["f"] != null ? param["f"] : def;
return typeof value === "number" ? value : parseInt(value, 10);
}
function parseDtypeParam(value) {
if (typeof value === "string") {
// tslint:disable-next-line:no-any
value = _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"][value];
}
switch (value) {
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_FLOAT:
return "float32";
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_INT32:
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_INT64:
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_INT8:
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_UINT8:
return "int32";
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_BOOL:
return "bool";
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_DOUBLE:
return "float32";
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_STRING:
return "string";
default:
// Unknown dtype error will happen at runtime (instead of parse time),
// since these nodes might not be used by the actual subgraph execution.
return null;
}
}
function getFuncParam(attrs, name, def) {
const param = attrs[name];
if (param && param.func) {
return param.func.name;
}
return def;
}
function getDtypeParam(attrs, name, def) {
const param = attrs[name];
if (param && param.type) {
return parseDtypeParam(param.type);
}
return def;
}
function getDtypeArrayParam(attrs, name, def) {
const param = attrs[name];
if (param && param.list && param.list.type) {
return param.list.type.map((v) => parseDtypeParam(v));
}
return def;
}
function parseTensorShapeParam(shape) {
if (shape.unknownRank) {
return undefined;
}
if (shape.dim != null) {
return shape.dim.map((dim) =>
typeof dim.size === "number" ? dim.size : parseInt(dim.size, 10)
);
}
return [];
}
function getTensorShapeParam(attrs, name, def) {
const param = attrs[name];
if (param && param.shape) {
return parseTensorShapeParam(param.shape);
}
return def;
}
function getNumericArrayParam(attrs, name, def) {
const param = attrs[name];
if (param) {
return ((param.list.f && param.list.f.length ? param.list.f : param.list.i) || []).map(
(v) => (typeof v === "number" ? v : parseInt(v, 10))
);
}
return def;
}
function getStringArrayParam(attrs, name, def, keepCase = false) {
const param = attrs[name];
if (param && param.list && param.list.s) {
return param.list.s.map((v) => {
return parseStringParam(v, keepCase);
});
}
return def;
}
function getTensorShapeArrayParam(attrs, name, def) {
const param = attrs[name];
if (param && param.list && param.list.shape) {
return param.list.shape.map((v) => {
return parseTensorShapeParam(v);
});
}
return def;
}
function getBoolArrayParam(attrs, name, def) {
const param = attrs[name];
if (param && param.list && param.list.b) {
return param.list.b;
}
return def;
}
//# sourceMappingURL=operation_mapper.js.map
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(39).Buffer));
/***/
},
/* 16 */
/***/ function (module, exports) {
module.exports = function () {
throw new Error("define cannot be used indirect");
};
/***/
},
/* 17 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return getKernel;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return getGradient;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return getKernelsForBackend;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function () {
return registerKernel;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function () {
return registerGradient;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function () {
return unregisterKernel;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function () {
return unregisterGradient;
});
/* harmony import */ var _global_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(33);
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const kernelRegistry = Object(_global_util__WEBPACK_IMPORTED_MODULE_0__[/* getGlobal */ "a"])(
"kernelRegistry",
() => new Map()
);
const gradRegistry = Object(_global_util__WEBPACK_IMPORTED_MODULE_0__[/* getGlobal */ "a"])(
"gradRegistry",
() => new Map()
);
/**
* Returns the kernel function (code) associated with the provided names.
*
* @param kernelName The official name of the kernel.
* @param backendName The official name of the backend.
*/
function getKernel(kernelName, backendName) {
const key = makeKey(kernelName, backendName);
return kernelRegistry.get(key);
}
/**
* Returns the registered gradient info associated with the provided kernel.
* @param kernelName The official TF kernel name.
*/
function getGradient(kernelName) {
return gradRegistry.get(kernelName);
}
function getKernelsForBackend(backendName) {
const it = kernelRegistry.entries();
const result = [];
while (true) {
const { done, value } = it.next();
if (done) {
break;
}
const [key, config] = value;
const [backend] = key.split("_");
if (backend === backendName) {
result.push(config);
}
}
return result;
}
/**
* Registers the function (forward pass) for the kernel in a global registry.
*
* @param config A config object with the following properties:
* - `kernelName` The official name of the kernel.
* - `backendName` The official name of the backend.
* - `kernelFunc` The function to run during the forward pass of the kernel.
* - `setupFunc` Optional. Gets called once, after the backend initializes.
* - `disposeFunc` Optional. Gets called once, right before the backend is
* disposed.
*/
function registerKernel(config) {
const { kernelName, backendName } = config;
const key = makeKey(kernelName, backendName);
if (kernelRegistry.has(key)) {
console.warn(
`The kernel '${kernelName}' for backend ` + `'${backendName}' is already registered`
);
}
kernelRegistry.set(key, config);
}
/**
* Registers a gradient function for a given kernel in the global registry,
* to be used during the back-propagation of that kernel.
*
* @param config An object with the following properties:
* - `kernelName` The name of the kernel that the gradient function is for.
* - `gradFunc` The function to run during back-propagation.
*/
function registerGradient(config) {
const { kernelName } = config;
if (gradRegistry.has(kernelName)) {
console.warn(`Overriding the gradient for '${kernelName}'`);
}
gradRegistry.set(kernelName, config);
}
/**
* Removes the kernel function from the registry.
*
* @param kernelName The official name of the kernel.
* @param backendName The official name of the backend.
*
*/
function unregisterKernel(kernelName, backendName) {
const key = makeKey(kernelName, backendName);
if (!kernelRegistry.has(key)) {
throw new Error(
`The kernel '${kernelName}' for backend ` + `'${backendName}' is not registered`
);
}
kernelRegistry.delete(key);
}
/** Removes the registered gradient from the global registry. */
function unregisterGradient(kernelName) {
if (!gradRegistry.has(kernelName)) {
throw new Error(`The gradient '${kernelName}' for backend is not registered`);
}
gradRegistry.delete(kernelName);
}
function makeKey(kernelName, backendName) {
return `${backendName}_${kernelName}`;
}
//# sourceMappingURL=kernel_registry.js.map
/***/
},
/* 18 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return complex;
});
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(3);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts two real numbers to a complex number.
*
* Given a tensor `real` representing the real part of a complex number, and a
* tensor `imag` representing the imaginary part of a complex number, this
* operation returns complex numbers elementwise of the form [r0, i0, r1, i1],
* where r represents the real part and i represents the imag part.
*
* The input tensors real and imag must have the same shape.
*
* ```js
* const real = tf.tensor1d([2.25, 3.25]);
* const imag = tf.tensor1d([4.75, 5.75]);
* const complex = tf.complex(real, imag);
*
* complex.print();
* ```
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function complex_(real, imag) {
const $real = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"]
)(real, "real", "complex");
const $imag = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"]
)(imag, "imag", "complex");
_util__WEBPACK_IMPORTED_MODULE_3__["assertShapesMatch"](
$real.shape,
$imag.shape,
`real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +
`must match in call to tf.complex().`
);
const forward = (backend) => {
return backend.complex($real, $imag);
};
const inputs = { real: $real, imag: $imag };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernelFunc(
forward,
inputs,
null /* gradient */,
_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Complex */ "k"]
);
}
const complex = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "a"])({ complex_ });
//# sourceMappingURL=complex.js.map
/***/
},
/* 19 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return deepMap;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function () {
return deepZip;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function () {
return zipToList;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return deepMapAndAwaitAll;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function () {
return isIterable;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return canTensorify;
});
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(0);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* Apply a mapping function to a nested structure in a recursive manner.
*
* The result of the mapping is an object with the same nested structure (i.e.,
* of arrays and dicts) as the input, except that some subtrees are replaced,
* according to the results of the mapping function.
*
* Mappings are memoized. Thus, if the nested structure contains the same
* object in multiple positions, the output will contain the same mapped object
* in those positions. Cycles are not supported, however.
*
* @param input: The object to which to apply the mapping function.
* @param mapFn: A function that expects a single node of the object tree, and
* returns a `DeepMapResult`. The `DeepMapResult` either provides a
* replacement value for that node (i.e., replacing the subtree), or indicates
* that the node should be processed recursively.
*/
function deepMap(input, mapFn) {
return deepMapInternal(input, mapFn);
}
/**
* @param seen: A Map of known object mappings (i.e., memoized results of
* `mapFn()`)
* @param containedIn: An set containing objects on the reference path currently
* being processed (used to detect cycles).
*/
function deepMapInternal(input, mapFn, seen = new Map(), containedIn = new Set()) {
if (input == null) {
return null;
}
if (containedIn.has(input)) {
throw new Error("Circular references are not supported.");
}
if (seen.has(input)) {
return seen.get(input);
}
const result = mapFn(input);
if (result.recurse && result.value !== null) {
throw new Error("A deep map function may not return both a value and recurse=true.");
}
if (!result.recurse) {
seen.set(input, result.value);
return result.value;
} else if (isIterable(input)) {
// tslint:disable-next-line:no-any
const mappedIterable = Array.isArray(input) ? [] : {};
containedIn.add(input);
for (const k in input) {
const child = input[k];
const childResult = deepMapInternal(child, mapFn, seen, containedIn);
mappedIterable[k] = childResult;
}
containedIn.delete(input);
return mappedIterable;
} else {
throw new Error(`Can't recurse into non-iterable type: ${input}`);
}
}
// TODO(soergel, kangyizhang) Reconsider naming of deepZip() to avoid confusion
// with zip()
/**
* Zip nested structures together in a recursive manner.
*
* This has the effect of transposing or pivoting data, e.g. converting it from
* a row-major representation to a column-major representation.
*
* For example, `deepZip([{a: 1, b: 2}, {a: 3, b: 4}])` returns
* `{a: [1, 3], b: [2, 4]}`.
*
* The inputs should all have the same nested structure (i.e., of arrays and
* dicts). The result is a single object with the same nested structure, where
* the leaves are arrays collecting the values of the inputs at that location
* (or, optionally, the result of a custom function applied to those arrays).
*
* @param inputs: An array of the objects to zip together.
* @param zipFn: (optional) A function that expects an array of elements at a
* single node of the object tree, and returns a `DeepMapResult`. The
* `DeepMapResult` either provides a result value for that node (i.e.,
* representing the subtree), or indicates that the node should be processed
* recursively. The default zipFn recurses as far as possible and places
* arrays at the leaves.
*/
function deepZip(inputs, zipFn = zipToList) {
return deepZipInternal(inputs, zipFn);
}
/**
* @param containedIn: An set containing objects on the reference path currently
* being processed (used to detect cycles).
*/
function deepZipInternal(inputs, zipFn, containedIn = new Set()) {
// The recursion follows the structure of input 0; it's assumed that all the
// other inputs have the same structure.
const input = inputs[0];
if (containedIn.has(input)) {
throw new Error("Circular references are not supported.");
}
const result = zipFn(inputs);
if (result.recurse && result.value !== null) {
throw new Error("A deep zip function may not return both a value and recurse=true.");
}
if (!result.recurse) {
return result.value;
} else if (isIterable(input)) {
// tslint:disable-next-line:no-any
const mappedIterable = Array.isArray(input) ? [] : {};
containedIn.add(input);
for (const k in input) {
const children = inputs.map((x) => x[k]);
const childResult = deepZipInternal(children, zipFn, containedIn);
mappedIterable[k] = childResult;
}
containedIn.delete(input);
return mappedIterable;
} else {
throw new Error(`Can't recurse into non-iterable type: ${input}`);
}
}
// tslint:disable-next-line:no-any
function zipToList(x) {
if (x === null) {
return null;
}
// TODO(soergel): validate array type?
if (isIterable(x[0])) {
return { value: null, recurse: true };
} else {
return { value: x, recurse: false };
}
}
/**
* Apply an async mapping function to a nested structure in a recursive manner.
*
* This first creates a nested structure of Promises, and then awaits all of
* those, resulting in a single Promise for a resolved nested structure.
*
* The result of the mapping is an object with the same nested structure (i.e.,
* of arrays and dicts) as the input, except that some subtrees are replaced,
* according to the results of the mapping function.
*
* Mappings are memoized. Thus, if the nested structure contains the same
* object in multiple positions, the output will contain the same mapped object
* in those positions. Cycles are not supported, however.
*
* @param input: The object to which to apply the mapping function.
* @param mapFn: A function that expects a single node of the object tree, and
* returns a `DeepMapAsyncResult`. The `DeepMapAsyncResult` either provides
* a `Promise` for a replacement value for that node (i.e., replacing the
* subtree), or indicates that the node should be processed recursively. Note
* that the decision whether or not to recurse must be made immediately; only
* the mapped value may be promised.
*/
async function deepMapAndAwaitAll(input, mapFn) {
const seen = new Map();
// First do a normal deepMap, collecting Promises in 'seen' as a side effect.
deepMapInternal(input, mapFn, seen);
// Replace the Promises in 'seen' in place.
// Note TypeScript provides no async map iteration, and regular map iteration
// is broken too, so sadly we have to do Array.from() to make it work.
// (There's no advantage to Promise.all(), and that would be tricky anyway.)
for (const key of Array.from(seen.keys())) {
const value = seen.get(key);
if (value instanceof Promise) {
const mappedValue = await value;
seen.set(key, mappedValue);
}
}
// Normal deepMap again, this time filling in the resolved values.
// It's unfortunate that we have to do two passes.
// TODO(soergel): test performance and think harder about a fast solution.
const result = deepMapInternal(input, mapFn, seen);
return result;
}
/**
* Determine whether the argument is iterable.
*
* @returns true if the argument is an array or any non-Tensor object.
*/
// tslint:disable-next-line:no-any
function isIterable(obj) {
return (
obj != null &&
!ArrayBuffer.isView(obj) &&
(Array.isArray(obj) ||
(typeof obj === "object" &&
!(obj instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"])))
);
}
/**
* Determine whether the argument can be converted to Tensor.
*
* Tensors, primitives, arrays, and TypedArrays all qualify; anything else does
* not.
*
* @returns true if the argument can be converted to Tensor.
*/
// tslint:disable-next-line:no-any
function canTensorify(obj) {
return (
obj == null ||
isPrimitive(obj) ||
Array.isArray(obj) ||
(typeof obj === "object" &&
obj instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]) ||
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].isTypedArray(obj)
);
}
/**
* Returns true if the given `value` is a primitive type. Otherwise returns
* false. This is equivalant to node util.isPrimitive
*/
function isPrimitive(value) {
return value === null || (typeof value !== "object" && typeof value !== "function");
}
//# sourceMappingURL=deep_map.js.map
/***/
},
/* 20 */
/***/ function (module, exports, __webpack_require__) {
// A library of seedable RNGs implemented in Javascript.
//
// Usage:
//
// var seedrandom = require('seedrandom');
// var random = seedrandom(1); // or any seed.
// var x = random(); // 0 <= x < 1. Every bit is random.
// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.
// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.
// Period: ~2^116
// Reported to pass all BigCrush tests.
var alea = __webpack_require__(68);
// xor128, a pure xor-shift generator by George Marsaglia.
// Period: 2^128-1.
// Reported to fail: MatrixRank and LinearComp.
var xor128 = __webpack_require__(69);
// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.
// Period: 2^192-2^32
// Reported to fail: CollisionOver, SimpPoker, and LinearComp.
var xorwow = __webpack_require__(70);
// xorshift7, by François Panneton and Pierre L'ecuyer, takes
// a different approach: it adds robustness by allowing more shifts
// than Marsaglia's original three. It is a 7-shift generator
// with 256 bits, that passes BigCrush with no systmatic failures.
// Period 2^256-1.
// No systematic BigCrush failures reported.
var xorshift7 = __webpack_require__(71);
// xor4096, by Richard Brent, is a 4096-bit xor-shift with a
// very long period that also adds a Weyl generator. It also passes
// BigCrush with no systematic failures. Its long period may
// be useful if you have many generators and need to avoid
// collisions.
// Period: 2^4128-2^32.
// No systematic BigCrush failures reported.
var xor4096 = __webpack_require__(72);
// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random
// number generator derived from ChaCha, a modern stream cipher.
// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
// Period: ~2^127
// No systematic BigCrush failures reported.
var tychei = __webpack_require__(73);
// The original ARC4-based prng included in this library.
// Period: ~2^1600
var sr = __webpack_require__(74);
sr.alea = alea;
sr.xor128 = xor128;
sr.xorwow = xorwow;
sr.xorshift7 = xorshift7;
sr.xor4096 = xor4096;
sr.tychei = tychei;
module.exports = sr;
/***/
},
/* 21 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return DataType;
});
/* unused harmony export SaverDef */
/**
* @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.
*
* =============================================================================
*/
/** DataType enum. */
var DataType;
(function (DataType) {
DataType[(DataType["DT_INVALID"] = 0)] = "DT_INVALID";
DataType[(DataType["DT_FLOAT"] = 1)] = "DT_FLOAT";
DataType[(DataType["DT_DOUBLE"] = 2)] = "DT_DOUBLE";
DataType[(DataType["DT_INT32"] = 3)] = "DT_INT32";
DataType[(DataType["DT_UINT8"] = 4)] = "DT_UINT8";
DataType[(DataType["DT_INT16"] = 5)] = "DT_INT16";
DataType[(DataType["DT_INT8"] = 6)] = "DT_INT8";
DataType[(DataType["DT_STRING"] = 7)] = "DT_STRING";
DataType[(DataType["DT_COMPLEX64"] = 8)] = "DT_COMPLEX64";
DataType[(DataType["DT_INT64"] = 9)] = "DT_INT64";
DataType[(DataType["DT_BOOL"] = 10)] = "DT_BOOL";
DataType[(DataType["DT_QINT8"] = 11)] = "DT_QINT8";
DataType[(DataType["DT_QUINT8"] = 12)] = "DT_QUINT8";
DataType[(DataType["DT_QINT32"] = 13)] = "DT_QINT32";
DataType[(DataType["DT_BFLOAT16"] = 14)] = "DT_BFLOAT16";
DataType[(DataType["DT_FLOAT_REF"] = 101)] = "DT_FLOAT_REF";
DataType[(DataType["DT_DOUBLE_REF"] = 102)] = "DT_DOUBLE_REF";
DataType[(DataType["DT_INT32_REF"] = 103)] = "DT_INT32_REF";
DataType[(DataType["DT_UINT8_REF"] = 104)] = "DT_UINT8_REF";
DataType[(DataType["DT_INT16_REF"] = 105)] = "DT_INT16_REF";
DataType[(DataType["DT_INT8_REF"] = 106)] = "DT_INT8_REF";
DataType[(DataType["DT_STRING_REF"] = 107)] = "DT_STRING_REF";
DataType[(DataType["DT_COMPLEX64_REF"] = 108)] = "DT_COMPLEX64_REF";
DataType[(DataType["DT_INT64_REF"] = 109)] = "DT_INT64_REF";
DataType[(DataType["DT_BOOL_REF"] = 110)] = "DT_BOOL_REF";
DataType[(DataType["DT_QINT8_REF"] = 111)] = "DT_QINT8_REF";
DataType[(DataType["DT_QUINT8_REF"] = 112)] = "DT_QUINT8_REF";
DataType[(DataType["DT_QINT32_REF"] = 113)] = "DT_QINT32_REF";
DataType[(DataType["DT_BFLOAT16_REF"] = 114)] = "DT_BFLOAT16_REF";
})(DataType || (DataType = {}));
var SaverDef;
(function (SaverDef) {
/** CheckpointFormatVersion enum. */
let CheckpointFormatVersion;
(function (CheckpointFormatVersion) {
CheckpointFormatVersion[(CheckpointFormatVersion["LEGACY"] = 0)] = "LEGACY";
CheckpointFormatVersion[(CheckpointFormatVersion["V1"] = 1)] = "V1";
CheckpointFormatVersion[(CheckpointFormatVersion["V2"] = 2)] = "V2";
})(
(CheckpointFormatVersion =
SaverDef.CheckpointFormatVersion || (SaverDef.CheckpointFormatVersion = {}))
);
})(SaverDef || (SaverDef = {}));
//# sourceMappingURL=compiled_api.js.map
/***/
},
/* 22 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return real;
});
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(3);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the real part of a complex (or real) tensor.
*
* Given a tensor input, this operation returns a tensor of type float that is
* the real part of each element in input considered as a complex number.
*
* If the input is real, it simply makes a clone.
*
* ```js
* const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);
* tf.real(x).print();
* ```
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function real_(input) {
const $input = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"]
)(input, "input", "real");
const forward = (backend) => {
return backend.real($input);
};
const inputs = { input: $input };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernelFunc(
forward,
inputs,
null /* gradient */,
_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Real */ "hb"]
);
}
const real = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "a"])({ real_ });
//# sourceMappingURL=real.js.map
/***/
},
/* 23 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return Rank;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return upcastType;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return sumOutType;
});
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var Rank;
(function (Rank) {
Rank["R0"] = "R0";
Rank["R1"] = "R1";
Rank["R2"] = "R2";
Rank["R3"] = "R3";
Rank["R4"] = "R4";
Rank["R5"] = "R5";
Rank["R6"] = "R6";
})(Rank || (Rank = {}));
// Looks for upcasting types. Used, for example, in operations with mixed dtype
// inputs.
var UpcastInt32AndMap;
(function (UpcastInt32AndMap) {
UpcastInt32AndMap["float32"] = "float32";
UpcastInt32AndMap["int32"] = "int32";
UpcastInt32AndMap["bool"] = "int32";
UpcastInt32AndMap["complex64"] = "complex64";
})(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
var UpcastBoolAndMap;
(function (UpcastBoolAndMap) {
UpcastBoolAndMap["float32"] = "float32";
UpcastBoolAndMap["int32"] = "int32";
UpcastBoolAndMap["bool"] = "bool";
UpcastBoolAndMap["complex64"] = "complex64";
})(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
var UpcastFloat32AndMap;
(function (UpcastFloat32AndMap) {
UpcastFloat32AndMap["float32"] = "float32";
UpcastFloat32AndMap["int32"] = "float32";
UpcastFloat32AndMap["bool"] = "float32";
UpcastFloat32AndMap["complex64"] = "complex64";
})(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
var UpcastComplex64AndMap;
(function (UpcastComplex64AndMap) {
UpcastComplex64AndMap["float32"] = "complex64";
UpcastComplex64AndMap["int32"] = "complex64";
UpcastComplex64AndMap["bool"] = "complex64";
UpcastComplex64AndMap["complex64"] = "complex64";
})(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
const upcastTypeMap = {
float32: UpcastFloat32AndMap,
int32: UpcastInt32AndMap,
bool: UpcastBoolAndMap,
complex64: UpcastComplex64AndMap,
};
function upcastType(typeA, typeB) {
if (typeA === "string" || typeB === "string") {
if (typeA === "string" && typeB === "string") {
return "string";
}
throw new Error(`Can not upcast ${typeA} with ${typeB}`);
}
return upcastTypeMap[typeA][typeB];
}
/** Returns the output type after summation. */
function sumOutType(type) {
return upcastType(type, "int32");
}
//# sourceMappingURL=types.js.map
/***/
},
/* 24 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function () {
return registerOp;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return getRegisteredOp;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return deregisterOp;
});
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const CUSTOM_OPS = {};
/**
* Register an Op for graph model executor. This allow you to register
* TensorFlow custom op or override existing op.
*
* Here is an example of registering a new MatMul Op.
* ```js
* const customMatmul = (node) =>
* tf.matMul(
* node.inputs[0], node.inputs[1],
* node.attrs['transpose_a'], node.attrs['transpose_b']);
*
* tf.registerOp('MatMul', customMatmul);
* ```
* The inputs and attrs of the node object is based on the TensorFlow op
* registry.
*
* @param name The Tensorflow Op name.
* @param opFunc An op function which is called with the current graph node
* during execution and needs to return a tensor or a list of tensors. The node
* has the following attributes:
* - attr: A map from attribute name to its value
* - inputs: A list of input tensors
*/
/** @doc {heading: 'Models', subheading: 'Op Registry'} */
function registerOp(name, opFunc) {
const opMapper = {
tfOpName: name,
category: "custom",
inputs: [],
attrs: [],
customExecutor: opFunc,
};
CUSTOM_OPS[name] = opMapper;
}
/**
* Retrieve the OpMapper object for the registered op.
*
* @param name The Tensorflow Op name.
*/
/** @doc {heading: 'Models', subheading: 'Op Registry'} */
function getRegisteredOp(name) {
return CUSTOM_OPS[name];
}
/**
* Deregister the Op for graph model executor.
*
* @param name The Tensorflow Op name.
*/
/** @doc {heading: 'Models', subheading: 'Op Registry'} */
function deregisterOp(name) {
delete CUSTOM_OPS[name];
}
//# sourceMappingURL=register.js.map
/***/
},
/* 25 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return imag;
});
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(3);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the imaginary part of a complex (or real) tensor.
*
* Given a tensor input, this operation returns a tensor of type float that is
* the imaginary part of each element in input considered as a complex number.
* If input is real, a tensor of all zeros is returned.
*
* ```js
* const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);
* tf.imag(x).print();
* ```
*/
/** @doc {heading: 'Tensors', subheading: 'Creation'} */
function imag_(input) {
const $input = Object(
_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"]
)(input, "input", "imag");
const forward = (backend) => {
return backend.imag($input);
};
const inputs = { input: $input };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernelFunc(
forward,
inputs,
null /* gradient */,
_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Imag */ "K"]
);
}
const imag = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "a"])({ imag_ });
//# sourceMappingURL=imag.js.map
/***/
},
/* 26 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return pool;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return maxPoolPositions;
});
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function pool(xValues, xShape, dtype, strides, convInfo, poolType) {
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const initialValue =
poolType === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
const output = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(
convInfo.outShape,
dtype
);
const outputVals = output.values;
const outputBatchStrides =
convInfo.outShape[1] * convInfo.outShape[2] * convInfo.outShape[3];
const outputRowStrides = convInfo.outShape[2] * convInfo.outShape[3];
const outputColStrides = convInfo.outShape[3];
for (let b = 0; b < convInfo.batchSize; ++b) {
const outputBatchOffset = b * outputBatchStrides;
const inputBatchOffset = b * strides[0];
for (let d = 0; d < convInfo.inChannels; ++d) {
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const xRCorner = yR * strideHeight - padTop;
const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(convInfo.inHeight, effectiveFilterHeight + xRCorner);
const outputRowOffset = outputBatchOffset + yR * outputRowStrides;
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const xCCorner = yC * strideWidth - padLeft;
const xCMin = Math.max(0, xCCorner);
const xCMax = Math.min(convInfo.inWidth, effectiveFilterWidth + xCCorner);
let minMaxValue = initialValue;
let avgValue = 0;
let count = 0;
for (let xR = xRMin; xR < xRMax; xR += dilationHeight) {
const xROffset = inputBatchOffset + xR * strides[1];
for (let xC = xCMin; xC < xCMax; xC += dilationWidth) {
const xCOffset = xROffset + xC * strides[2];
const pixel = xValues[xCOffset + d];
if (poolType === "max" && pixel > minMaxValue) {
minMaxValue = pixel;
} else if (poolType === "avg") {
avgValue += pixel;
count++;
}
}
if (isNaN(minMaxValue)) {
break;
}
}
const outputOffset = outputRowOffset + yC * outputColStrides + d;
outputVals[outputOffset] = poolType === "avg" ? avgValue / count : minMaxValue;
}
}
}
}
return output;
}
function maxPoolPositions(
xValues,
xShape,
dtype,
convInfo,
flattenPositions = false,
includeBatchInIndex = false
) {
const maxPositions = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(
convInfo.outShape,
"int32"
);
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const xBuf = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(
xShape,
dtype,
xValues
);
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d = 0; d < convInfo.inChannels; ++d) {
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const xRCorner = yR * strideHeight - padTop;
let xRMin = xRCorner;
while (xRMin < 0) {
xRMin += dilationHeight;
}
// const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(convInfo.inHeight, effectiveFilterHeight + xRCorner);
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const xCCorner = yC * strideWidth - padLeft;
let xCMin = xCCorner;
while (xCMin < 0) {
xCMin += dilationWidth;
}
const xCMax = Math.min(convInfo.inWidth, effectiveFilterWidth + xCCorner);
let maxValue = Number.NEGATIVE_INFINITY;
let maxPosition = -1;
for (let xR = xRMin; xR < xRMax; xR += dilationHeight) {
const wR = xR - xRCorner;
for (let xC = xCMin; xC < xCMax; xC += dilationWidth) {
const wC = xC - xCCorner;
const pixel = xBuf.get(b, xR, xC, d);
if (pixel > maxValue) {
maxValue = pixel;
if (flattenPositions) {
maxPosition = includeBatchInIndex
? ((b * convInfo.inHeight + xR) * convInfo.inWidth + xC) *
convInfo.inChannels +
d
: (xR * convInfo.inWidth + xC) * convInfo.inChannels + d;
} else {
maxPosition = wR * effectiveFilterWidth + wC;
}
}
}
}
maxPositions.set(maxPosition, b, yR, yC, d);
}
}
}
}
return maxPositions;
}
//# sourceMappingURL=pool_utils.js.map
/***/
},
/* 27 */
/***/ function (module, exports) {
var g;
// This works in non-strict mode
g = (function () {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/
},
/* 28 */
/***/ function (module, exports) {
module.exports = function (module) {
if (!module.webpackPolyfill) {
module.deprecate = function () {};
module.paths = [];
// module.parent = undefined by default
if (!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function () {
return module.l;
},
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function () {
return module.i;
},
});
module.webpackPolyfill = 1;
}
return module;
};
/***/
},
/* 29 */
/***/ function (module, exports) {
/* WEBPACK VAR INJECTION */ (function (__webpack_amd_options__) {
/* globals __webpack_amd_options__ */
module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */
}.call(this, {}));
/***/
},
/* 30 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return transposeImpl;
});
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function transposeImpl(xVals, xShape, dtype, perm, newShape) {
const xRank = xShape.length;
const xSize =
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(xShape);
const xStrides =
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].computeStrides(xShape);
const newStrides =
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].computeStrides(newShape);
const result = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[
"util"
].getTypedArrayFromDType(
dtype,
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(newShape)
);
for (let i = 0; i < xSize; ++i) {
const loc = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].indexToLoc(
i,
xRank,
xStrides
);
// Permute location.
const newLoc = new Array(loc.length);
for (let i = 0; i < newLoc.length; i++) {
newLoc[i] = loc[perm[i]];
}
const newIndex = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].locToIndex(
newLoc,
xRank,
newStrides
);
result[newIndex] = xVals[i];
}
return result;
}
//# sourceMappingURL=Transpose_impl.js.map
/***/
},
/* 31 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function () {
return /* reexport */ backend_cpu_MathBackendCPU;
});
__webpack_require__.d(__webpack_exports__, "c", function () {
return /* reexport */ version;
});
__webpack_require__.d(__webpack_exports__, "b", function () {
return /* reexport */ shared_namespaceObject;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/shared.js
var shared_namespaceObject = {};
__webpack_require__.r(shared_namespaceObject);
__webpack_require__.d(shared_namespaceObject, "maxImpl", function () {
return Max_impl["a" /* maxImpl */];
});
__webpack_require__.d(shared_namespaceObject, "transposeImpl", function () {
return Transpose_impl["a" /* transposeImpl */];
});
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Max_impl.js
var Max_impl = __webpack_require__(37);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Transpose_impl.js
var Transpose_impl = __webpack_require__(30);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/shared.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Shared kernel impls for use in other backends.
//# sourceMappingURL=shared.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js + 269 modules
var dist = __webpack_require__(0);
// EXTERNAL MODULE: ./node_modules/seedrandom/index.js
var seedrandom = __webpack_require__(20);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/cpu_util.js
var cpu_util = __webpack_require__(9);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/pool_utils.js
var pool_utils = __webpack_require__(26);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/backend_cpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const nonMaxSuppressionV3 = dist["kernel_impls"].nonMaxSuppressionV3;
const split = dist["kernel_impls"].split;
const tile = dist["kernel_impls"].tile;
const topkImpl = dist["kernel_impls"].topkImpl;
const whereImpl = dist["kernel_impls"].whereImpl;
function mapActivation(backend, x, activation, preluActivationWeights) {
if (activation === "linear") {
return backend.linear(x);
} else if (activation === "relu") {
return backend.relu(x);
} else if (activation === "elu") {
return backend.elu(x);
} else if (activation === "relu6") {
return backend.relu6(x);
} else if (activation === "prelu") {
return backend.prelu(x, preluActivationWeights);
}
throw new Error(`Activation ${activation} has not been implemented for the CPU backend.`);
}
class backend_cpu_MathBackendCPU extends dist["KernelBackend"] {
constructor() {
super();
this.blockSize = 48;
this.firstUse = true;
this.data = new dist["DataStorage"](this, Object(dist["engine"])());
}
write(values, shape, dtype) {
if (this.firstUse) {
this.firstUse = false;
if (Object(dist["env"])().get("IS_NODE")) {
dist["backend_util"].warn(
"\n============================\n" +
"Hi there 👋. Looks like you are running TensorFlow.js in " +
"Node.js. To speed things up dramatically, install our node " +
"backend, which binds to TensorFlow C++, by running " +
"npm i @tensorflow/tfjs-node, " +
"or npm i @tensorflow/tfjs-node-gpu if you have CUDA. " +
"Then call require('@tensorflow/tfjs-node'); (-gpu " +
"suffix for CUDA) at the start of your program. " +
"Visit https://github.com/tensorflow/tfjs-node for more details." +
"\n============================"
);
}
}
const dataId = {};
this.data.set(dataId, { values, dtype });
return dataId;
}
move(dataId, values, shape, dtype) {
this.data.set(dataId, { values, dtype });
}
numDataIds() {
return this.data.numDataIds();
}
async read(dataId) {
return this.readSync(dataId);
}
readSync(dataId) {
const { dtype, complexTensors } = this.data.get(dataId);
if (dtype === "complex64") {
const realValues = this.readSync(complexTensors.real.dataId);
const imagValues = this.readSync(complexTensors.imag.dataId);
return dist["backend_util"].mergeRealAndImagArrays(realValues, imagValues);
}
return this.data.get(dataId).values;
}
bufferSync(t) {
const data = this.readSync(t.dataId);
let decodedData = data;
if (t.dtype === "string") {
try {
// Decode the bytes into string.
decodedData = data.map((d) => dist["util"].decodeString(d));
} catch (_a) {
throw new Error("Failed to decode encoded string bytes into utf-8");
}
}
return dist["buffer"](t.shape, t.dtype, decodedData);
}
makeOutput(values, shape, dtype) {
const dataId = this.write(values, shape, dtype);
return Object(dist["engine"])().makeTensorFromDataId(dataId, shape, dtype, this);
}
disposeData(dataId) {
if (this.data.has(dataId)) {
const { complexTensors } = this.data.get(dataId);
if (complexTensors != null) {
complexTensors.real.dispose();
complexTensors.imag.dispose();
}
this.data.delete(dataId);
}
}
async time(f) {
const start = dist["util"].now();
f();
const kernelMs = dist["util"].now() - start;
return { kernelMs };
}
memory() {
return {
// Unreliable due to automatic gc. The numbers above are cumulative.
unreliable: true,
reasons: [
"The reported memory is an upper bound. Due to automatic garbage " +
"collection, the true allocated memory may be less.",
],
};
}
complex(real, imag) {
const result = this.makeOutput(null, real.shape, "complex64");
const resultData = this.data.get(result.dataId);
// The backend owns the reference to the underlying real and imaginary
// clones. These will explicitly get disposed when the complex tensor is
// disposed.
resultData.complexTensors = {
real: Object(dist["engine"])().keep(real.clone()),
imag: Object(dist["engine"])().keep(imag.clone()),
};
return result;
}
real(input) {
const resultData = this.data.get(input.dataId);
return resultData.complexTensors.real.clone();
}
imag(input) {
const resultData = this.data.get(input.dataId);
return resultData.complexTensors.imag.clone();
}
slice(x, begin, size) {
Object(cpu_util["a" /* assertNotComplex */])(x, "slice");
const isContinous = dist["slice_util"].isSliceContinous(x.shape, begin, size);
if (isContinous) {
const flatOffset = dist["slice_util"].computeFlatOffset(begin, x.strides);
const length = dist["util"].sizeFromShape(size);
const vals = this.readSync(x.dataId);
return dist["tensor"](vals.subarray(flatOffset, flatOffset + length), size, x.dtype);
}
const buffer = dist["buffer"](size, x.dtype);
const xBuf = this.bufferSync(x);
for (let i = 0; i < buffer.size; ++i) {
const loc = buffer.indexToLoc(i);
const xLoc = loc.map((idx, j) => idx + begin[j]);
buffer.values[i] = xBuf.get(...xLoc);
}
return buffer.toTensor();
}
stridedSlice(x, begin, end, strides) {
Object(cpu_util["a" /* assertNotComplex */])(x, "stridedSlice");
const outShape = dist["slice_util"].computeOutShape(begin, end, strides);
if (outShape.some((axis) => axis === 0)) {
return dist["tensor"]([], outShape);
}
const buffer = dist["buffer"](outShape, x.dtype);
const xBuf = this.bufferSync(x);
for (let i = 0; i < buffer.size; i++) {
const loc = buffer.indexToLoc(i);
const newLoc = new Array(loc.length);
for (let j = 0; j < newLoc.length; j++) {
newLoc[j] = loc[j] * strides[j] + begin[j];
}
buffer.set(xBuf.get(...newLoc), ...loc);
}
return buffer.toTensor();
}
diag(x) {
const xVals = this.readSync(x.dataId);
const buffer = dist["buffer"]([x.size, x.size], x.dtype);
const vals = buffer.values;
for (let i = 0; i < xVals.length; i++) {
vals[i * x.size + i] = xVals[i];
}
return buffer.toTensor();
}
unstack(x, axis) {
const num = x.shape[axis];
const outShape = new Array(x.rank - 1);
let outIndex = 0;
for (let i = 0; i < x.rank; i++) {
if (i !== axis) {
outShape[outIndex++] = x.shape[i];
}
}
const begin = new Array(x.rank).fill(0);
const size = x.shape.slice();
size[axis] = 1;
const res = new Array(num);
for (let i = 0; i < res.length; i++) {
begin[axis] = i;
res[i] = this.slice(x, begin, size).reshape(outShape);
}
return res;
}
reverse(x, axis) {
Object(cpu_util["a" /* assertNotComplex */])(x, "reverse");
const buffer = dist["buffer"](x.shape, x.dtype);
const xBuf = this.bufferSync(x);
for (let i = 0; i < buffer.size; i++) {
const outLoc = buffer.indexToLoc(i);
const inLoc = outLoc.slice();
axis.forEach((ax) => (inLoc[ax] = x.shape[ax] - 1 - inLoc[ax]));
buffer.set(xBuf.get(...inLoc), ...outLoc);
}
return buffer.toTensor();
}
concat(tensors, axis) {
if (tensors[0].dtype === "complex64") {
const reals = tensors.map((t) => dist["real"](t));
const imags = tensors.map((t) => dist["imag"](t));
return dist["complex"](this.concat(reals, axis), this.concat(imags, axis));
}
const tensors2D = tensors.map((t) => {
const innerSize = dist["util"].sizeFromShape(t.shape.slice(axis));
return t.as2D(-1, innerSize);
});
const outShape = dist["backend_util"].computeOutShape(
tensors2D.map((t) => t.shape),
1
/* axis
*/
);
const values = dist["buffer"](outShape, tensors[0].dtype).values;
if (tensors2D[0].shape[0] === 1) {
// Use built-in TypedArray.set() method for speed.
let offset = 0;
tensors2D.forEach((t) => {
values.set(this.readSync(t.dataId), offset);
offset += t.size;
});
} else {
let colOffset = 0;
tensors2D.forEach((t) => {
const tVals = this.readSync(t.dataId);
let tIdx = 0;
for (let row = 0; row < t.shape[0]; ++row) {
const resIdx = row * outShape[1] + colOffset;
for (let col = 0; col < t.shape[1]; ++col) {
values[resIdx + col] = tVals[tIdx++];
}
}
colOffset += t.shape[1];
});
}
const finalOutShape = dist["backend_util"].computeOutShape(
tensors.map((t) => t.shape),
axis
);
return dist["tensor"](values, finalOutShape, tensors[0].dtype);
}
neg(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "neg");
return this.multiply(dist["scalar"](-1), x);
}
add(a, b) {
if (a.dtype === "complex64" || b.dtype === "complex64") {
return this.broadcastedBinaryComplexOp(
a.cast("complex64"),
b.cast("complex64"),
(aReal, aImag, bReal, bImag) => {
return { real: aReal + bReal, imag: aImag + bImag };
}
);
}
return this.broadcastedBinaryOp(
a,
b,
Object(dist["upcastType"])(a.dtype, b.dtype),
(aValue, bValue) => aValue + bValue
);
}
addN(tensors) {
Object(cpu_util["a" /* assertNotComplex */])(tensors, "addN");
const vals = tensors.map((t) => this.readSync(t.dataId));
const result = dist["buffer"](tensors[0].shape, tensors[0].dtype);
const resultVals = result.values;
for (let i = 0; i < tensors.length; i++) {
const currVals = vals[i];
for (let j = 0; j < resultVals.length; j++) {
resultVals[j] += currVals[j];
}
}
return result.toTensor();
}
softmax(logits, dim) {
const axes = dist["util"].parseAxisParam([dim], logits.shape);
// TODO(annxingyuan): Call maxImpl rather than op as part of softmax kernel
// modularization.
const maxLogit = Object(dist["max"])(logits, axes);
const expandedShape = dist["backend_util"].expandShapeToKeepDim(maxLogit.shape, axes);
const a = this.subtract(logits, maxLogit.reshape(expandedShape));
const b = this.exp(a);
const sumExp = this.sum(b, axes).reshape(expandedShape);
// TODO(annxingyuan): Call divImpl rather than op as part of softmax
// kernel modularization.
return dist["div"](b, sumExp);
}
subtract(a, b) {
if (a.dtype === "complex64" || b.dtype === "complex64") {
return this.broadcastedBinaryComplexOp(
a.cast("complex64"),
b.cast("complex64"),
(aReal, aImag, bReal, bImag) => {
return { real: aReal - bReal, imag: aImag - bImag };
}
);
}
return this.broadcastedBinaryOp(
a,
b,
Object(dist["upcastType"])(a.dtype, b.dtype),
(aValue, bValue) => aValue - bValue
);
}
pow(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "pow");
return this.broadcastedBinaryOp(a, b, a.dtype, (aValue, bValue) =>
Math.pow(aValue, bValue)
);
}
batchMatMul(a, b, transposeA, transposeB) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "matMul");
const sharedDim = transposeA ? a.shape[1] : a.shape[2];
const leftDim = transposeA ? a.shape[2] : a.shape[1];
const rightDim = transposeB ? b.shape[1] : b.shape[2];
const batchDim = a.shape[0];
const aValues = this.readSync(a.dataId);
const bValues = this.readSync(b.dataId);
const [aBatch, aOuterStep, aInnerStep] = transposeA
? [a.strides[0], 1, a.strides[1]]
: [a.strides[0], a.strides[1], 1];
const [bInnerStep, bOuterStep, bBatch] = transposeB
? [1, b.strides[1], b.strides[0]]
: [b.strides[1], 1, b.strides[0]];
const size = leftDim * rightDim;
const result = dist["buffer"]([batchDim, leftDim, rightDim], a.dtype);
const resVals = result.values;
const blockSize = this.blockSize;
for (let b = 0; b < batchDim; b++) {
for (let i0 = 0; i0 < leftDim; i0 += blockSize) {
for (let j0 = 0; j0 < rightDim; j0 += blockSize) {
for (let k0 = 0; k0 < sharedDim; k0 += blockSize) {
// for when blockSize doesn't evenly divide the input
const iBlock = Math.min(i0 + blockSize, leftDim);
const jBlock = Math.min(j0 + blockSize, rightDim);
const kBlock = Math.min(k0 + blockSize, sharedDim);
for (let i = i0; i < iBlock; i++) {
for (let j = j0; j < jBlock; j++) {
let sum = 0.0;
for (let k = k0; k < kBlock; k++) {
sum +=
aValues[b * aBatch + i * aOuterStep + k * aInnerStep] *
bValues[k * bInnerStep + j * bOuterStep + b * bBatch];
}
resVals[b * size + (i * rightDim + j)] += sum;
}
}
}
}
}
}
return result.toTensor();
}
fusedBatchMatMul({
a,
b,
transposeA,
transposeB,
bias,
activation,
preluActivationWeights,
}) {
let result = this.batchMatMul(a, b, transposeA, transposeB);
if (bias) {
result = this.add(result, bias);
}
if (activation) {
result = mapActivation(this, result, activation, preluActivationWeights);
}
return result;
}
multiply(a, b) {
if (a.dtype === "complex64" || b.dtype === "complex64") {
return this.broadcastedBinaryComplexOp(
a.cast("complex64"),
b.cast("complex64"),
(aReal, aImag, bReal, bImag) => {
return {
real: aReal * bReal - aImag * bImag,
imag: aReal * bImag + aImag * bReal,
};
}
);
}
return this.broadcastedBinaryOp(
a,
b,
Object(dist["upcastType"])(a.dtype, b.dtype),
(aValue, bValue) => aValue * bValue
);
}
floorDiv(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "floorDiv");
const op = (a, b) => Math.floor(a / b);
const outputDtype = "int32";
return this.broadcastedBinaryOp(a, b, outputDtype, op);
}
sum(x, axes) {
Object(cpu_util["a" /* assertNotComplex */])(x, "sum");
dist["backend_util"].assertAxesAreInnerMostDims("sum", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const resultDtype = Object(dist["upcastType"])(x.dtype, "int32");
const result = dist["zeros"](outShape, resultDtype);
const reduceSize = dist["util"].sizeFromShape(reduceShape);
const vals = this.readSync(result.dataId);
const aVals = this.readSync(x.dataId);
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let sum = 0;
for (let j = 0; j < reduceSize; ++j) {
sum += aVals[offset + j];
}
vals[i] = sum;
}
return result;
}
prod(x, axes) {
Object(cpu_util["a" /* assertNotComplex */])(x, "sum");
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const resultDtype = Object(dist["upcastType"])(x.dtype, "int32");
const result = dist["zeros"](outShape, resultDtype);
const reduceSize = dist["util"].sizeFromShape(reduceShape);
const vals = this.readSync(result.dataId);
const aVals = this.readSync(x.dataId);
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let prod = 1;
for (let j = 0; j < reduceSize; ++j) {
prod *= aVals[offset + j];
}
vals[i] = prod;
}
return result;
}
unsortedSegmentSum(x, segmentIds, numSegments) {
Object(cpu_util["a" /* assertNotComplex */])(x, "unsortedSegmentSum");
const res = [];
// Reshape the segment id's so that they can be broadcast with
// x. The new shape should be [segmentIds.shape, 1, ..., 1]
const numIters = x.rank - segmentIds.rank;
for (let i = 0; i < numIters; ++i) {
segmentIds = segmentIds.expandDims(i + 1);
}
for (let i = 0; i < numSegments; ++i) {
const segmentId = dist["scalar"](i, "int32");
const mask = dist["equal"](segmentId, segmentIds).asType("float32");
const sum = mask.mul(x).sum(0);
res.push(sum);
}
return dist["stack"](res);
}
argMin(x, axis) {
Object(cpu_util["a" /* assertNotComplex */])(x, "argMin");
const axes = [axis];
dist["backend_util"].assertAxesAreInnerMostDims("argMin", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const result = dist["zeros"](outShape, "int32");
const reduceSize = dist["util"].sizeFromShape(reduceShape);
const vals = this.readSync(result.dataId);
const aVals = this.readSync(x.dataId);
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let min = aVals[offset];
let minIndex = 0;
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (value < min) {
min = value;
minIndex = j;
}
}
vals[i] = minIndex;
}
return result;
}
argMax(x, axis) {
Object(cpu_util["a" /* assertNotComplex */])(x, "argMax");
const axes = [axis];
dist["backend_util"].assertAxesAreInnerMostDims("argMax", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const result = dist["zeros"](outShape, "int32");
const reduceSize = dist["util"].sizeFromShape(reduceShape);
const vals = this.readSync(result.dataId);
const aVals = this.readSync(x.dataId);
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let max = aVals[offset];
let maxIndex = 0;
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (value > max) {
max = value;
maxIndex = j;
}
}
vals[i] = maxIndex;
}
return result;
}
cumsum(x, axis, exclusive, reverse) {
Object(cpu_util["a" /* assertNotComplex */])(x, "cumsum");
if (axis !== x.rank - 1) {
throw new Error(
`backend.cumsum in CPU expects an inner-most axis=${x.rank - 1} ` +
`but got axis=${axis}`
);
}
const resultDtype = Object(dist["upcastType"])(x.dtype, "int32");
const result = dist["zeros"](x.shape, resultDtype);
const vals = this.readSync(result.dataId);
const aVals = this.readSync(x.dataId);
const finalDim = x.shape[x.rank - 1];
const indexAdjuster = reverse ? (i, j) => i + finalDim - j - 1 : (i, j) => i + j;
for (let i = 0; i < aVals.length; i += finalDim) {
for (let j = 0; j < finalDim; j++) {
const idx = indexAdjuster(i, j);
if (j === 0) {
vals[idx] = exclusive ? 0 : aVals[idx];
} else {
const prevIdx = indexAdjuster(i, j - 1);
vals[idx] = exclusive ? aVals[prevIdx] + vals[prevIdx] : aVals[idx] + vals[prevIdx];
}
}
}
return result;
}
equal(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "equal");
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
return aVal === bVal ? 1 : 0;
});
}
notEqual(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "notEqual");
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
return aVal !== bVal ? 1 : 0;
});
}
less(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "less");
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
return aVal < bVal ? 1 : 0;
});
}
lessEqual(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "lessEqual");
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
return aVal <= bVal ? 1 : 0;
});
}
greater(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "greater");
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
return aVal > bVal ? 1 : 0;
});
}
greaterEqual(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "greaterEqual");
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
return aVal >= bVal ? 1 : 0;
});
}
logicalNot(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "logicalNot");
const values = this.readSync(x.dataId);
const newValues = new Uint8Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = values[i] ? 0 : 1;
}
return this.makeOutput(newValues, x.shape, "bool");
}
logicalAnd(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "logicalAnd");
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
return aVal && bVal;
});
}
logicalOr(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "logicalOr");
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
return aVal || bVal;
});
}
select(condition, a, b) {
Object(cpu_util["a" /* assertNotComplex */])([condition, a, b], "select");
const values = this.readSync(condition.dataId);
const aValues = this.readSync(a.dataId);
const bValues = this.readSync(b.dataId);
const result = dist["zeros"](a.shape, Object(dist["upcastType"])(a.dtype, b.dtype));
const newValues = this.readSync(result.dataId);
let index = 0;
const offset =
condition.rank === 0 || condition.rank > 1 || a.rank === 1
? 1
: dist["util"].sizeFromShape(a.shape.slice(1));
for (let i = 0; i < values.length; i++) {
for (let j = 0; j < offset; j++) {
if (values[i] === 1) {
newValues[index++] = aValues[i];
} else {
newValues[index++] = bValues[i];
}
}
}
return result;
}
where(condition) {
Object(cpu_util["a" /* assertNotComplex */])([condition], "where");
const condVals = this.readSync(condition.dataId);
return whereImpl(condition.shape, condVals);
}
topk(x, k, sorted) {
Object(cpu_util["a" /* assertNotComplex */])(x, "topk");
const xVals = this.readSync(x.dataId);
return topkImpl(xVals, x.shape, x.dtype, k, sorted);
}
min(x, axes) {
Object(cpu_util["a" /* assertNotComplex */])(x, "min");
dist["backend_util"].assertAxesAreInnerMostDims("min", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const result = dist["zeros"](outShape, x.dtype);
const reduceSize = dist["util"].sizeFromShape(reduceShape);
const vals = this.readSync(result.dataId);
const aVals = this.readSync(x.dataId);
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let min = aVals[offset];
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (value < min) {
min = value;
}
}
vals[i] = min;
}
return result;
}
minimum(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "minimum");
return this.broadcastedBinaryOp(a, b, a.dtype, (aVal, bVal) => Math.min(aVal, bVal));
}
mod(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "mod");
return this.broadcastedBinaryOp(a, b, a.dtype, (aVal, bVal) => {
const rem = aVal % bVal;
if ((aVal < 0 && bVal < 0) || (aVal >= 0 && bVal >= 0)) {
return rem;
} else {
return (rem + bVal) % bVal;
}
});
}
maximum(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "maximum");
return this.broadcastedBinaryOp(a, b, a.dtype, (aVal, bVal) => Math.max(aVal, bVal));
}
all(x, axes) {
Object(cpu_util["a" /* assertNotComplex */])(x, "all");
dist["backend_util"].assertAxesAreInnerMostDims("all", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const result = dist["zeros"](outShape, x.dtype);
const reduceSize = dist["util"].sizeFromShape(reduceShape);
const vals = this.readSync(result.dataId);
const aVals = this.readSync(x.dataId);
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let all = aVals[offset];
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
all = all && value;
}
vals[i] = all;
}
return result;
}
any(x, axes) {
Object(cpu_util["a" /* assertNotComplex */])(x, "any");
dist["backend_util"].assertAxesAreInnerMostDims("any", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const result = dist["zeros"](outShape, x.dtype);
const reduceSize = dist["util"].sizeFromShape(reduceShape);
const vals = this.readSync(result.dataId);
const aVals = this.readSync(x.dataId);
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let anyVal = aVals[offset];
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
anyVal = anyVal || value;
}
vals[i] = anyVal;
}
return result;
}
squaredDifference(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "squaredDifference");
return this.broadcastedBinaryOp(a, b, a.dtype, (aVal, bVal) => {
const diff = aVal - bVal;
return diff * diff;
});
}
ceil(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "ceil");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = Math.ceil(values[i]);
}
return this.makeOutput(newValues, x.shape, "float32");
}
floor(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "floor");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = Math.floor(values[i]);
}
return this.makeOutput(newValues, x.shape, "float32");
}
sign(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "x");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
if (values[i] < 0) {
newValues[i] = -1;
} else if (values[i] > 0) {
newValues[i] = 1;
} else {
newValues[i] = 0;
}
}
return this.makeOutput(newValues, x.shape, "float32");
}
isNaN(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "x");
const values = this.readSync(x.dataId);
const newValues = new Uint8Array(values.length);
for (let i = 0; i < values.length; ++i) {
if (Number.isNaN(values[i])) {
newValues[i] = 1;
}
}
return this.makeOutput(newValues, x.shape, "bool");
}
isInf(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "x");
const values = this.readSync(x.dataId);
const newValues = new Uint8Array(values.length);
for (let i = 0; i < values.length; ++i) {
if (Math.abs(values[i]) === Infinity) {
newValues[i] = 1;
}
}
return this.makeOutput(newValues, x.shape, "bool");
}
isFinite(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "x");
const values = this.readSync(x.dataId);
const newValues = new Uint8Array(values.length);
for (let i = 0; i < values.length; ++i) {
if (Number.isFinite(values[i])) {
newValues[i] = 1;
}
}
return this.makeOutput(newValues, x.shape, "bool");
}
round(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "round");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
// The algorithm is based on banker's rounding.
const base = Math.floor(values[i]);
if (values[i] - base < 0.5) {
newValues[i] = Math.floor(values[i]);
} else if (values[i] - base > 0.5) {
newValues[i] = Math.ceil(values[i]);
} else {
if (base % 2.0 === 0.0) {
newValues[i] = base;
} else {
newValues[i] = base + 1.0;
}
}
}
return this.makeOutput(newValues, x.shape, "float32");
}
exp(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "exp");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = Math.exp(values[i]);
}
return this.makeOutput(newValues, x.shape, "float32");
}
expm1(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "expm1");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = Math.expm1(values[i]);
}
return this.makeOutput(newValues, x.shape, "float32");
}
log(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "log");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = Math.log(value);
}
return this.makeOutput(newValues, x.shape, "float32");
}
log1p(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "log1p");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = Math.log1p(value);
}
return this.makeOutput(newValues, x.shape, "float32");
}
sqrt(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "sqrt");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = Math.sqrt(value);
}
return this.makeOutput(newValues, x.shape, "float32");
}
rsqrt(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "rsqrt");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = 1 / Math.sqrt(value);
}
return this.makeOutput(newValues, x.shape, "float32");
}
reciprocal(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "reciprocal");
const values = this.readSync(x.dataId);
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = 1 / values[i];
}
return this.makeOutput(newValues, x.shape, "float32");
}
linear(x) {
return x;
}
relu(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "relu");
const res = dist["zeros"](x.shape, x.dtype);
const resVals = this.readSync(res.dataId);
const inVals = this.readSync(x.dataId);
for (let i = 0; i < inVals.length; ++i) {
resVals[i] = Math.max(0, inVals[i]);
}
return res;
}
relu6(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "relu");
const res = dist["zeros"](x.shape, x.dtype);
const resVals = this.readSync(res.dataId);
const inVals = this.readSync(x.dataId);
for (let i = 0; i < inVals.length; ++i) {
resVals[i] = Math.min(Math.max(0, inVals[i]), 6);
}
return res;
}
prelu(x, a) {
Object(cpu_util["a" /* assertNotComplex */])([x, a], "prelu");
return this.broadcastedBinaryOp(x, a, x.dtype, (xValue, aValue) =>
xValue < 0 ? aValue * xValue : xValue
);
}
elu(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "elu");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
const v = values[i];
if (v >= 0) {
resultValues[i] = v;
} else {
resultValues[i] = Math.exp(v) - 1;
}
}
return this.makeOutput(resultValues, x.shape, "float32");
}
eluDer(dy, y) {
Object(cpu_util["a" /* assertNotComplex */])([dy, y], "eluDer");
const resultValues = new Float32Array(y.size);
const values = this.readSync(y.dataId);
const dyValues = this.readSync(dy.dataId);
for (let i = 0; i < values.length; ++i) {
const v = values[i];
if (v >= 1) {
resultValues[i] = dyValues[i];
} else {
resultValues[i] = dyValues[i] * (v + 1);
}
}
return this.makeOutput(resultValues, y.shape, "float32");
}
selu(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "selu");
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
const scaleAlpha = dist["backend_util"].SELU_SCALEALPHA;
const scale = dist["backend_util"].SELU_SCALE;
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
const v = values[i];
if (v >= 0) {
resultValues[i] = scale * v;
} else {
resultValues[i] = scaleAlpha * (Math.exp(v) - 1);
}
}
return this.makeOutput(resultValues, x.shape, "float32");
}
clip(x, min, max) {
Object(cpu_util["a" /* assertNotComplex */])(x, "clip");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
const v = values[i];
resultValues[i] = v > max ? max : v < min ? min : v;
}
return this.makeOutput(resultValues, x.shape, "float32");
}
abs(x) {
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.abs(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
complexAbs(x) {
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < x.size; ++i) {
const real = values[i * 2];
const imag = values[i * 2 + 1];
resultValues[i] = Math.hypot(real, imag);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
int(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "int");
const resultValues = new Int32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = values[i];
}
return this.makeOutput(resultValues, x.shape, "int32");
}
sigmoid(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "sigmoid");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = 1 / (1 + Math.exp(-values[i]));
}
return this.makeOutput(resultValues, x.shape, "float32");
}
softplus(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "softplus");
// mirrors the implementation of tf.nn.softplus: https://goo.gl/vkcvwX
// epsilon is the difference between 1.0 and the next representable float.
// For a single precision 32 bit float this should be 2^-23, see:
// https://math.byu.edu/~schow/work/IEEEFloatingPoint.htm
const epsilon = 1.1920928955078125e-7;
const threshold = Math.log(epsilon) + 2.0;
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
// Value above which exp(x) may overflow, but softplus(x) == x
// is within machine epsilon.
const tooLarge = values[i] > -threshold;
// Value below which exp(x) may underflow, but softplus(x) == exp(x)
// is within machine epsilon.
const tooSmall = values[i] < threshold;
const expX = Math.exp(values[i]);
let result;
if (tooSmall) {
result = expX;
} else if (tooLarge) {
result = values[i];
} else {
result = Math.log(1.0 + expX);
}
resultValues[i] = result;
}
return this.makeOutput(resultValues, x.shape, "float32");
}
sin(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "sin");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.sin(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
cos(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "cos");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.cos(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
tan(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "tan");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.tan(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
asin(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "asin");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.asin(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
acos(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "acos");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.acos(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
atan(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "atan");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.atan(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
atan2(a, b) {
Object(cpu_util["a" /* assertNotComplex */])([a, b], "atan2");
return this.broadcastedBinaryOp(a, b, a.dtype, (aValue, bValue) =>
Math.atan2(aValue, bValue)
);
}
sinh(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "sinh");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.sinh(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
cosh(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "cosh");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.cosh(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
tanh(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "tanh");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = dist["util"].tanh(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
asinh(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "asinh");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.asinh(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
acosh(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "acosh");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.acosh(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
atanh(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "atanh");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.atanh(values[i]);
}
return this.makeOutput(resultValues, x.shape, "float32");
}
erf(x) {
Object(cpu_util["a" /* assertNotComplex */])(x, "erf");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
const p = dist["backend_util"].ERF_P;
const a1 = dist["backend_util"].ERF_A1;
const a2 = dist["backend_util"].ERF_A2;
const a3 = dist["backend_util"].ERF_A3;
const a4 = dist["backend_util"].ERF_A4;
const a5 = dist["backend_util"].ERF_A5;
for (let i = 0; i < values.length; ++i) {
const sign = Math.sign(values[i]);
const v = Math.abs(values[i]);
const t = 1.0 / (1.0 + p * v);
resultValues[i] =
sign * (1.0 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-v * v));
}
return this.makeOutput(resultValues, x.shape, "float32");
}
step(x, alpha = 0) {
Object(cpu_util["a" /* assertNotComplex */])(x, "step");
const resultValues = new Float32Array(x.size);
const values = this.readSync(x.dataId);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
if (isNaN(value)) {
resultValues[i] = NaN;
} else {
resultValues[i] = value > 0 ? 1 : alpha;
}
}
return this.makeOutput(resultValues, x.shape, "float32");
}
fusedConv2d({ input, filter, convInfo, bias, activation, preluActivationWeights }) {
let result = this.conv2d(input, filter, convInfo);
if (bias) {
result = this.add(result, bias);
}
if (activation) {
result = mapActivation(this, result, activation, preluActivationWeights);
}
return result;
}
conv2d(x, filter, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([x, filter], "conv2d");
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const padLeft = convInfo.padInfo.left;
const padTop = convInfo.padInfo.top;
const isChannelsLast = convInfo.dataFormat === "channelsLast";
const y = dist["buffer"](convInfo.outShape, x.dtype);
const xBatchStride = x.strides[0];
const xRowStride = isChannelsLast ? x.strides[1] : x.strides[2];
const xColStride = isChannelsLast ? x.strides[2] : 1;
const xChannelStride = isChannelsLast ? 1 : x.strides[1];
const yBatchStride = y.strides[0];
const yRowStride = isChannelsLast ? y.strides[1] : y.strides[2];
const yColStride = isChannelsLast ? y.strides[2] : 1;
const yChannelStride = isChannelsLast ? 1 : y.strides[1];
const xVals = this.readSync(x.dataId);
const wVals = this.readSync(filter.dataId);
const yVals = y.values;
for (let b = 0; b < convInfo.batchSize; ++b) {
const xOffset1 = b * xBatchStride;
const yOffset1 = b * yBatchStride;
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const yOffset2 = yOffset1 + yR * yRowStride;
const xRCorner = yR * convInfo.strideHeight - padTop;
for (let wR = 0; wR < filterHeight; wR++) {
const xR = xRCorner + wR * dilationHeight;
if (xR < 0 || xR >= convInfo.inHeight) {
continue;
}
const wOffset1 = wR * filter.strides[0];
const xOffset2 = xOffset1 + xR * xRowStride;
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const yOffset3 = yOffset2 + yC * yColStride;
const xCCorner = yC * convInfo.strideWidth - padLeft;
for (let wC = 0; wC < filterWidth; wC++) {
const xC = xCCorner + wC * dilationWidth;
if (xC < 0 || xC >= convInfo.inWidth) {
continue;
}
const wOffset2 = wOffset1 + wC * filter.strides[1];
const xOffset3 = xOffset2 + xC * xColStride;
let wOffset3 = wOffset2;
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
const xVal = xVals[xOffset3 + d1 * xChannelStride];
for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {
yVals[yOffset3 + d2 * yChannelStride] += xVal * wVals[wOffset3 + d2];
}
wOffset3 += convInfo.outChannels;
}
}
}
}
}
}
return y.toTensor();
}
conv3d(x, filter, convInfo) {
const filterDepth = convInfo.filterDepth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const padFront = convInfo.padInfo.front;
const padLeft = convInfo.padInfo.left;
const padTop = convInfo.padInfo.top;
const y = dist["buffer"](convInfo.outShape, x.dtype);
const xVals = this.readSync(x.dataId);
const wVals = this.readSync(filter.dataId);
const yVals = y.values;
for (let b = 0; b < convInfo.batchSize; ++b) {
const xOffset1 = b * x.strides[0];
const yOffset1 = b * y.strides[0];
for (let yF = 0; yF < convInfo.outDepth; ++yF) {
const yOffset2 = yOffset1 + yF * y.strides[1];
const xFCorner = yF * convInfo.strideDepth - padFront;
for (let wF = 0; wF < filterDepth; wF++) {
const xF = xFCorner + wF * dilationDepth;
if (xF < 0 || xF >= convInfo.inDepth) {
continue;
}
const wOffset1 = wF * filter.strides[0];
const xOffset2 = xOffset1 + xF * x.strides[1];
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const yOffset3 = yOffset2 + yR * y.strides[2];
const xRCorner = yR * convInfo.strideHeight - padTop;
for (let wR = 0; wR < filterHeight; wR++) {
const xR = xRCorner + wR * dilationHeight;
if (xR < 0 || xR >= convInfo.inHeight) {
continue;
}
const wOffset2 = wOffset1 + wR * filter.strides[1];
const xOffset3 = xOffset2 + xR * x.strides[2];
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const yOffset4 = yOffset3 + yC * convInfo.outChannels;
const xCCorner = yC * convInfo.strideWidth - padLeft;
for (let wC = 0; wC < filterWidth; wC++) {
const xC = xCCorner + wC * dilationWidth;
if (xC < 0 || xC >= convInfo.inWidth) {
continue;
}
const wOffset3 = wOffset2 + wC * filter.strides[2];
const xOffset4 = xOffset3 + xC * convInfo.inChannels;
let wOffset4 = wOffset3;
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
const xVal = xVals[xOffset4 + d1];
for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {
yVals[yOffset4 + d2] += xVal * wVals[wOffset4 + d2];
}
wOffset4 += convInfo.outChannels;
}
}
}
}
}
}
}
}
return y.toTensor();
}
conv2dDerInput(dy, filter, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([dy, filter], "conv2dDerInput");
const dx = dist["buffer"](convInfo.inShape, "float32");
const dxValues = dx.values;
const dyValues = this.readSync(dy.dataId);
const fltValues = this.readSync(filter.dataId);
const [fltS0, fltS1, fltS2] = filter.strides;
const {
batchSize,
filterHeight,
filterWidth,
inChannels,
inHeight,
inWidth,
outChannels,
outHeight,
outWidth,
strideHeight,
strideWidth,
dataFormat,
} = convInfo;
const topPad = filterHeight - 1 - convInfo.padInfo.top;
const leftPad = filterWidth - 1 - convInfo.padInfo.left;
const isChannelsLast = dataFormat === "channelsLast";
const xBatchStride = dx.strides[0];
const xRowStride = isChannelsLast ? dx.strides[1] : dx.strides[2];
const xColStride = isChannelsLast ? dx.strides[2] : 1;
const xChannelStride = isChannelsLast ? 1 : dx.strides[1];
const yBatchStride = dy.strides[0];
const yRowStride = isChannelsLast ? dy.strides[1] : dy.strides[2];
const yColStride = isChannelsLast ? dy.strides[2] : 1;
const yChannelStride = isChannelsLast ? 1 : dy.strides[1];
for (let b = 0; b < batchSize; ++b) {
for (let d1 = 0; d1 < inChannels; ++d1) {
for (let xR = 0; xR < inHeight; ++xR) {
const xRCorner = xR - topPad;
const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
const yRMax = Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);
for (let xC = 0; xC < inWidth; ++xC) {
const xCCorner = xC - leftPad;
const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
const yCMax = Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);
let dotProd = 0;
for (let yR = xRMin; yR < yRMax; ++yR) {
const wR = yR * strideHeight - xRCorner;
for (let yC = xCMin; yC < yCMax; ++yC) {
const wC = yC * strideWidth - xCCorner;
const dyOffset = yBatchStride * b + yRowStride * yR + yColStride * yC;
const fltOffset =
fltS0 * (filterHeight - 1 - wR) +
fltS1 * (filterWidth - 1 - wC) +
fltS2 * d1;
for (let d2 = 0; d2 < outChannels; ++d2) {
const pixel = dyValues[dyOffset + yChannelStride * d2];
const weight = fltValues[fltOffset + d2];
dotProd += pixel * weight;
}
}
}
const dxOffset =
xBatchStride * b + xRowStride * xR + xColStride * xC + xChannelStride * d1;
dxValues[dxOffset] = dotProd;
}
}
}
}
return dx.toTensor();
}
conv3dDerInput(dy, filter, convInfo) {
const dx = dist["buffer"](convInfo.inShape, "float32");
const dxValues = dx.values;
const [dxS0, dxS1, dxS2, dxS3] = dx.strides;
const dyValues = this.readSync(dy.dataId);
const [dyS0, dyS1, dyS2, dyS3] = dy.strides;
const fltValues = this.readSync(filter.dataId);
const [fltS0, fltS1, fltS2, fltS3] = filter.strides;
const {
batchSize,
filterDepth,
filterHeight,
filterWidth,
inChannels,
inDepth,
inHeight,
inWidth,
outChannels,
outDepth,
outHeight,
outWidth,
strideDepth,
strideHeight,
strideWidth,
} = convInfo;
const frontPad = filterDepth - 1 - convInfo.padInfo.front;
const topPad = filterHeight - 1 - convInfo.padInfo.top;
const leftPad = filterWidth - 1 - convInfo.padInfo.left;
for (let b = 0; b < batchSize; ++b) {
for (let d1 = 0; d1 < inChannels; ++d1) {
// Frames of depth
for (let xF = 0; xF < inDepth; ++xF) {
const xFCorner = xF - frontPad;
const xFMin = Math.max(0, Math.ceil(xFCorner / strideDepth));
const yFMax = Math.min(outDepth, (filterDepth + xFCorner) / strideDepth);
// Rows as per standard 2d matrix notation
for (let xR = 0; xR < inHeight; ++xR) {
const xRCorner = xR - topPad;
const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
const yRMax = Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);
// Columns as per standard 2d matrix notation
for (let xC = 0; xC < inWidth; ++xC) {
const xCCorner = xC - leftPad;
const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
const yCMax = Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);
let dotProd = 0;
for (let yF = xFMin; yF < yFMax; ++yF) {
const wF = yF * strideDepth - xFCorner;
for (let yR = xRMin; yR < yRMax; ++yR) {
const wR = yR * strideHeight - xRCorner;
for (let yC = xCMin; yC < yCMax; ++yC) {
const wC = yC * strideWidth - xCCorner;
const dyOffset = dyS0 * b + dyS1 * yF + dyS2 * yR + dyS3 * yC;
const fltOffset =
fltS0 * (filterDepth - 1 - wF) +
fltS1 * (filterHeight - 1 - wR) +
fltS2 * (filterWidth - 1 - wC) +
fltS3 * d1;
for (let d2 = 0; d2 < outChannels; ++d2) {
const pixel = dyValues[dyOffset + d2];
const weight = fltValues[fltOffset + d2];
dotProd += pixel * weight;
}
}
}
}
dxValues[dxS0 * b + dxS1 * xF + dxS2 * xR + dxS3 * xC + d1] = dotProd;
}
}
}
}
}
return dx.toTensor();
}
conv2dDerFilter(x, dy, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([x, dy], "conv2dDerFilter");
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const isChannelsLast = convInfo.dataFormat === "channelsLast";
const dW = dist["buffer"](convInfo.filterShape, "float32");
const leftPad = convInfo.padInfo.left;
const topPad = convInfo.padInfo.top;
const xBuf = this.bufferSync(x);
const dyBuf = this.bufferSync(dy);
for (let wR = 0; wR < filterHeight; ++wR) {
const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
const yRMax = Math.min(
convInfo.outHeight,
(convInfo.inHeight + topPad - wR) / strideHeight
);
for (let wC = 0; wC < filterWidth; ++wC) {
const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
const yCMax = Math.min(
convInfo.outWidth,
(convInfo.inWidth + leftPad - wC) / strideWidth
);
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {
// Need to convolve.
let dotProd = 0;
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let yR = yRMin; yR < yRMax; ++yR) {
const xR = wR + yR * strideHeight - topPad;
for (let yC = yCMin; yC < yCMax; ++yC) {
const xC = wC + yC * strideWidth - leftPad;
if (isChannelsLast) {
dotProd += xBuf.get(b, xR, xC, d1) * dyBuf.get(b, yR, yC, d2);
} else {
dotProd += xBuf.get(b, d1, xR, xC) * dyBuf.get(b, d2, yR, yC);
}
}
}
}
dW.set(dotProd, wR, wC, d1, d2);
}
}
}
}
return dW.toTensor();
}
conv3dDerFilter(x, dy, convInfo) {
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterDepth = convInfo.filterDepth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dw = dist["buffer"](convInfo.filterShape, "float32");
const dwValues = dw.values;
const [dwS0, dwS1, dwS2, dwS3] = dw.strides;
const dyValues = this.readSync(dy.dataId);
const [dyS0, dyS1, dyS2, dyS3] = dy.strides;
const xValues = this.readSync(x.dataId);
const [xS0, xS1, xS2, xS3] = x.strides;
const frontPad = convInfo.padInfo.front;
const leftPad = convInfo.padInfo.left;
const topPad = convInfo.padInfo.top;
for (let wF = 0; wF < filterDepth; ++wF) {
const yFMin = Math.max(0, Math.ceil((frontPad - wF) / strideDepth));
const yFMax = Math.min(
convInfo.outDepth,
(convInfo.inDepth + frontPad - wF) / strideDepth
);
const wOffset1 = wF * dwS0;
for (let wR = 0; wR < filterHeight; ++wR) {
const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
const yRMax = Math.min(
convInfo.outHeight,
(convInfo.inHeight + topPad - wR) / strideHeight
);
const wOffset2 = wR * dwS1 + wOffset1;
for (let wC = 0; wC < filterWidth; ++wC) {
const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
const yCMax = Math.min(
convInfo.outWidth,
(convInfo.inWidth + leftPad - wC) / strideWidth
);
const wOffset3 = wC * dwS2 + wOffset2;
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
const wOffset4 = d1 * dwS3 + wOffset3;
for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {
let dotProd = 0;
for (let b = 0; b < convInfo.batchSize; ++b) {
const xOffset1 = b * xS0;
const yOffset1 = b * dyS0;
for (let yF = yFMin; yF < yFMax; ++yF) {
const xF = wF + yF * strideDepth - frontPad;
const xOffset2 = xF * xS1 + xOffset1;
const yOffset2 = yF * dyS1 + yOffset1;
for (let yR = yRMin; yR < yRMax; ++yR) {
const xR = wR + yR * strideHeight - topPad;
const xOffset3 = xR * xS2 + xOffset2;
const yOffset3 = yR * dyS2 + yOffset2;
for (let yC = yCMin; yC < yCMax; ++yC) {
const xC = wC + yC * strideWidth - leftPad;
const xOffset4 = xC * xS3 + xOffset3;
const yOffset4 = yC * dyS3 + yOffset3;
dotProd += xValues[xOffset4 + d1] * dyValues[yOffset4 + d2];
}
}
}
}
dwValues[wOffset4 + d2] = dotProd;
}
}
}
}
}
return dw.toTensor();
}
fusedDepthwiseConv2D({
input,
filter,
convInfo,
bias,
activation,
preluActivationWeights,
}) {
let result = this.depthwiseConv2D(input, filter, convInfo);
if (bias) {
result = this.add(result, bias);
}
if (activation) {
result = mapActivation(this, result, activation, preluActivationWeights);
}
return result;
}
depthwiseConv2D(x, filter, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([x, filter], "depthwiseConv2D");
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const padLeft = convInfo.padInfo.left;
const padTop = convInfo.padInfo.top;
const chMul = convInfo.outChannels / convInfo.inChannels;
const y = dist["buffer"](convInfo.outShape, x.dtype);
const xVals = this.readSync(x.dataId);
const wVals = this.readSync(filter.dataId);
const yVals = y.values;
for (let b = 0; b < convInfo.batchSize; ++b) {
const xOffset1 = b * x.strides[0];
const yOffset1 = b * y.strides[0];
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const yOffset2 = yOffset1 + yR * y.strides[1];
const xRCorner = yR * convInfo.strideHeight - padLeft;
for (let wR = 0; wR < filterHeight; ++wR) {
const xR = xRCorner + wR * dilationHeight;
if (xR < 0 || xR >= convInfo.inHeight) {
continue;
}
const wOffset1 = wR * filter.strides[0];
const xOffset2 = xOffset1 + xR * x.strides[1];
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const yOffset3 = yOffset2 + yC * y.strides[2];
const xCCorner = yC * convInfo.strideWidth - padTop;
for (let wC = 0; wC < filterWidth; ++wC) {
const xC = xCCorner + wC * dilationWidth;
if (xC < 0 || xC >= convInfo.inWidth) {
continue;
}
const wOffset2 = wOffset1 + wC * filter.strides[1];
const xOffset3 = xOffset2 + xC * convInfo.inChannels;
let yOffset4 = yOffset3;
let wOffset3 = wOffset2;
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
const xVal = xVals[xOffset3 + d1];
for (let q = 0; q < chMul; ++q) {
yVals[yOffset4 + q] += xVal * wVals[wOffset3 + q];
}
yOffset4 += chMul;
wOffset3 += chMul;
}
}
}
}
}
}
return y.toTensor();
}
depthwiseConv2DDerInput(dy, filter, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([dy, filter], "depthwiseConv2DDerInput");
const dx = dist["buffer"](convInfo.inShape, "float32");
const dxValues = dx.values;
const [dxS0, dxS1, dxS2] = dx.strides;
const dyValues = this.readSync(dy.dataId);
const [dyS0, dyS1, dyS2] = dy.strides;
const fltValues = this.readSync(filter.dataId);
const [fltS0, fltS1, fltS2] = filter.strides;
const {
batchSize,
filterHeight,
filterWidth,
inChannels,
inHeight,
inWidth,
outChannels,
outHeight,
outWidth,
strideHeight,
strideWidth,
} = convInfo;
const topPad = filterHeight - 1 - convInfo.padInfo.top;
const leftPad = filterWidth - 1 - convInfo.padInfo.left;
const chMul = outChannels / inChannels;
for (let b = 0; b < batchSize; ++b) {
for (let d1 = 0; d1 < inChannels; ++d1) {
for (let xR = 0; xR < inHeight; ++xR) {
const xRCorner = xR - topPad;
const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
const yRMax = Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);
for (let xC = 0; xC < inWidth; ++xC) {
const xCCorner = xC - leftPad;
const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
const yCMax = Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);
let dotProd = 0;
for (let yR = xRMin; yR < yRMax; ++yR) {
const wR = yR * strideHeight - xRCorner;
for (let yC = xCMin; yC < yCMax; ++yC) {
const wC = yC * strideWidth - xCCorner;
const dyOffset = dyS0 * b + dyS1 * yR + dyS2 * yC;
const fltOffset =
fltS0 * (filterHeight - 1 - wR) +
fltS1 * (filterWidth - 1 - wC) +
fltS2 * d1;
for (let dm = 0; dm < chMul; ++dm) {
const d2 = d1 * chMul + dm;
const pixel = dyValues[dyOffset + d2];
const weight = fltValues[fltOffset + dm];
dotProd += pixel * weight;
}
}
}
dxValues[dxS0 * b + dxS1 * xR + dxS2 * xC + d1] = dotProd;
}
}
}
}
return dx.toTensor();
}
depthwiseConv2DDerFilter(x, dy, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([x, dy], "depthwiseConv2DDerFilter");
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dW = dist["buffer"](convInfo.filterShape, "float32");
const leftPad = convInfo.padInfo.left;
const topPad = convInfo.padInfo.top;
const chMul = convInfo.outChannels / convInfo.inChannels;
const xBuf = this.bufferSync(x);
const dyBuf = this.bufferSync(dy);
for (let wR = 0; wR < filterHeight; ++wR) {
const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
const yRMax = Math.min(
convInfo.outHeight,
(convInfo.inHeight + topPad - wR) / strideHeight
);
for (let wC = 0; wC < filterWidth; ++wC) {
const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
const yCMax = Math.min(
convInfo.outWidth,
(convInfo.inWidth + leftPad - wC) / strideWidth
);
for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {
const d1 = Math.trunc(d2 / chMul);
const dm = d2 % chMul;
let dotProd = 0;
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let yR = yRMin; yR < yRMax; ++yR) {
const xR = wR + yR * strideHeight - topPad;
for (let yC = yCMin; yC < yCMax; ++yC) {
const xC = wC + yC * strideWidth - leftPad;
dotProd += xBuf.get(b, xR, xC, d1) * dyBuf.get(b, yR, yC, d2);
}
}
}
dW.set(dotProd, wR, wC, d1, dm);
}
}
}
return dW.toTensor();
}
tile(x, reps) {
Object(cpu_util["a" /* assertNotComplex */])(x, "tile");
return tile(this.bufferSync(x), reps);
}
pad(x, paddings, constantValue) {
Object(cpu_util["a" /* assertNotComplex */])(x, "pad");
const outShape = paddings.map(
(p, i) => p[0] /* beforePad */ + x.shape[i] + p[1] /* afterPad */
);
const start = paddings.map((p) => p[0]);
const xBuffer = this.bufferSync(x);
const buffer = dist["buffer"](outShape, x.dtype);
if (constantValue !== 0) {
buffer.values.fill(constantValue);
}
for (let i = 0; i < x.size; i++) {
const coords = xBuffer.indexToLoc(i);
const outCoords = coords.map((c, i) => c + start[i]);
buffer.set(xBuffer.get(...coords), ...outCoords);
}
return buffer.toTensor();
}
gather(x, indices, axis) {
Object(cpu_util["a" /* assertNotComplex */])([x, indices], "gather");
const newShape = x.shape.slice();
const indicesValues = this.readSync(indices.dataId);
newShape[axis] = indicesValues.length;
const result = dist["buffer"](newShape, x.dtype);
const xBuf = this.bufferSync(x);
for (let i = 0; i < result.size; ++i) {
const newLoc = result.indexToLoc(i);
const originalLoc = newLoc.slice();
originalLoc[axis] = indicesValues[newLoc[axis]];
const originalIndex = xBuf.locToIndex(originalLoc);
result.values[i] = xBuf.values[originalIndex];
}
return result.toTensor();
}
batchToSpaceND(x, blockShape, crops) {
Object(cpu_util["a" /* assertNotComplex */])([x], "batchToSpaceND");
const prod = blockShape.reduce((a, b) => a * b);
const reshaped = dist["backend_util"].getReshaped(x.shape, blockShape, prod);
const permuted = dist["backend_util"].getPermuted(reshaped.length, blockShape.length);
const reshapedPermuted = dist["backend_util"].getReshapedPermuted(
x.shape,
blockShape,
prod
);
const sliceBeginCoords = dist["backend_util"].getSliceBeginCoords(
crops,
blockShape.length
);
const sliceSize = dist["backend_util"].getSliceSize(
reshapedPermuted,
crops,
blockShape.length
);
return dist["transpose"](x.reshape(reshaped), permuted)
.reshape(reshapedPermuted)
.slice(sliceBeginCoords, sliceSize);
}
spaceToBatchND(x, blockShape, paddings) {
Object(cpu_util["a" /* assertNotComplex */])([x], "spaceToBatchND");
const prod = blockShape.reduce((a, b) => a * b);
const completePaddings = [[0, 0]];
completePaddings.push(...paddings);
for (let i = 1 + blockShape.length; i < x.shape.length; ++i) {
completePaddings.push([0, 0]);
}
const paddedX = x.pad(completePaddings);
const reshapedPaddedShape = dist["backend_util"].getReshaped(
paddedX.shape,
blockShape,
prod,
false
);
const permutedReshapedPaddedPermutation = dist["backend_util"].getPermuted(
reshapedPaddedShape.length,
blockShape.length,
false
);
const flattenShape = dist["backend_util"].getReshapedPermuted(
paddedX.shape,
blockShape,
prod,
false
);
return dist["transpose"](
paddedX.reshape(reshapedPaddedShape),
permutedReshapedPaddedPermutation
).reshape(flattenShape);
}
maxPool(x, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])(x, "maxPool");
const xValues = this.readSync(x.dataId);
return Object(pool_utils["b" /* pool */])(
xValues,
x.shape,
x.dtype,
x.strides,
convInfo,
"max"
).toTensor();
}
maxPoolBackprop(dy, x, y, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([x, y], "maxPoolBackprop");
const xValues = this.readSync(x.dataId);
const maxPosBuf = Object(dist["buffer"])(
convInfo.outShape,
x.dtype,
Object(pool_utils["a" /* maxPoolPositions */])(xValues, x.shape, x.dtype, convInfo)
.values
);
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const dx = dist["buffer"](x.shape, "float32");
const dyBuf = this.bufferSync(dy);
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d = 0; d < convInfo.inChannels; ++d) {
for (let dxR = 0; dxR < convInfo.inHeight; ++dxR) {
for (let dxC = 0; dxC < convInfo.inWidth; ++dxC) {
// Shader code begins.
const dyRCorner = dxR - padTop;
const dyCCorner = dxC - padLeft;
let dotProd = 0;
for (let wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {
const dyR = (dyRCorner + wR) / strideHeight;
if (dyR < 0 || dyR >= convInfo.outHeight || Math.floor(dyR) !== dyR) {
continue;
}
for (let wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {
const dyC = (dyCCorner + wC) / strideWidth;
if (dyC < 0 || dyC >= convInfo.outWidth || Math.floor(dyC) !== dyC) {
continue;
}
const maxPos =
effectiveFilterHeight * effectiveFilterWidth -
1 -
maxPosBuf.get(b, dyR, dyC, d);
const curPos = wR * effectiveFilterWidth + wC;
const mask = maxPos === curPos ? 1 : 0;
if (mask === 0) {
continue;
}
const pixel = dyBuf.get(b, dyR, dyC, d);
dotProd += pixel * mask;
}
}
dx.set(dotProd, b, dxR, dxC, d);
}
}
}
}
return dx.toTensor();
}
avgPoolBackprop(dy, x, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([dy, x], "avgPoolBackprop");
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const dx = dist["buffer"](x.shape, "float32");
const avgMultiplier = 1 / (filterHeight * filterWidth);
const dyBuf = this.bufferSync(dy);
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d = 0; d < convInfo.inChannels; ++d) {
for (let dxR = 0; dxR < convInfo.inHeight; ++dxR) {
for (let dxC = 0; dxC < convInfo.inWidth; ++dxC) {
// Shader code begins.
const dyRCorner = dxR - padTop;
const dyCCorner = dxC - padLeft;
let dotProd = 0;
for (let wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {
const dyR = (dyRCorner + wR) / strideHeight;
if (dyR < 0 || dyR >= convInfo.outHeight || Math.floor(dyR) !== dyR) {
continue;
}
for (let wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {
const dyC = (dyCCorner + wC) / strideWidth;
if (dyC < 0 || dyC >= convInfo.outWidth || Math.floor(dyC) !== dyC) {
continue;
}
const pixel = dyBuf.get(b, dyR, dyC, d);
dotProd += pixel;
}
}
dx.set(dotProd * avgMultiplier, b, dxR, dxC, d);
}
}
}
}
return dx.toTensor();
}
pool3d(x, convInfo, poolType) {
Object(cpu_util["a" /* assertNotComplex */])(x, "pool3d");
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterDepth = convInfo.effectiveFilterDepth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padFront = convInfo.padInfo.front;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const initialValue =
poolType === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
const xValues = this.readSync(x.dataId);
const output = dist["buffer"](convInfo.outShape, x.dtype);
const outputVals = output.values;
const outputBatchStrides =
convInfo.outShape[1] *
convInfo.outShape[2] *
convInfo.outShape[3] *
convInfo.outShape[4];
const outputDepthStrides =
convInfo.outShape[2] * convInfo.outShape[3] * convInfo.outShape[4];
const outputRowStrides = convInfo.outShape[3] * convInfo.outShape[4];
const outputColStrides = convInfo.outShape[4];
for (let batch = 0; batch < convInfo.batchSize; ++batch) {
const outputBatchOffset = batch * outputBatchStrides;
const inputBatchOffset = batch * x.strides[0];
for (let channel = 0; channel < convInfo.inChannels; ++channel) {
for (let yDepth = 0; yDepth < convInfo.outDepth; ++yDepth) {
const xDepthCorner = yDepth * strideDepth - padFront;
let xDepthMin = xDepthCorner;
while (xDepthMin < 0) {
xDepthMin += dilationDepth;
}
const xDepthMax = Math.min(convInfo.inDepth, effectiveFilterDepth + xDepthCorner);
const outputDepthOffset = outputBatchOffset + yDepth * outputDepthStrides;
for (let yRow = 0; yRow < convInfo.outHeight; ++yRow) {
const xRowCorner = yRow * strideHeight - padTop;
let xRowMin = xRowCorner;
while (xRowMin < 0) {
xRowMin += dilationHeight;
}
const xRowMax = Math.min(convInfo.inHeight, effectiveFilterHeight + xRowCorner);
const outputRowOffset = outputDepthOffset + yRow * outputRowStrides;
for (let yCol = 0; yCol < convInfo.outWidth; ++yCol) {
const xColCorner = yCol * strideWidth - padLeft;
let xColMin = xColCorner;
while (xColMin < 0) {
xColMin += dilationWidth;
}
const xColMax = Math.min(convInfo.inWidth, effectiveFilterWidth + xColCorner);
// Shader code begins
const outputColOffset = outputRowOffset + yCol * outputColStrides;
let minMaxValue = initialValue;
let avgValue = 0;
let count = 0;
for (let xDepth = xDepthMin; xDepth < xDepthMax; xDepth += dilationDepth) {
const xDepthOffset = inputBatchOffset + xDepth * x.strides[1];
for (let xRow = xRowMin; xRow < xRowMax; xRow += dilationHeight) {
const xRowOffset = xDepthOffset + xRow * x.strides[2];
for (let xCol = xColMin; xCol < xColMax; xCol += dilationWidth) {
const xColOffset = xRowOffset + xCol * x.strides[3];
const pixel = xValues[xColOffset + channel];
if (poolType === "max" && pixel > minMaxValue) {
minMaxValue = pixel;
} else if (poolType === "avg") {
avgValue += pixel;
count++;
}
if (isNaN(minMaxValue)) {
break;
}
}
if (isNaN(minMaxValue)) {
break;
}
}
if (isNaN(minMaxValue)) {
break;
}
}
const outputOffset = outputColOffset + channel;
outputVals[outputOffset] = poolType === "avg" ? avgValue / count : minMaxValue;
}
}
}
}
}
return output.toTensor();
}
avgPool3d(x, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])(x, "avgPool3d");
return this.pool3d(x, convInfo, "avg").toFloat();
}
avgPool3dBackprop(dy, x, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([dy, x], "avgPool3dBackprop");
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterDepth = convInfo.filterDepth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterDepth = convInfo.effectiveFilterDepth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const dx = dist["buffer"](x.shape, "float32");
const avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);
const dyBuf = this.bufferSync(dy);
for (let batch = 0; batch < convInfo.batchSize; ++batch) {
for (let channel = 0; channel < convInfo.inChannels; ++channel) {
for (let dxDepth = 0; dxDepth < convInfo.inDepth; ++dxDepth) {
for (let dxRow = 0; dxRow < convInfo.inHeight; ++dxRow) {
for (let dxCol = 0; dxCol < convInfo.inWidth; ++dxCol) {
// Shader code begins.
const dyDepthCorner = dxDepth - padFront;
const dyRowCorner = dxRow - padTop;
const dyColCorner = dxCol - padLeft;
let dotProd = 0;
for (let wDepth = 0; wDepth < effectiveFilterDepth; wDepth += dilationDepth) {
const dyDepth = (dyDepthCorner + wDepth) / strideDepth;
if (
dyDepth < 0 ||
dyDepth >= convInfo.outDepth ||
Math.floor(dyDepth) !== dyDepth
) {
continue;
}
for (let wRow = 0; wRow < effectiveFilterHeight; wRow += dilationHeight) {
const dyRow = (dyRowCorner + wRow) / strideHeight;
if (
dyRow < 0 ||
dyRow >= convInfo.outHeight ||
Math.floor(dyRow) !== dyRow
) {
continue;
}
for (let wCol = 0; wCol < effectiveFilterWidth; wCol += dilationWidth) {
const dyCol = (dyColCorner + wCol) / strideWidth;
if (
dyCol < 0 ||
dyCol >= convInfo.outWidth ||
Math.floor(dyCol) !== dyCol
) {
continue;
}
const pixel = dyBuf.get(batch, dyDepth, dyRow, dyCol, channel);
dotProd += pixel;
}
}
}
dx.set(dotProd * avgMultiplier, batch, dxDepth, dxRow, dxCol, channel);
}
}
}
}
}
return dx.toTensor();
}
maxPool3d(x, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])(x, "maxPool3d");
return this.pool3d(x, convInfo, "max").toFloat();
}
maxPool3dPositions(x, convInfo) {
const maxPositions = dist["buffer"](convInfo.outShape, "int32");
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterDepth = convInfo.effectiveFilterDepth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padFront = convInfo.padInfo.front;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const xBuf = this.bufferSync(x);
for (let batch = 0; batch < convInfo.batchSize; ++batch) {
for (let channel = 0; channel < convInfo.inChannels; ++channel) {
for (let yDepth = 0; yDepth < convInfo.outDepth; ++yDepth) {
const xDepthCorner = yDepth * strideDepth - padFront;
let xDepthMin = xDepthCorner;
while (xDepthMin < 0) {
xDepthMin += dilationDepth;
}
const xDepthMax = Math.min(convInfo.inDepth, effectiveFilterDepth + xDepthCorner);
for (let yRow = 0; yRow < convInfo.outHeight; ++yRow) {
const xRowCorner = yRow * strideHeight - padTop;
let xRowMin = xRowCorner;
while (xRowMin < 0) {
xRowMin += dilationHeight;
}
const xRowMax = Math.min(convInfo.inHeight, effectiveFilterHeight + xRowCorner);
for (let yCol = 0; yCol < convInfo.outWidth; ++yCol) {
const xColCorner = yCol * strideWidth - padLeft;
let xColMin = xColCorner;
while (xColMin < 0) {
xColMin += dilationWidth;
}
const xColMax = Math.min(convInfo.inWidth, effectiveFilterWidth + xColCorner);
// Shader code begins
let maxValue = Number.NEGATIVE_INFINITY;
let maxPosition = -1;
for (let xDepth = xDepthMin; xDepth < xDepthMax; xDepth += dilationDepth) {
const wDepth = xDepth - xDepthCorner;
for (let xRow = xRowMin; xRow < xRowMax; xRow += dilationHeight) {
const wRow = xRow - xRowCorner;
for (let xCol = xColMin; xCol < xColMax; xCol += dilationWidth) {
const wCol = xCol - xColCorner;
const pixel = xBuf.get(batch, xDepth, xRow, xCol, channel);
if (pixel >= maxValue) {
maxValue = pixel;
maxPosition =
wDepth * effectiveFilterHeight * effectiveFilterWidth +
wRow * effectiveFilterHeight +
wCol;
}
}
}
}
maxPositions.set(maxPosition, batch, yDepth, yRow, yCol, channel);
}
}
}
}
}
return maxPositions.toTensor();
}
maxPool3dBackprop(dy, x, y, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])([x, y], "maxPool3dBackprop");
const maxPositions = this.maxPool3dPositions(x, convInfo);
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterDepth = convInfo.effectiveFilterDepth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const dx = dist["buffer"](x.shape, "float32");
const maxPosBuf = this.bufferSync(maxPositions);
const dyBuf = this.bufferSync(dy);
for (let batch = 0; batch < convInfo.batchSize; ++batch) {
for (let channel = 0; channel < convInfo.inChannels; ++channel) {
for (let dxDepth = 0; dxDepth < convInfo.inDepth; ++dxDepth) {
for (let dxRow = 0; dxRow < convInfo.inHeight; ++dxRow) {
for (let dxCol = 0; dxCol < convInfo.inWidth; ++dxCol) {
// Shader code begins
const dyDepthCorner = dxDepth - padFront;
const dyRowCorner = dxRow - padTop;
const dyColCorner = dxCol - padLeft;
let dotProd = 0;
for (let wDepth = 0; wDepth < effectiveFilterDepth; wDepth += dilationDepth) {
const dyDepth = (dyDepthCorner + wDepth) / strideDepth;
if (
dyDepth < 0 ||
dyDepth >= convInfo.outDepth ||
Math.floor(dyDepth) !== dyDepth
) {
continue;
}
for (let wRow = 0; wRow < effectiveFilterHeight; wRow += dilationHeight) {
const dyRow = (dyRowCorner + wRow) / strideHeight;
if (
dyRow < 0 ||
dyRow >= convInfo.outHeight ||
Math.floor(dyRow) !== dyRow
) {
continue;
}
for (let wCol = 0; wCol < effectiveFilterWidth; wCol += dilationWidth) {
const dyCol = (dyColCorner + wCol) / strideWidth;
if (
dyCol < 0 ||
dyCol >= convInfo.outWidth ||
Math.floor(dyCol) !== dyCol
) {
continue;
}
const maxPos =
effectiveFilterDepth * effectiveFilterHeight * effectiveFilterWidth -
1 -
maxPosBuf.get(batch, dyDepth, dyRow, dyCol, channel);
const curPos =
wDepth * effectiveFilterHeight * effectiveFilterWidth +
wRow * effectiveFilterWidth +
wCol;
const mask = maxPos === curPos ? 1 : 0;
if (mask === 0) {
continue;
}
const pixel = dyBuf.get(batch, dyDepth, dyRow, dyCol, channel);
dotProd += pixel * mask;
}
}
}
dx.set(dotProd, batch, dxDepth, dxRow, dxCol, channel);
}
}
}
}
}
return dx.toTensor();
}
cast(x, dtype) {
return dist["backend_util"].castTensor(x, dtype, this);
}
reshape(x, shape) {
return dist["backend_util"].reshapeTensor(x, shape);
}
avgPool(x, convInfo) {
Object(cpu_util["a" /* assertNotComplex */])(x, "avgPool");
Object(cpu_util["a" /* assertNotComplex */])(x, "maxPool");
const xValues = this.readSync(x.dataId);
return Object(pool_utils["b" /* pool */])(
xValues,
x.shape,
x.dtype,
x.strides,
convInfo,
"avg"
)
.toTensor()
.toFloat();
}
resizeBilinear(x, newHeight, newWidth, alignCorners) {
Object(cpu_util["a" /* assertNotComplex */])(x, "resizeBilinear");
const [batch, oldHeight, oldWidth, numChannels] = x.shape;
const xValues = this.readSync(x.dataId);
const result = new Float32Array(
dist["util"].sizeFromShape([batch, newHeight, newWidth, numChannels])
);
const effectiveInputSize = [
alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth,
];
const effectiveOutputSize = [
alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
alignCorners && newWidth > 1 ? newWidth - 1 : newWidth,
];
let outputIdx = 0;
const effectiveRowSizeRatio = effectiveInputSize[0] / effectiveOutputSize[0];
const effectiveColSizeRatio = effectiveInputSize[1] / effectiveOutputSize[1];
for (let b = 0; b < batch; b++) {
for (let r = 0; r < newHeight; r++) {
const sourceFracRow = effectiveRowSizeRatio * r;
const sourceRowFloor = Math.floor(sourceFracRow);
const rowFrac = sourceFracRow - sourceRowFloor;
const sourceRowCeil = Math.min(oldHeight - 1, Math.ceil(sourceFracRow));
const topRowOffset = b * x.strides[0] + sourceRowFloor * x.strides[1];
const botRowOffset = b * x.strides[0] + sourceRowCeil * x.strides[1];
for (let c = 0; c < newWidth; c++) {
const sourceFracCol = effectiveColSizeRatio * c;
const sourceColFloor = Math.floor(sourceFracCol);
const colFrac = sourceFracCol - sourceColFloor;
const sourceColCeil = Math.min(oldWidth - 1, Math.ceil(sourceFracCol));
const topLeftOffest = topRowOffset + sourceColFloor * x.strides[2];
const botLeftOffset = botRowOffset + sourceColFloor * x.strides[2];
const topRightOffset = topRowOffset + sourceColCeil * x.strides[2];
const botRightOffest = botRowOffset + sourceColCeil * x.strides[2];
for (let d = 0; d < numChannels; d++) {
// Begin shader.
// Compute the fractional index of the source.
const topLeft = xValues[topLeftOffest + d];
const bottomLeft = xValues[botLeftOffset + d];
const topRight = xValues[topRightOffset + d];
const bottomRight = xValues[botRightOffest + d];
const top = topLeft + (topRight - topLeft) * colFrac;
const bottom = bottomLeft + (bottomRight - bottomLeft) * colFrac;
const newValue = top + (bottom - top) * rowFrac;
result[outputIdx++] = newValue;
}
}
}
}
return dist["tensor"](result, [batch, newHeight, newWidth, numChannels]);
}
resizeBilinearBackprop(dy, x, alignCorners) {
Object(cpu_util["a" /* assertNotComplex */])([dy, x], "resizeBilinearBackprop");
const [batch, xHeight, xWidth, depth] = x.shape;
const [, yHeight, yWidth] = dy.shape;
const output = new Float32Array(batch * xHeight * xWidth * depth);
// In the backwards pass, we want to find the pixels that were generated
// for each pixel in the input image the forward pass and add the
// corresponding coefficient from dy to the gradient (with some
// interpolation).
const effectiveXSize = [
alignCorners && yHeight > 1 ? xHeight - 1 : xHeight,
alignCorners && yWidth > 1 ? xWidth - 1 : xWidth,
];
const effectiveYSize = [
alignCorners && yHeight > 1 ? yHeight - 1 : yHeight,
alignCorners && yWidth > 1 ? yWidth - 1 : yWidth,
];
const heightScale = effectiveXSize[0] / effectiveYSize[0];
const widthScale = effectiveXSize[1] / effectiveYSize[1];
// Reference implementation
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/3039375c86a5bbc9610c7725dcaa95d635f87ba2/tensorflow/core/kernels/resize_bilinear_op.cc#L275
const dyValues = this.readSync(dy.dataId);
let offset = 0;
for (let b = 0; b < batch; b++) {
const bOffset = b * x.strides[0];
for (let r = 0; r < yHeight; r++) {
const dxR = r * heightScale;
const topDxRIndex = Math.floor(dxR);
const bottomDxRIndex = Math.min(Math.ceil(dxR), xHeight - 1);
const topDxROffset = bOffset + topDxRIndex * x.strides[1];
const bottomDxROffset = bOffset + bottomDxRIndex * x.strides[1];
const dxRLerp = dxR - topDxRIndex;
const inverseDxRLerp = 1.0 - dxRLerp;
for (let c = 0; c < yWidth; c++) {
const dxC = c * widthScale;
const leftDxCIndex = Math.floor(dxC);
const rightDxCIndex = Math.min(Math.ceil(dxC), xWidth - 1);
const dxCLerp = dxC - leftDxCIndex;
const inverseDxCLerp = 1.0 - dxCLerp;
const topLeftRCOffset = topDxROffset + leftDxCIndex * x.strides[2];
const topRightRCOffset = topDxROffset + rightDxCIndex * x.strides[2];
const bottomLeftRCOffset = bottomDxROffset + leftDxCIndex * x.strides[2];
const bottomRightRCOffset = bottomDxROffset + rightDxCIndex * x.strides[2];
const inverseDxRLerpTimesInverseDxCLerp = inverseDxRLerp * inverseDxCLerp;
const inverseDxRLerpTimesDxCLerp = inverseDxRLerp * dxCLerp;
const dxRLerpTimesInverseDxCLerp = dxRLerp * inverseDxCLerp;
const dxRLerpTimesDxCLerp = dxRLerp * dxCLerp;
for (let d = 0; d < depth; d++) {
const dyVal = dyValues[offset++];
output[topLeftRCOffset + d] += dyVal * inverseDxRLerpTimesInverseDxCLerp;
output[topRightRCOffset + d] += dyVal * inverseDxRLerpTimesDxCLerp;
output[bottomLeftRCOffset + d] += dyVal * dxRLerpTimesInverseDxCLerp;
output[bottomRightRCOffset + d] += dyVal * dxRLerpTimesDxCLerp;
}
}
}
}
return dist["tensor4d"](output, [batch, xWidth, xHeight, depth], x.dtype);
}
resizeNearestNeighbor(x, newHeight, newWidth, alignCorners) {
Object(cpu_util["a" /* assertNotComplex */])(x, "resizeNearestNeighbor");
const [batch, oldHeight, oldWidth, numChannels] = x.shape;
const xValues = this.readSync(x.dataId);
const output = new Float32Array(batch * newHeight * newWidth * numChannels);
const effectiveInputSize = [
alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth,
];
const effectiveOutputSize = [
alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
alignCorners && newWidth > 1 ? newWidth - 1 : newWidth,
];
const effectiveRowSizeRatio = effectiveInputSize[0] / effectiveOutputSize[0];
const effectiveColSizeRatio = effectiveInputSize[1] / effectiveOutputSize[1];
let outputOffset = 0;
for (let b = 0; b < batch; b++) {
const batchOffset = b * x.strides[0];
for (let r = 0; r < newHeight; r++) {
const sourceFracRow = effectiveRowSizeRatio * r;
const sourceNearestRow = Math.min(
oldHeight - 1,
alignCorners ? Math.round(sourceFracRow) : Math.floor(sourceFracRow)
);
const rowOffset = batchOffset + sourceNearestRow * x.strides[1];
for (let c = 0; c < newWidth; c++) {
const sourceFracCol = effectiveColSizeRatio * c;
const sourceNearestCol = Math.min(
oldWidth - 1,
alignCorners ? Math.round(sourceFracCol) : Math.floor(sourceFracCol)
);
const colOffset = rowOffset + sourceNearestCol * x.strides[2];
for (let d = 0; d < numChannels; d++) {
// Begin shader.
// Compute the fractional index of the source.
const newVal = xValues[colOffset + d];
output[outputOffset++] = newVal;
}
}
}
}
return dist["tensor"](output, [batch, newHeight, newWidth, numChannels], x.dtype);
}
resizeNearestNeighborBackprop(dy, x, alignCorners) {
Object(cpu_util["a" /* assertNotComplex */])([dy, x], "resizeNearestNeighborBackprop");
const [batch, xHeight, xWidth, depth] = x.shape;
const [, yHeight, yWidth] = dy.shape;
const output = new Float32Array(batch * xHeight * xWidth * depth);
const dyValues = this.readSync(dy.dataId);
// In the backwards pass, we want to find the pixels that were generated
// for each pixel in the input image the forward pass
const effectiveXSize = [
alignCorners && yHeight > 1 ? xHeight - 1 : xHeight,
alignCorners && yWidth > 1 ? xWidth - 1 : xWidth,
];
const effectiveYSize = [
alignCorners && yHeight > 1 ? yHeight - 1 : yHeight,
alignCorners && yWidth > 1 ? yWidth - 1 : yWidth,
];
const heightScale = effectiveXSize[0] / effectiveYSize[0];
const widthScale = effectiveXSize[1] / effectiveYSize[1];
const invHeightScale = 1 / heightScale;
const invWidthScale = 1 / widthScale;
// This defines the size of the window of values around a particular
// index in dy that we want to search for contributions to dx.
const winHeight = Math.ceil(invHeightScale) * 2 + 2;
const winWidth = Math.ceil(invWidthScale) * 2 + 2;
// Loop over the output space.
for (let b = 0; b < batch; b++) {
const batchOffset = b * x.strides[0];
for (let r = 0; r < xHeight; r++) {
const rowOffset = batchOffset + r * x.strides[1];
// Compute bounds for where in dy we will look
const startRLerp = Math.floor(r * invHeightScale);
const startDyR = Math.floor(startRLerp - winHeight / 2);
for (let c = 0; c < xWidth; c++) {
const colOffset = rowOffset + c * x.strides[2];
// Compute bounds for where in dy we will look
const startCLerp = Math.floor(c * invWidthScale);
const startDyC = Math.floor(startCLerp - winWidth / 2);
for (let d = 0; d < depth; d++) {
let accum = 0;
// loop over dy
for (let dyRIndex = 0; dyRIndex < winHeight; dyRIndex++) {
const dyR = dyRIndex + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= yHeight) {
continue;
}
const dyROffset = batchOffset + dyR * dy.strides[1];
const sourceFracRow = dyR * heightScale;
const sourceNearestRow = Math.min(
xHeight - 1,
alignCorners ? Math.round(sourceFracRow) : Math.floor(sourceFracRow)
);
if (r !== sourceNearestRow) {
continue;
}
for (let dyCIndex = 0; dyCIndex < winWidth; dyCIndex++) {
const dyC = dyCIndex + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= yWidth) {
continue;
}
const dyCOffset = dyROffset + dyC * dy.strides[2];
const sourceFracCol = dyC * widthScale;
const sourceNearestCol = Math.min(
xWidth - 1,
alignCorners ? Math.round(sourceFracCol) : Math.floor(sourceFracCol)
);
if (c === sourceNearestCol) {
accum += dyValues[dyCOffset + d];
}
}
}
output[colOffset + d] = accum;
}
}
}
}
return dist["tensor4d"](output, x.shape, x.dtype);
}
batchNorm(x, mean, variance, offset, scale, varianceEpsilon) {
Object(cpu_util["a" /* assertNotComplex */])(
[x, mean, variance, scale, offset],
"batchNorm"
);
const xVals = this.readSync(x.dataId);
const mVals = this.readSync(mean.dataId);
const varVals = this.readSync(variance.dataId);
const sVals = scale ? this.readSync(scale.dataId) : new Float32Array([1]);
const offVals = offset ? this.readSync(offset.dataId) : new Float32Array([0]);
const outVals = new Float32Array(xVals.length);
const offValsLength = offVals.length;
const sValsLength = sVals.length;
const varValsLength = varVals.length;
const mValsLength = mVals.length;
let offi = 0;
let mi = 0;
let si = 0;
let vi = 0;
for (let i = 0; i < xVals.length; ++i) {
outVals[i] =
offVals[offi++] +
((xVals[i] - mVals[mi++]) * sVals[si++]) / Math.sqrt(varVals[vi++] + varianceEpsilon);
if (offi >= offValsLength) {
offi = 0;
}
if (mi >= mValsLength) {
mi = 0;
}
if (si >= sValsLength) {
si = 0;
}
if (vi >= varValsLength) {
vi = 0;
}
}
return dist["tensor4d"](outVals, x.shape);
}
localResponseNormalization4D(x, depthRadius, bias, alpha, beta) {
Object(cpu_util["a" /* assertNotComplex */])(x, "localResponseNormalization4D");
const channels = x.shape[3];
const maxD = channels - 1;
const xValues = this.readSync(x.dataId);
const size = x.size;
const result = new Float32Array(size);
function sumAcrossChannels(offset) {
const currentChannel = offset % channels;
let beginSumOffset =
offset - currentChannel + Math.max(0, currentChannel - depthRadius);
const endSumOffset =
offset - currentChannel + Math.min(currentChannel + depthRadius, maxD);
let sum = 0.0;
for (; beginSumOffset <= endSumOffset; beginSumOffset++) {
const z = xValues[beginSumOffset];
sum += z * z;
}
return sum;
}
for (let offset = 0; offset < size; offset++) {
const sum = sumAcrossChannels(offset);
const val = xValues[offset] * Math.pow(bias + alpha * sum, -beta);
result[offset] = val;
}
return dist["tensor4d"](result, x.shape);
}
LRNGrad(dy, inputImage, outputImage, depthRadius, bias, alpha, beta) {
Object(cpu_util["a" /* assertNotComplex */])(dy, "LRNGrad");
const channels = dy.shape[3];
const dyValues = this.readSync(dy.dataId);
const inputImageValues = this.readSync(inputImage.dataId);
const outputImageValues = this.readSync(outputImage.dataId);
const result = new Float32Array(dy.size);
const size = dy.size;
for (let offset = 0; offset < size; offset++) {
const currentChannel = offset % channels;
const depthBegin = offset - currentChannel + Math.max(0, currentChannel - depthRadius);
const depthEnd =
offset - currentChannel + Math.min(channels, currentChannel + depthRadius + 1);
let norm = 0;
for (let k = depthBegin; k < depthEnd; k++) {
norm += Math.pow(inputImageValues[k], 2);
}
norm = alpha * norm + bias;
for (let k = depthBegin; k < depthEnd; k++) {
let dyi =
(-2 * alpha * beta * inputImageValues[k] * outputImageValues[offset]) / norm;
if (offset === k) {
dyi += Math.pow(norm, -beta);
}
dyi *= dyValues[offset];
result[k] += dyi;
}
}
return dist["tensor4d"](result, dy.shape);
}
multinomial(logits, normalized, numSamples, seed) {
Object(cpu_util["a" /* assertNotComplex */])(logits, "multinomial");
const probabilities = normalized ? logits : dist["softmax"](logits);
const batchSize = probabilities.shape[0];
const numEvents = probabilities.shape[1];
const res = dist["zeros"]([batchSize, numSamples], "int32");
const resVals = this.readSync(res.dataId);
const probVals = this.readSync(probabilities.dataId);
for (let b = 0; b < batchSize; ++b) {
const offset = b * numEvents;
// The cdf won't include the last event. It will be implicit if no other
// event happened.
const cdf = new Float32Array(numEvents - 1);
cdf[0] = probVals[offset];
for (let event = 1; event < cdf.length; ++event) {
cdf[event] = cdf[event - 1] + probVals[offset + event];
}
const random = seedrandom["alea"](seed.toString());
const outOffset = b * numSamples;
for (let sampleId = 0; sampleId < numSamples; ++sampleId) {
const r = random();
// Assume last event happened by default.
resVals[outOffset + sampleId] = cdf.length;
for (let event = 0; event < cdf.length; event++) {
if (r < cdf[event]) {
resVals[outOffset + sampleId] = event;
break;
}
}
}
}
return res;
}
oneHot(indices, depth, onValue, offValue) {
Object(cpu_util["a" /* assertNotComplex */])(indices, "oneHot");
const res = new Float32Array(indices.size * depth);
res.fill(offValue);
const indicesVal = this.readSync(indices.dataId);
for (let event = 0; event < indices.size; ++event) {
if (indicesVal[event] >= 0 && indicesVal[event] < depth) {
res[event * depth + indicesVal[event]] = onValue;
}
}
return dist["tensor2d"](res, [indices.size, depth], "int32");
}
nonMaxSuppression(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
Object(cpu_util["a" /* assertNotComplex */])(boxes, "nonMaxSuppression");
const boxesVals = this.readSync(boxes.dataId);
const scoresVals = this.readSync(scores.dataId);
return nonMaxSuppressionV3(
boxesVals,
scoresVals,
maxOutputSize,
iouThreshold,
scoreThreshold
);
}
fft(x) {
return this.fftBatch(x, false);
}
ifft(x) {
return this.fftBatch(x, true);
}
/**
* Calculate FFT of inner most elements of batch tensor.
*/
fftBatch(x, inverse) {
const batch = x.shape[0];
const innerDim = x.shape[1];
// Collects real and imaginary values separately.
const realResult = dist["buffer"](x.shape, "float32");
const imagResult = dist["buffer"](x.shape, "float32");
const real = dist["real"](x).as2D(batch, innerDim);
const imag = dist["imag"](x).as2D(batch, innerDim);
for (let b = 0; b < batch; b++) {
// TODO: Support slice ops for complex type.
const r = real.slice([b, 0], [1, innerDim]);
const i = imag.slice([b, 0], [1, innerDim]);
const input = dist["complex"](r, i);
// Run FFT by batch element.
const res = this.readSync(this.fftImpl(input, inverse).dataId);
for (let d = 0; d < innerDim; d++) {
const c = dist["backend_util"].getComplexWithIndex(res, d);
realResult.values[b * innerDim + d] = c.real;
imagResult.values[b * innerDim + d] = c.imag;
}
}
const t = dist["complex"](realResult.toTensor(), imagResult.toTensor());
return t.as2D(batch, innerDim);
}
fftImpl(x, inverse) {
const x1D = x.as1D();
const n = x1D.size;
if (this.isExponentOf2(n)) {
let result = this.fftRadix2(x1D, n, inverse).as2D(x.shape[0], x.shape[1]);
if (inverse) {
result = dist["complex"](
dist["real"](result).div(dist["scalar"](n)),
dist["imag"](result).div(dist["scalar"](n))
);
}
return result;
} else {
const data = this.readSync(x.dataId);
const rawOutput = this.fourierTransformByMatmul(data, n, inverse);
const output = dist["backend_util"].splitRealAndImagArrays(rawOutput);
return dist["complex"](output.real, output.imag).as2D(x.shape[0], x.shape[1]);
}
}
isExponentOf2(size) {
return (size & (size - 1)) === 0;
}
// FFT using Cooley-Tukey algorithm on radix 2 dimensional input.
fftRadix2(input, size, inverse) {
if (size === 1) {
return input;
}
const data = this.readSync(input.dataId);
const half = size / 2;
const evenComplex = dist["backend_util"].complexWithEvenIndex(data);
let evenTensor = dist["complex"](evenComplex.real, evenComplex.imag).as1D();
const oddComplex = dist["backend_util"].complexWithOddIndex(data);
let oddTensor = dist["complex"](oddComplex.real, oddComplex.imag).as1D();
// Recursive call for half part of original input.
evenTensor = this.fftRadix2(evenTensor, half, inverse);
oddTensor = this.fftRadix2(oddTensor, half, inverse);
const e = dist["backend_util"].exponents(size, inverse);
const exponent = dist["complex"](e.real, e.imag).mul(oddTensor);
const addPart = evenTensor.add(exponent);
const subPart = evenTensor.sub(exponent);
const realTensor = dist["real"](addPart).concat(dist["real"](subPart));
const imagTensor = dist["imag"](addPart).concat(dist["imag"](subPart));
return dist["complex"](realTensor, imagTensor).as1D();
}
// Calculate fourier transform by multplying sinusoid matrix.
fourierTransformByMatmul(data, size, inverse) {
const ret = new Float32Array(size * 2);
// TODO: Use matmul instead once it supports complex64 type.
for (let r = 0; r < size; r++) {
let real = 0.0;
let imag = 0.0;
for (let c = 0; c < size; c++) {
const e = dist["backend_util"].exponent(r * c, size, inverse);
const term = dist["backend_util"].getComplexWithIndex(data, c);
real += term.real * e.real - term.imag * e.imag;
imag += term.real * e.imag + term.imag * e.real;
}
if (inverse) {
real /= size;
imag /= size;
}
dist["backend_util"].assignToTypedArray(ret, real, imag, r);
}
return ret;
}
depthToSpace(x, blockSize, dataFormat) {
dist["util"].assert(
dataFormat === "NHWC",
() => `Only NHWC dataFormat supported on CPU for depthToSpace. Got ${dataFormat}`
);
dist["util"].assert(
blockSize > 1,
() => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`
);
const batchSize = x.shape[0];
const inputHeight = x.shape[1];
const inputWidth = x.shape[2];
const inputDepth = x.shape[3];
const outputHeight = inputHeight * blockSize;
const outputWidth = inputWidth * blockSize;
const outputDepth = inputDepth / (blockSize * blockSize);
const xValues = this.readSync(x.dataId);
const result = new Float32Array(batchSize * outputHeight * outputWidth * outputDepth);
let outputIdx = 0;
for (let b = 0; b < batchSize; ++b) {
for (let h = 0; h < outputHeight; ++h) {
const inH = Math.floor(h / blockSize);
const offsetH = h % blockSize;
for (let w = 0; w < outputWidth; ++w) {
const inW = Math.floor(w / blockSize);
const offsetW = w % blockSize;
const offsetD = (offsetH * blockSize + offsetW) * outputDepth;
for (let d = 0; d < outputDepth; ++d) {
const inD = d + offsetD;
const inputIdx = inD + inputDepth * (inW + inputWidth * (inH + inputHeight * b));
result[outputIdx++] = xValues[inputIdx];
}
}
}
}
return dist["tensor4d"](result, [batchSize, outputHeight, outputWidth, outputDepth]);
}
broadcastedBinaryOp(a, b, dtype, op) {
const newShape = dist["backend_util"].assertAndGetBroadcastShape(a.shape, b.shape);
const result = dist["buffer"](newShape, dtype);
const aVals = this.readSync(a.dataId);
const bVals = this.readSync(b.dataId);
const aBroadcastDims = dist["backend_util"].getBroadcastDims(a.shape, newShape);
const bBroadcastDims = dist["backend_util"].getBroadcastDims(b.shape, newShape);
const resVals = result.values;
if (aBroadcastDims.length + bBroadcastDims.length === 0) {
for (let i = 0; i < resVals.length; ++i) {
resVals[i] = op(aVals[i % aVals.length], bVals[i % bVals.length]);
}
} else {
const aBuf = this.bufferSync(a);
const bBuf = this.bufferSync(b);
for (let i = 0; i < resVals.length; ++i) {
const loc = result.indexToLoc(i);
const aLoc = loc.slice(-a.rank);
aBroadcastDims.forEach((d) => (aLoc[d] = 0));
const aIndex = aBuf.locToIndex(aLoc);
const bLoc = loc.slice(-b.rank);
bBroadcastDims.forEach((d) => (bLoc[d] = 0));
const bIndex = bBuf.locToIndex(bLoc);
resVals[i] = op(aVals[aIndex], bVals[bIndex]);
}
}
return result.toTensor();
}
broadcastedBinaryComplexOp(a, b, op) {
const newShape = dist["backend_util"].assertAndGetBroadcastShape(a.shape, b.shape);
const realResult = dist["buffer"](newShape, "float32");
const imagResult = dist["buffer"](newShape, "float32");
const aVals = this.readSync(a.dataId);
const bVals = this.readSync(b.dataId);
const aBroadcastDims = dist["backend_util"].getBroadcastDims(a.shape, newShape);
const bBroadcastDims = dist["backend_util"].getBroadcastDims(b.shape, newShape);
const realVals = realResult.values;
const imagVals = imagResult.values;
if (aBroadcastDims.length + bBroadcastDims.length === 0) {
for (let i = 0; i < realVals.length; i++) {
const aIdx = i % aVals.length;
const bIdx = i % bVals.length;
const result = op(
aVals[aIdx * 2],
aVals[aIdx * 2 + 1],
bVals[bIdx * 2],
bVals[bIdx * 2 + 1]
);
realVals[i] = result.real;
imagVals[i] = result.imag;
}
} else {
const aRealBuf = this.bufferSync(this.data.get(a.dataId).complexTensors.real);
const bRealBuf = this.bufferSync(this.data.get(b.dataId).complexTensors.real);
for (let i = 0; i < realVals.length; i++) {
const loc = realResult.indexToLoc(i);
const aLoc = loc.slice(-a.rank);
aBroadcastDims.forEach((d) => (aLoc[d] = 0));
const aIndex = aRealBuf.locToIndex(aLoc);
const bLoc = loc.slice(-b.rank);
bBroadcastDims.forEach((d) => (bLoc[d] = 0));
const bIndex = bRealBuf.locToIndex(bLoc);
const opResult = op(
aVals[aIndex * 2],
aVals[aIndex * 2 + 1],
bVals[bIndex * 2],
bVals[bIndex * 2 + 1]
);
realVals[i] = opResult.real;
imagVals[i] = opResult.imag;
}
}
return this.complex(realResult.toTensor(), imagResult.toTensor());
}
split(x, sizeSplits, axis) {
return split(x, sizeSplits, axis);
}
dispose() {}
floatPrecision() {
return 32;
}
/** Returns the smallest representable number. */
epsilon() {
return super.epsilon();
}
cropAndResize(images, boxes, boxIndex, cropSize, method, extrapolationValue) {
const [batch, imageHeight, imageWidth, numChannels] = images.shape;
const numBoxes = boxes.shape[0];
const [cropHeight, cropWidth] = cropSize;
const output = dist["buffer"]([numBoxes, cropHeight, cropWidth, numChannels], "float32");
const boxVals = this.readSync(boxes.dataId);
const boxIndVals = this.readSync(boxIndex.dataId);
const imageVals = this.readSync(images.dataId);
const inStride = images.strides; // to calculate flat indexes into image
const outStride = output.strides; // to calculate flat indexes into output
// Reference implementation
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/crop_and_resize_op.cc
for (let b = 0; b < numBoxes; b++) {
const startInd = b * 4;
const y1 = boxVals[startInd];
const x1 = boxVals[startInd + 1];
const y2 = boxVals[startInd + 2];
const x2 = boxVals[startInd + 3];
const bInd = boxIndVals[b];
if (bInd >= batch) {
continue;
}
const heightScale =
cropHeight > 1 ? ((y2 - y1) * (imageHeight - 1)) / (cropHeight - 1) : 0;
const widthScale = cropWidth > 1 ? ((x2 - x1) * (imageWidth - 1)) / (cropWidth - 1) : 0;
for (let y = 0; y < cropHeight; y++) {
const yInd =
cropHeight > 1
? y1 * (imageHeight - 1) + y * heightScale
: 0.5 * (y1 + y2) * (imageHeight - 1);
if (yInd < 0 || yInd > imageHeight - 1) {
for (let x = 0; x < cropWidth; x++) {
for (let c = 0; c < numChannels; c++) {
const ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
output.values[ind] = extrapolationValue;
}
}
continue;
}
if (method === "bilinear") {
const topInd = Math.floor(yInd);
const bottomInd = Math.ceil(yInd);
const yLerp = yInd - topInd;
for (let x = 0; x < cropWidth; x++) {
const xInd =
cropWidth > 1
? x1 * (imageWidth - 1) + x * widthScale
: 0.5 * (x1 + x2) * (imageWidth - 1);
if (xInd < 0 || xInd > imageWidth - 1) {
for (let c = 0; c < numChannels; c++) {
const ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
output.values[ind] = extrapolationValue;
}
continue;
}
const leftInd = Math.floor(xInd);
const rightInd = Math.ceil(xInd);
const xLerp = xInd - leftInd;
for (let c = 0; c < numChannels; c++) {
let ind = c + leftInd * inStride[2] + topInd * inStride[1] + bInd * inStride[0];
const topLeft = imageVals[ind];
ind = c + rightInd * inStride[2] + topInd * inStride[1] + bInd * inStride[0];
const topRight = imageVals[ind];
ind = c + leftInd * inStride[2] + bottomInd * inStride[1] + bInd * inStride[0];
const bottomLeft = imageVals[ind];
ind = c + rightInd * inStride[2] + bottomInd * inStride[1] + bInd * inStride[0];
const bottomRight = imageVals[ind];
const top = topLeft + (topRight - topLeft) * xLerp;
const bottom = bottomLeft + (bottomRight - bottomLeft) * xLerp;
ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
output.values[ind] = top + (bottom - top) * yLerp;
}
}
} else {
// method == "nearest"
for (let x = 0; x < cropWidth; ++x) {
const xInd =
cropWidth > 1
? x1 * (imageWidth - 1) + x * widthScale
: 0.5 * (x1 + x2) * (imageWidth - 1);
if (xInd < 0 || xInd > imageWidth - 1) {
for (let c = 0; c < numChannels; c++) {
const ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
output.values[ind] = extrapolationValue;
}
continue;
}
const closestX = Math.round(xInd);
const closestY = Math.round(yInd);
for (let c = 0; c < numChannels; c++) {
const inInd =
c + closestX * inStride[2] + closestY * inStride[1] + bInd * inStride[0];
const outInd = c + x * outStride[2] + y * outStride[1] + b * outStride[0];
output.values[outInd] = imageVals[inInd];
}
}
}
}
}
return output.toTensor();
}
sparseToDense(sparseIndices, sparseValues, outputShape, defaultValue) {
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = dist[
"backend_util"
].calculateShapes(sparseValues, sparseIndices, outputShape);
const sumDupeIndices = false;
return this.scatter(
sparseIndices,
sparseValues,
outputShape,
outputSize,
sliceSize,
numUpdates,
sliceRank,
strides,
defaultValue,
sumDupeIndices
);
}
gatherND(x, indices) {
const indicesShape = indices.shape;
const sliceRank = indicesShape[indicesShape.length - 1];
const [resultShape, numSlices, sliceSize, strides] = dist[
"backend_util"
].prepareAndValidate(x, indices);
if (numSlices === 0) {
return dist["tensor"]([], resultShape, x.dtype);
}
const buffer = new dist["TensorBuffer"]([numSlices, sliceSize], x.dtype);
const indicesData = this.readSync(indices.dataId);
const xData = this.readSync(x.dataId);
for (let i = 0; i < numSlices; i++) {
const index = [];
let flattenIndex = 0;
for (let j = 0; j < sliceRank; j++) {
const dim = indicesData[i * sliceRank + j];
flattenIndex += dim * strides[j];
index.push(dim);
}
if (flattenIndex < 0 || flattenIndex >= x.size / sliceSize) {
throw new Error(`Invalid indices: ${index} does not index into ${x.shape}`);
}
for (let k = 0; k < sliceSize; k++) {
buffer.values[i * sliceSize + k] = xData[flattenIndex * sliceSize + k];
}
}
return buffer.toTensor().reshape(resultShape);
}
scatterND(indices, updates, shape) {
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = dist[
"backend_util"
].calculateShapes(updates, indices, shape);
const defaultValue = dist["scalar"](0);
const sumDupeIndices = true;
return this.scatter(
indices,
updates,
shape,
outputSize,
sliceSize,
numUpdates,
sliceRank,
strides,
defaultValue,
sumDupeIndices
);
}
fill(shape, value, dtype) {
dtype = dtype || dist["util"].inferDtype(value);
const values = dist["util"].getArrayFromDType(dtype, dist["util"].sizeFromShape(shape));
values.fill(value);
return Object(dist["engine"])().makeTensor(values, shape, dtype, this);
}
onesLike(x) {
if (x.dtype === "string") {
throw new Error("onesLike is not supported for string tensors");
} else {
return this.fill(x.shape, 1, x.dtype);
}
}
zerosLike(x) {
const values = dist["util"].getArrayFromDType(
x.dtype,
dist["util"].sizeFromShape(x.shape)
);
return this.makeOutput(values, x.shape, x.dtype);
}
linspace(start, stop, num) {
return dist["backend_util"].linspaceImpl(start, stop, num);
}
scatter(
indices,
updates,
shape,
outputSize,
sliceSize,
numUpdates,
sliceRank,
strides,
defaultValue,
sumDupeIndices
) {
const flattenShape = [outputSize / sliceSize, sliceSize];
const indicesData = this.readSync(indices.dataId);
const updatesData = this.readSync(updates.dataId);
if (outputSize === 0) {
return dist["tensor"]([], shape, updates.dtype);
}
const buffer = new dist["TensorBuffer"](flattenShape, updates.dtype);
buffer.values.fill(this.readSync(defaultValue.dataId)[0]);
for (let i = 0; i < numUpdates; i++) {
const index = [];
let flattenIndex = 0;
for (let j = 0; j < sliceRank; j++) {
const dim = indicesData[i * sliceRank + j];
index.push(dim);
flattenIndex += dim * strides[j];
}
if (flattenIndex < 0 || flattenIndex >= outputSize / sliceSize) {
throw new Error(`Invalid indices: ${index} does not index into ${shape}`);
}
for (let k = 0; k < sliceSize; k++) {
if (sumDupeIndices) {
buffer.values[flattenIndex * sliceSize + k] += updatesData[i * sliceSize + k];
} else {
buffer.values[flattenIndex * sliceSize + k] =
updates.rank === 0 ? updatesData[0] : updatesData[i * sliceSize + k];
}
}
}
return buffer.toTensor().reshape(shape);
}
}
//# sourceMappingURL=backend_cpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/version.js
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
const version = "2.0.1";
//# sourceMappingURL=version.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/base.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/*
* base.ts contains all the exports from tfjs-backend-cpu
* that do not trigger side effects.
*/
//# sourceMappingURL=base.js.map
/***/
},
/* 32 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (global) {
var require;
var require; /*!
localForage -- Offline Storage, Improved
Version 1.7.3
https://localforage.github.io/localForage
(c) 2013-2017 Mozilla, Apache License 2.0
*/
(function (f) {
if (true) {
module.exports = f();
} else {
var g;
}
})(function () {
var define, module, exports;
return (function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == "function" && require;
if (!u && a) return require(o, !0);
if (i) return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw ((f.code = "MODULE_NOT_FOUND"), f);
}
var l = (n[o] = { exports: {} });
t[o][0].call(
l.exports,
function (e) {
var n = t[o][1][e];
return s(n ? n : e);
},
l,
l.exports,
e,
t,
n,
r
);
}
return n[o].exports;
}
var i = typeof require == "function" && require;
for (var o = 0; o < r.length; o++) s(r[o]);
return s;
})(
{
1: [
function (_dereq_, module, exports) {
(function (global) {
"use strict";
var Mutation = global.MutationObserver || global.WebKitMutationObserver;
var scheduleDrain;
{
if (Mutation) {
var called = 0;
var observer = new Mutation(nextTick);
var element = global.document.createTextNode("");
observer.observe(element, {
characterData: true,
});
scheduleDrain = function () {
element.data = called = ++called % 2;
};
} else if (
!global.setImmediate &&
typeof global.MessageChannel !== "undefined"
) {
var channel = new global.MessageChannel();
channel.port1.onmessage = nextTick;
scheduleDrain = function () {
channel.port2.postMessage(0);
};
} else if (
"document" in global &&
"onreadystatechange" in global.document.createElement("script")
) {
scheduleDrain = function () {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = global.document.createElement("script");
scriptEl.onreadystatechange = function () {
nextTick();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
};
} else {
scheduleDrain = function () {
setTimeout(nextTick, 0);
};
}
}
var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
draining = true;
var i, oldQueue;
var len = queue.length;
while (len) {
oldQueue = queue;
queue = [];
i = -1;
while (++i < len) {
oldQueue[i]();
}
len = queue.length;
}
draining = false;
}
module.exports = immediate;
function immediate(task) {
if (queue.push(task) === 1 && !draining) {
scheduleDrain();
}
}
}.call(
this,
typeof global !== "undefined"
? global
: typeof self !== "undefined"
? self
: typeof window !== "undefined"
? window
: {}
));
},
{},
],
2: [
function (_dereq_, module, exports) {
"use strict";
var immediate = _dereq_(1);
/* istanbul ignore next */
function INTERNAL() {}
var handlers = {};
var REJECTED = ["REJECTED"];
var FULFILLED = ["FULFILLED"];
var PENDING = ["PENDING"];
module.exports = Promise;
function Promise(resolver) {
if (typeof resolver !== "function") {
throw new TypeError("resolver must be a function");
}
this.state = PENDING;
this.queue = [];
this.outcome = void 0;
if (resolver !== INTERNAL) {
safelyResolveThenable(this, resolver);
}
}
Promise.prototype["catch"] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
if (
(typeof onFulfilled !== "function" && this.state === FULFILLED) ||
(typeof onRejected !== "function" && this.state === REJECTED)
) {
return this;
}
var promise = new this.constructor(INTERNAL);
if (this.state !== PENDING) {
var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
unwrap(promise, resolver, this.outcome);
} else {
this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
}
return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
this.promise = promise;
if (typeof onFulfilled === "function") {
this.onFulfilled = onFulfilled;
this.callFulfilled = this.otherCallFulfilled;
}
if (typeof onRejected === "function") {
this.onRejected = onRejected;
this.callRejected = this.otherCallRejected;
}
}
QueueItem.prototype.callFulfilled = function (value) {
handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
immediate(function () {
var returnValue;
try {
returnValue = func(value);
} catch (e) {
return handlers.reject(promise, e);
}
if (returnValue === promise) {
handlers.reject(
promise,
new TypeError("Cannot resolve promise with itself")
);
} else {
handlers.resolve(promise, returnValue);
}
});
}
handlers.resolve = function (self, value) {
var result = tryCatch(getThen, value);
if (result.status === "error") {
return handlers.reject(self, result.value);
}
var thenable = result.value;
if (thenable) {
safelyResolveThenable(self, thenable);
} else {
self.state = FULFILLED;
self.outcome = value;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callFulfilled(value);
}
}
return self;
};
handlers.reject = function (self, error) {
self.state = REJECTED;
self.outcome = error;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callRejected(error);
}
return self;
};
function getThen(obj) {
// Make sure we only access the accessor once as required by the spec
var then = obj && obj.then;
if (
obj &&
(typeof obj === "object" || typeof obj === "function") &&
typeof then === "function"
) {
return function appyThen() {
then.apply(obj, arguments);
};
}
}
function safelyResolveThenable(self, thenable) {
// Either fulfill, reject or reject with error
var called = false;
function onError(value) {
if (called) {
return;
}
called = true;
handlers.reject(self, value);
}
function onSuccess(value) {
if (called) {
return;
}
called = true;
handlers.resolve(self, value);
}
function tryToUnwrap() {
thenable(onSuccess, onError);
}
var result = tryCatch(tryToUnwrap);
if (result.status === "error") {
onError(result.value);
}
}
function tryCatch(func, value) {
var out = {};
try {
out.value = func(value);
out.status = "success";
} catch (e) {
out.status = "error";
out.value = e;
}
return out;
}
Promise.resolve = resolve;
function resolve(value) {
if (value instanceof this) {
return value;
}
return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
var promise = new this(INTERNAL);
return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== "[object Array]") {
return this.reject(new TypeError("must be an array"));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var values = new Array(len);
var resolved = 0;
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
allResolver(iterable[i], i);
}
return promise;
function allResolver(value, i) {
self.resolve(value).then(resolveFromAll, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
function resolveFromAll(outValue) {
values[i] = outValue;
if (++resolved === len && !called) {
called = true;
handlers.resolve(promise, values);
}
}
}
}
Promise.race = race;
function race(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== "[object Array]") {
return this.reject(new TypeError("must be an array"));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
resolver(iterable[i]);
}
return promise;
function resolver(value) {
self.resolve(value).then(
function (response) {
if (!called) {
called = true;
handlers.resolve(promise, response);
}
},
function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
}
);
}
}
},
{ 1: 1 },
],
3: [
function (_dereq_, module, exports) {
(function (global) {
"use strict";
if (typeof global.Promise !== "function") {
global.Promise = _dereq_(2);
}
}.call(
this,
typeof global !== "undefined"
? global
: typeof self !== "undefined"
? self
: typeof window !== "undefined"
? window
: {}
));
},
{ 2: 2 },
],
4: [
function (_dereq_, module, exports) {
"use strict";
var _typeof =
typeof Symbol === "function" && typeof Symbol.iterator === "symbol"
? function (obj) {
return typeof obj;
}
: function (obj) {
return obj &&
typeof Symbol === "function" &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? "symbol"
: typeof obj;
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function getIDB() {
/* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
try {
if (typeof indexedDB !== "undefined") {
return indexedDB;
}
if (typeof webkitIndexedDB !== "undefined") {
return webkitIndexedDB;
}
if (typeof mozIndexedDB !== "undefined") {
return mozIndexedDB;
}
if (typeof OIndexedDB !== "undefined") {
return OIndexedDB;
}
if (typeof msIndexedDB !== "undefined") {
return msIndexedDB;
}
} catch (e) {
return;
}
}
var idb = getIDB();
function isIndexedDBValid() {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
if (!idb) {
return false;
}
// We mimic PouchDB here;
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
var isSafari =
typeof openDatabase !== "undefined" &&
/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) &&
!/Chrome/.test(navigator.userAgent) &&
!/BlackBerry/.test(navigator.platform);
var hasFetch =
typeof fetch === "function" &&
fetch.toString().indexOf("[native code") !== -1;
// Safari <10.1 does not meet our requirements for IDB support (#5572)
// since Safari 10.1 shipped with fetch, we can use that to detect it
return (
(!isSafari || hasFetch) &&
typeof indexedDB !== "undefined" &&
// some outdated implementations of IDB that appear on Samsung
// and HTC Android devices <4.4 are missing IDBKeyRange
// See: https://github.com/mozilla/localForage/issues/128
// See: https://github.com/mozilla/localForage/issues/272
typeof IDBKeyRange !== "undefined"
);
} catch (e) {
return false;
}
}
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function createBlob(parts, properties) {
/* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== "TypeError") {
throw e;
}
var Builder =
typeof BlobBuilder !== "undefined"
? BlobBuilder
: typeof MSBlobBuilder !== "undefined"
? MSBlobBuilder
: typeof MozBlobBuilder !== "undefined"
? MozBlobBuilder
: WebKitBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// This is CommonJS because lie is an external dependency, so Rollup
// can just ignore it.
if (typeof Promise === "undefined") {
// In the "nopromises" build this will just throw if you don't have
// a global promise object, but it would throw anyway later.
_dereq_(3);
}
var Promise$1 = Promise;
function executeCallback(promise, callback) {
if (callback) {
promise.then(
function (result) {
callback(null, result);
},
function (error) {
callback(error);
}
);
}
}
function executeTwoCallbacks(promise, callback, errorCallback) {
if (typeof callback === "function") {
promise.then(callback);
}
if (typeof errorCallback === "function") {
promise["catch"](errorCallback);
}
}
function normalizeKey(key) {
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== "string") {
console.warn(key + " used as a key, but it is not a string.");
key = String(key);
}
return key;
}
function getCallback() {
if (arguments.length && typeof arguments[arguments.length - 1] === "function") {
return arguments[arguments.length - 1];
}
}
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support";
var supportsBlobs = void 0;
var dbContexts = {};
var toString = Object.prototype.toString;
// Transaction Modes
var READ_ONLY = "readonly";
var READ_WRITE = "readwrite";
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
//
// Blobs are not supported in all versions of IndexedDB, notably
// Chrome <37 and Android <5. In those versions, storing a blob will throw.
//
// Various other blob bugs exist in Chrome v37-42 (inclusive).
// Detecting them is expensive and confusing to users, and Chrome 37-42
// is at very low usage worldwide, so we do a hacky userAgent check instead.
//
// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
// Code borrowed from PouchDB. See:
// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise$1(function (resolve) {
var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
var blob = createBlob([""]);
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key");
txn.onabort = function (e) {
// If the transaction aborts now its due to not being able to
// write to the database, likely due to the disk being full
e.preventDefault();
e.stopPropagation();
resolve(false);
};
txn.oncomplete = function () {
var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
var matchedEdge = navigator.userAgent.match(/Edge\//);
// MS Edge pretends to be Chrome 42:
// https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
resolve(
matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43
);
};
})["catch"](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === "boolean") {
return Promise$1.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new Promise$1(function (resolve, reject) {
deferredOperation.resolve = resolve;
deferredOperation.reject = reject;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
return deferredOperation.promise;
}
}
function _rejectReadiness(dbInfo, err) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Reject its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.reject(err);
return deferredOperation.promise;
}
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise$1(function (resolve, reject) {
dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
if (dbInfo.db) {
if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = idb.open.apply(idb, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === "ConstraintError") {
console.warn(
'The database "' +
dbInfo.name +
'"' +
" has been upgraded from version " +
e.oldVersion +
" to version " +
e.newVersion +
', but the storage "' +
dbInfo.storeName +
'" already exists.'
);
} else {
throw ex;
}
}
};
}
openreq.onerror = function (e) {
e.preventDefault();
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
_advanceReadiness(dbInfo);
};
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
console.warn(
'The database "' +
dbInfo.name +
'"' +
" can't be downgraded from version " +
dbInfo.db.version +
" to version " +
dbInfo.version +
"."
);
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise$1(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || "");
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type,
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
executeTwoCallbacks(promise, callback, callback);
return promise;
}
// Try to establish a new db connection to replace the
// current one which is broken (i.e. experiencing
// InvalidStateError while creating a transaction).
function _tryReconnect(dbInfo) {
_deferReadiness(dbInfo);
var dbContext = dbContexts[dbInfo.name];
var forages = dbContext.forages;
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
if (forage._dbInfo.db) {
forage._dbInfo.db.close();
forage._dbInfo.db = null;
}
}
dbInfo.db = null;
return _getOriginalConnection(dbInfo)
.then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
})
.then(function (db) {
// store the latest db reference
// in case the db was upgraded
dbInfo.db = dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
})
["catch"](function (err) {
_rejectReadiness(dbInfo, err);
throw err;
});
}
// FF doesn't like Promises (micro-tasks) and IDDB store operations,
// so we have to do it with callbacks
function createTransaction(dbInfo, mode, callback, retries) {
if (retries === undefined) {
retries = 1;
}
try {
var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
callback(null, tx);
} catch (err) {
if (
retries > 0 &&
(!dbInfo.db ||
err.name === "InvalidStateError" ||
err.name === "NotFoundError")
) {
return Promise$1.resolve()
.then(function () {
if (
!dbInfo.db ||
(err.name === "NotFoundError" &&
!dbInfo.db.objectStoreNames.contains(dbInfo.storeName) &&
dbInfo.version <= dbInfo.db.version)
) {
// increase the db version, to create the new ObjectStore
if (dbInfo.db) {
dbInfo.version = dbInfo.db.version + 1;
}
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
})
.then(function () {
return _tryReconnect(dbInfo).then(function () {
createTransaction(dbInfo, mode, callback, retries - 1);
});
})
["catch"](callback);
}
callback(err);
}
}
function createDbContext() {
return {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: [],
};
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null,
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = createDbContext();
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise$1.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady()["catch"](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise$1.all(initPromises)
.then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
})
.then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
})
.then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
// when the iterator callback retuns any
// (non-`undefined`) value, then we stop
// the iteration immediately
if (result !== void 0) {
resolve(result);
} else {
cursor["continue"]();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
var dbInfo;
self
.ready()
.then(function () {
dbInfo = self._dbInfo;
if (toString.call(value) === "[object Blob]") {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
return _encodeBlob(value);
});
}
return value;
})
.then(function (value) {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `.delete()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store["delete"](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self
.ready()
.then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor["continue"]();
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = (typeof options !== "function" && options) || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject("Invalid arguments");
} else {
var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
var dbPromise = isCurrentDb
? Promise$1.resolve(self._dbInfo.db)
: _getOriginalConnection(options).then(function (db) {
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
return db;
});
if (!options.storeName) {
promise = dbPromise.then(function (db) {
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
}
var dropDBPromise = new Promise$1(function (resolve, reject) {
var req = idb.deleteDatabase(options.name);
req.onerror = req.onblocked = function (err) {
var db = req.result;
if (db) {
db.close();
}
reject(err);
};
req.onsuccess = function () {
var db = req.result;
if (db) {
db.close();
}
resolve(db);
};
});
return dropDBPromise
.then(function (db) {
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
var _forage = forages[i];
_advanceReadiness(_forage._dbInfo);
}
})
["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](
function () {}
);
throw err;
});
});
} else {
promise = dbPromise.then(function (db) {
if (!db.objectStoreNames.contains(options.storeName)) {
return;
}
var newVersion = db.version + 1;
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
forage._dbInfo.version = newVersion;
}
var dropObjectPromise = new Promise$1(function (resolve, reject) {
var req = idb.open(options.name, newVersion);
req.onerror = function (err) {
var db = req.result;
db.close();
reject(err);
};
req.onupgradeneeded = function () {
var db = req.result;
db.deleteObjectStore(options.storeName);
};
req.onsuccess = function () {
var db = req.result;
db.close();
resolve(db);
};
});
return dropObjectPromise
.then(function (db) {
dbContext.db = db;
for (var j = 0; j < forages.length; j++) {
var _forage2 = forages[j];
_forage2._dbInfo.db = db;
_advanceReadiness(_forage2._dbInfo);
}
})
["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](
function () {}
);
throw err;
});
});
}
}
executeCallback(promise, callback);
return promise;
}
var asyncStorage = {
_driver: "asyncStorage",
_initStorage: _initStorage,
_support: isIndexedDBValid(),
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys,
dropInstance: dropInstance,
};
function isWebSQLValid() {
return typeof openDatabase === "function";
}
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var BLOB_TYPE_PREFIX = "~~local_forage_type~";
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = "__lfsc__:";
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = "arbf";
var TYPE_BLOB = "blob";
var TYPE_INT8ARRAY = "si08";
var TYPE_UINT8ARRAY = "ui08";
var TYPE_UINT8CLAMPEDARRAY = "uic8";
var TYPE_INT16ARRAY = "si16";
var TYPE_INT32ARRAY = "si32";
var TYPE_UINT16ARRAY = "ur16";
var TYPE_UINT32ARRAY = "ui32";
var TYPE_FLOAT32ARRAY = "fl32";
var TYPE_FLOAT64ARRAY = "fl64";
var TYPE_SERIALIZED_MARKER_LENGTH =
SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var toString$1 = Object.prototype.toString;
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === "=") {
bufferLength--;
if (serializedString[serializedString.length - 2] === "=") {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = "";
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + "=";
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + "==";
}
return base64String;
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueType = "";
if (value) {
valueType = toString$1.call(value);
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (
value &&
(valueType === "[object ArrayBuffer]" ||
(value.buffer && toString$1.call(value.buffer) === "[object ArrayBuffer]"))
) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueType === "[object Int8Array]") {
marker += TYPE_INT8ARRAY;
} else if (valueType === "[object Uint8Array]") {
marker += TYPE_UINT8ARRAY;
} else if (valueType === "[object Uint8ClampedArray]") {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueType === "[object Int16Array]") {
marker += TYPE_INT16ARRAY;
} else if (valueType === "[object Uint16Array]") {
marker += TYPE_UINT16ARRAY;
} else if (valueType === "[object Int32Array]") {
marker += TYPE_INT32ARRAY;
} else if (valueType === "[object Uint32Array]") {
marker += TYPE_UINT32ARRAY;
} else if (valueType === "[object Float32Array]") {
marker += TYPE_FLOAT32ARRAY;
} else if (valueType === "[object Float64Array]") {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error("Failed to get type for BinaryArray"));
}
}
callback(marker + bufferToString(buffer));
} else if (valueType === "[object Blob]") {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + "~" + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(
SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH
);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error("Unkown type: " + type);
}
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString,
};
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
function createDbTable(t, dbInfo, callback, errorCallback) {
t.executeSql(
"CREATE TABLE IF NOT EXISTS " +
dbInfo.storeName +
" " +
"(id INTEGER PRIMARY KEY, key unique, value)",
[],
callback,
errorCallback
);
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage$1(options) {
var self = this;
var dbInfo = {
db: null,
};
if (options) {
for (var i in options) {
dbInfo[i] =
typeof options[i] !== "string" ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise$1(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(
dbInfo.name,
String(dbInfo.version),
dbInfo.description,
dbInfo.size
);
} catch (e) {
return reject(e);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
createDbTable(
t,
dbInfo,
function () {
self._dbInfo = dbInfo;
resolve();
},
function (t, error) {
reject(error);
}
);
}, reject);
});
dbInfo.serializer = localforageSerializer;
return dbInfoPromise;
}
function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
t.executeSql(
sqlStatement,
args,
callback,
function (t, error) {
if (error.code === error.SYNTAX_ERR) {
t.executeSql(
"SELECT name FROM sqlite_master " + "WHERE type='table' AND name = ?",
[dbInfo.storeName],
function (t, results) {
if (!results.rows.length) {
// if the table is missing (was deleted)
// re-create it table and retry
createDbTable(
t,
dbInfo,
function () {
t.executeSql(sqlStatement, args, callback, errorCallback);
},
errorCallback
);
} else {
errorCallback(t, error);
}
},
errorCallback
);
} else {
errorCallback(t, error);
}
},
errorCallback
);
}
function getItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(
t,
dbInfo,
"SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1",
[key],
function (t, results) {
var result = results.rows.length
? results.rows.item(0).value
: null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
},
function (t, error) {
reject(error);
}
);
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate$1(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(
t,
dbInfo,
"SELECT * FROM " + dbInfo.storeName,
[],
function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
},
function (t, error) {
reject(error);
}
);
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function _setItem(key, value, callback, retriesLeft) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(
function (t) {
tryExecuteSql(
t,
dbInfo,
"INSERT OR REPLACE INTO " +
dbInfo.storeName +
" " +
"(key, value) VALUES (?, ?)",
[key, value],
function () {
resolve(originalValue);
},
function (t, error) {
reject(error);
}
);
},
function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// Try to re-run the transaction.
if (retriesLeft > 0) {
resolve(
_setItem.apply(self, [
key,
originalValue,
callback,
retriesLeft - 1,
])
);
return;
}
reject(sqlError);
}
}
);
}
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem$1(key, value, callback) {
return _setItem.apply(this, [key, value, callback, 1]);
}
function removeItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(
t,
dbInfo,
"DELETE FROM " + dbInfo.storeName + " WHERE key = ?",
[key],
function () {
resolve();
},
function (t, error) {
reject(error);
}
);
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(
t,
dbInfo,
"DELETE FROM " + dbInfo.storeName,
[],
function () {
resolve();
},
function (t, error) {
reject(error);
}
);
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
tryExecuteSql(
t,
dbInfo,
"SELECT COUNT(key) as c FROM " + dbInfo.storeName,
[],
function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
},
function (t, error) {
reject(error);
}
);
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key$1(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(
t,
dbInfo,
"SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1",
[n + 1],
function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
},
function (t, error) {
reject(error);
}
);
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self
.ready()
.then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(
t,
dbInfo,
"SELECT key FROM " + dbInfo.storeName,
[],
function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
},
function (t, error) {
reject(error);
}
);
});
})
["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// https://www.w3.org/TR/webdatabase/#databases
// > There is no way to enumerate or delete the databases available for an origin from this API.
function getAllStoreNames(db) {
return new Promise$1(function (resolve, reject) {
db.transaction(
function (t) {
t.executeSql(
"SELECT name FROM sqlite_master " +
"WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",
[],
function (t, results) {
var storeNames = [];
for (var i = 0; i < results.rows.length; i++) {
storeNames.push(results.rows.item(i).name);
}
resolve({
db: db,
storeNames: storeNames,
});
},
function (t, error) {
reject(error);
}
);
},
function (sqlError) {
reject(sqlError);
}
);
});
}
function dropInstance$1(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = (typeof options !== "function" && options) || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject("Invalid arguments");
} else {
promise = new Promise$1(function (resolve) {
var db;
if (options.name === currentConfig.name) {
// use the db reference of the current instance
db = self._dbInfo.db;
} else {
db = openDatabase(options.name, "", "", 0);
}
if (!options.storeName) {
// drop all database tables
resolve(getAllStoreNames(db));
} else {
resolve({
db: db,
storeNames: [options.storeName],
});
}
}).then(function (operationInfo) {
return new Promise$1(function (resolve, reject) {
operationInfo.db.transaction(
function (t) {
function dropTable(storeName) {
return new Promise$1(function (resolve, reject) {
t.executeSql(
"DROP TABLE IF EXISTS " + storeName,
[],
function () {
resolve();
},
function (t, error) {
reject(error);
}
);
});
}
var operations = [];
for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
operations.push(dropTable(operationInfo.storeNames[i]));
}
Promise$1.all(operations)
.then(function () {
resolve();
})
["catch"](function (e) {
reject(e);
});
},
function (sqlError) {
reject(sqlError);
}
);
});
});
}
executeCallback(promise, callback);
return promise;
}
var webSQLStorage = {
_driver: "webSQLStorage",
_initStorage: _initStorage$1,
_support: isWebSQLValid(),
iterate: iterate$1,
getItem: getItem$1,
setItem: setItem$1,
removeItem: removeItem$1,
clear: clear$1,
length: length$1,
key: key$1,
keys: keys$1,
dropInstance: dropInstance$1,
};
function isLocalStorageValid() {
try {
return (
typeof localStorage !== "undefined" &&
"setItem" in localStorage &&
// in IE8 typeof localStorage.setItem === 'object'
!!localStorage.setItem
);
} catch (e) {
return false;
}
}
function _getKeyPrefix(options, defaultConfig) {
var keyPrefix = options.name + "/";
if (options.storeName !== defaultConfig.storeName) {
keyPrefix += options.storeName + "/";
}
return keyPrefix;
}
// Check if localStorage throws when saving an item
function checkIfLocalStorageThrows() {
var localStorageTestKey = "_localforage_support_test";
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
}
// Check if localStorage is usable and allows to save an item
// This method checks if localStorage is usable in Safari Private Browsing
// mode, or in any other case where the available quota for localStorage
// is 0 and there wasn't any saved items yet.
function _isLocalStorageUsable() {
return !checkIfLocalStorageThrows() || localStorage.length > 0;
}
// Config the localStorage backend, using options set in the config.
function _initStorage$2(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
if (!_isLocalStorageUsable()) {
return Promise$1.reject();
}
self._dbInfo = dbInfo;
dbInfo.serializer = localforageSerializer;
return Promise$1.resolve();
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate$2(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key$2(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
var itemKey = localStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length$2(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem$2(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise$1(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (
e.name === "QuotaExceededError" ||
e.name === "NS_ERROR_DOM_QUOTA_REACHED"
) {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function dropInstance$2(options, callback) {
callback = getCallback.apply(this, arguments);
options = (typeof options !== "function" && options) || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject("Invalid arguments");
} else {
promise = new Promise$1(function (resolve) {
if (!options.storeName) {
resolve(options.name + "/");
} else {
resolve(_getKeyPrefix(options, self._defaultConfig));
}
}).then(function (keyPrefix) {
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
}
executeCallback(promise, callback);
return promise;
}
var localStorageWrapper = {
_driver: "localStorageWrapper",
_initStorage: _initStorage$2,
_support: isLocalStorageValid(),
iterate: iterate$2,
getItem: getItem$2,
setItem: setItem$2,
removeItem: removeItem$2,
clear: clear$2,
length: length$2,
key: key$2,
keys: keys$2,
dropInstance: dropInstance$2,
};
var sameValue = function sameValue(x, y) {
return (
x === y ||
(typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y))
);
};
var includes = function includes(array, searchElement) {
var len = array.length;
var i = 0;
while (i < len) {
if (sameValue(array[i], searchElement)) {
return true;
}
i++;
}
return false;
};
var isArray =
Array.isArray ||
function (arg) {
return Object.prototype.toString.call(arg) === "[object Array]";
};
// Drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var DefinedDrivers = {};
var DriverSupport = {};
var DefaultDrivers = {
INDEXEDDB: asyncStorage,
WEBSQL: webSQLStorage,
LOCALSTORAGE: localStorageWrapper,
};
var DefaultDriverOrder = [
DefaultDrivers.INDEXEDDB._driver,
DefaultDrivers.WEBSQL._driver,
DefaultDrivers.LOCALSTORAGE._driver,
];
var OptionalDriverMethods = ["dropInstance"];
var LibraryMethods = [
"clear",
"getItem",
"iterate",
"key",
"keys",
"length",
"removeItem",
"setItem",
].concat(OptionalDriverMethods);
var DefaultConfig = {
description: "",
driver: DefaultDriverOrder.slice(),
name: "localforage",
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: "keyvaluepairs",
version: 1.0,
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var _key in arg) {
if (arg.hasOwnProperty(_key)) {
if (isArray(arg[_key])) {
arguments[0][_key] = arg[_key].slice();
} else {
arguments[0][_key] = arg[_key];
}
}
}
}
}
return arguments[0];
}
var LocalForage = (function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
for (var driverTypeKey in DefaultDrivers) {
if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
var driver = DefaultDrivers[driverTypeKey];
var driverName = driver._driver;
this[driverTypeKey] = driverName;
if (!DefinedDrivers[driverName]) {
// we don't need to wait for the promise,
// since the default drivers can be defined
// in a blocking manner
this.defineDriver(driver);
}
}
}
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver)["catch"](function () {});
}
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (
(typeof options === "undefined" ? "undefined" : _typeof(options)) ===
"object"
) {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error(
"Can't call config() after localforage " + "has been used."
);
}
for (var i in options) {
if (i === "storeName") {
options[i] = options[i].replace(/\W/g, "_");
}
if (i === "version" && typeof options[i] !== "number") {
return new Error("Database version must be a number.");
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ("driver" in options && options.driver) {
return this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === "string") {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(
driverObject,
callback,
errorCallback
) {
var promise = new Promise$1(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error(
"Custom driver not compliant; see " +
"https://mozilla.github.io/localForage/#definedriver"
);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
var driverMethods = LibraryMethods.concat("_initStorage");
for (var i = 0, len = driverMethods.length; i < len; i++) {
var driverMethodName = driverMethods[i];
// when the property is there,
// it should be a method even when optional
var isRequired = !includes(OptionalDriverMethods, driverMethodName);
if (
(isRequired || driverObject[driverMethodName]) &&
typeof driverObject[driverMethodName] !== "function"
) {
reject(complianceError);
return;
}
}
var configureMissingMethods = function configureMissingMethods() {
var methodNotImplementedFactory = function methodNotImplementedFactory(
methodName
) {
return function () {
var error = new Error(
"Method " +
methodName +
" is not implemented by the current driver"
);
var promise = Promise$1.reject(error);
executeCallback(promise, arguments[arguments.length - 1]);
return promise;
};
};
for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
var optionalDriverMethod = OptionalDriverMethods[_i];
if (!driverObject[optionalDriverMethod]) {
driverObject[optionalDriverMethod] =
methodNotImplementedFactory(optionalDriverMethod);
}
}
};
configureMissingMethods();
var setDriverSupport = function setDriverSupport(support) {
if (DefinedDrivers[driverName]) {
console.info("Redefining LocalForage driver: " + driverName);
}
DefinedDrivers[driverName] = driverObject;
DriverSupport[driverName] = support;
// don't use a then, so that we can define
// drivers that have simple _support methods
// in a blocking manner
resolve();
};
if ("_support" in driverObject) {
if (
driverObject._support &&
typeof driverObject._support === "function"
) {
driverObject._support().then(setDriverSupport, reject);
} else {
setDriverSupport(!!driverObject._support);
}
} else {
setDriverSupport(true);
}
} catch (e) {
reject(e);
}
});
executeTwoCallbacks(promise, callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(
driverName,
callback,
errorCallback
) {
var getDriverPromise = DefinedDrivers[driverName]
? Promise$1.resolve(DefinedDrivers[driverName])
: Promise$1.reject(new Error("Driver not found."));
executeTwoCallbacks(getDriverPromise, callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = Promise$1.resolve(localforageSerializer);
executeTwoCallbacks(serializerPromise, callback);
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
executeTwoCallbacks(promise, callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(
drivers,
callback,
errorCallback
) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function extendSelfWithDriver(driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self
.getDriver(driverName)
.then(extendSelfWithDriver)
["catch"](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error("No available storage method found.");
self._driverSet = Promise$1.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone =
this._driverSet !== null
? this._driverSet["catch"](function () {
return Promise$1.resolve();
})
: Promise$1.resolve();
this._driverSet = oldDriverSetDone
.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})
["catch"](function () {
setDriverToConfig();
var error = new Error("No available storage method found.");
self._driverSet = Promise$1.reject(error);
return self._driverSet;
});
executeTwoCallbacks(this._driverSet, callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!DriverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(
drivers
) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady =
function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0, len = LibraryMethods.length; i < len; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
})();
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localforage_js = new LocalForage();
module.exports = localforage_js;
},
{ 3: 3 },
],
},
{},
[4]
)(4);
});
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(27)));
/***/
},
/* 33 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (global, process) {
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function () {
return getGlobalNamespace;
});
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return getGlobal;
});
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Note that the identifier globalNameSpace is scoped to this module, but will
// always resolve to the same global object regardless of how the module is
// resolved.
// tslint:disable-next-line:no-any
let globalNameSpace;
// tslint:disable-next-line:no-any
function getGlobalNamespace() {
if (globalNameSpace == null) {
// tslint:disable-next-line:no-any
let ns;
if (typeof window !== "undefined") {
ns = window;
} else if (typeof global !== "undefined") {
ns = global;
} else if (typeof process !== "undefined") {
ns = process;
} else if (typeof self !== "undefined") {
ns = self;
} else {
throw new Error("Could not find a global object");
}
globalNameSpace = ns;
}
return globalNameSpace;
}
// tslint:disable-next-line:no-any
function getGlobalMap() {
const ns = getGlobalNamespace();
if (ns._tfGlobals == null) {
ns._tfGlobals = new Map();
}
return ns._tfGlobals;
}
/**
* Returns a globally accessible 'singleton' object.
*
* @param key the name of the object
* @param init a function to initialize to initialize this object
* the first time it is fetched.
*/
function getGlobal(key, init) {
const globalMap = getGlobalMap();
if (globalMap.has(key)) {
return globalMap.get(key);
} else {
const singleton = init();
globalMap.set(key, singleton);
return globalMap.get(key);
}
}
//# sourceMappingURL=global_util.js.map
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(27), __webpack_require__(35)));
/***/
},
/* 34 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return DTYPE_VALUE_SIZE_MAP;
});
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/* Type definitions for exporting and importing of models. */
/**
* A map from Tensor dtype to number of bytes per element of the Tensor.
*/
const DTYPE_VALUE_SIZE_MAP = {
float32: 4,
float16: 2,
int32: 4,
uint16: 2,
uint8: 1,
bool: 1,
complex64: 8,
};
//# sourceMappingURL=types.js.map
/***/
},
/* 35 */
/***/ function (module, exports) {
// shim for using process in browser
var process = (module.exports = {});
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error("setTimeout has not been defined");
}
function defaultClearTimeout() {
throw new Error("clearTimeout has not been defined");
}
(function () {
try {
if (typeof setTimeout === "function") {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === "function") {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = "browser";
process.browser = true;
process.env = {};
process.argv = [];
process.version = ""; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) {
return [];
};
process.binding = function (name) {
throw new Error("process.binding is not supported");
};
process.cwd = function () {
return "/";
};
process.chdir = function (dir) {
throw new Error("process.chdir is not supported");
};
process.umask = function () {
return 0;
};
/***/
},
/* 36 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isMobile",
function () {
return isMobile;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"isBrowser",
function () {
return isBrowser;
}
);
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line:no-any
function _isNavigatorDefined() {
return typeof navigator !== "undefined" && navigator != null;
}
function isMobile() {
if (_isNavigatorDefined()) {
// tslint:disable-next-line:no-any
const a = navigator.userAgent || navigator.vendor || window.opera;
// tslint:disable-next-line:max-line-length
return (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
a
) ||
// tslint:disable-next-line:max-line-length
/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(
a.substr(0, 4)
)
);
}
return false;
}
function isBrowser() {
return (
(typeof window !== "undefined" && window.document != null) ||
//@ts-ignore
typeof WorkerGlobalScope !== "undefined"
);
}
//# sourceMappingURL=device_util.js.map
/***/
},
/* 37 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return maxImpl;
});
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(0);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function maxImpl(aVals, reduceSize, outShape, dtype) {
const vals = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[
"util"
].getTypedArrayFromDType(
dtype,
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(outShape)
);
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let max = aVals[offset];
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (value > max) {
max = value;
}
}
vals[i] = max;
}
return vals;
}
//# sourceMappingURL=Max_impl.js.map
/***/
},
/* 38 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "GraphModel", function () {
return /* reexport */ graph_model_GraphModel;
});
__webpack_require__.d(__webpack_exports__, "loadGraphModel", function () {
return /* reexport */ loadGraphModel;
});
__webpack_require__.d(__webpack_exports__, "deregisterOp", function () {
return /* reexport */ register["a" /* deregisterOp */];
});
__webpack_require__.d(__webpack_exports__, "registerOp", function () {
return /* reexport */ register["c" /* registerOp */];
});
__webpack_require__.d(__webpack_exports__, "version_converter", function () {
return /* reexport */ version;
});
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js + 269 modules
var dist = __webpack_require__(0);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/operation_mapper.js
var operation_mapper = __webpack_require__(15);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/utils.js
var utils = __webpack_require__(2);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/custom_op/node_value_impl.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.
* =============================================================================
*/
/**
* Helper class for lookup inputs and params for nodes in the model graph.
*/
class node_value_impl_NodeValueImpl {
constructor(node, tensorMap, context) {
this.node = node;
this.tensorMap = tensorMap;
this.context = context;
this.inputs = [];
this.attrs = {};
this.inputs = node.inputNames.map((name) => this.getInput(name));
if (node.rawAttrs != null) {
this.attrs = Object.keys(node.rawAttrs).reduce((attrs, key) => {
attrs[key] = this.getAttr(key);
return attrs;
}, {});
}
}
/**
* Return the value of the attribute or input param.
* @param name String: name of attribute or input param.
*/
getInput(name) {
return Object(utils["c" /* getTensor */])(name, this.tensorMap, this.context);
}
/**
* Return the value of the attribute or input param.
* @param name String: name of attribute or input param.
*/
getAttr(name, defaultValue) {
const value = this.node.rawAttrs[name];
if (value.tensor != null) {
return Object(utils["c" /* getTensor */])(name, this.tensorMap, this.context);
}
if (value.i != null || value.f != null) {
return Object(operation_mapper["f" /* getNumberParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.s != null) {
return Object(operation_mapper["i" /* getStringParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.b != null) {
return Object(operation_mapper["c" /* getBoolParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.shape != null) {
return Object(operation_mapper["k" /* getTensorShapeParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.type != null) {
return Object(operation_mapper["e" /* getDtypeParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.list != null) {
if (value.list.i != null || value.list.f != null) {
return Object(operation_mapper["g" /* getNumericArrayParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.list.s != null) {
return Object(operation_mapper["h" /* getStringArrayParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.list.shape != null) {
return Object(operation_mapper["j" /* getTensorShapeArrayParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.list.b != null) {
return Object(operation_mapper["b" /* getBoolArrayParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
if (value.list.type != null) {
return Object(operation_mapper["d" /* getDtypeArrayParam */])(
this.node.rawAttrs,
name,
defaultValue
);
}
}
return defaultValue;
}
}
//# sourceMappingURL=node_value_impl.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/custom_op/register.js
var register = __webpack_require__(24);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/arithmetic_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "BiasAdd":
case "AddV2":
case "Add": {
return [
dist["add"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "AddN": {
return [
dist["addN"](
Object(utils["b" /* getParamValue */])("tensors", node, tensorMap, context)
),
];
}
case "FloorMod":
case "Mod":
return [
dist["mod"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
case "Mul":
return [
dist["mul"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
case "RealDiv":
case "Div": {
return [
dist["div"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "DivNoNan": {
return [
dist["divNoNan"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "FloorDiv": {
return [
dist["floorDiv"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "Sub": {
return [
dist["sub"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "Minimum": {
return [
dist["minimum"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "Maximum": {
return [
dist["maximum"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "Pow": {
return [
dist["pow"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "SquaredDifference": {
return [
dist["squaredDifference"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const CATEGORY = "arithmetic";
//# sourceMappingURL=arithmetic_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/basic_math_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const basic_math_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "Abs":
case "ComplexAbs":
return [
dist["abs"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Acos":
return [
dist["acos"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Acosh":
return [
dist["acosh"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Asin":
return [
dist["asin"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Asinh":
return [
dist["asinh"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Atan":
return [
dist["atan"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Atan2":
return [
dist["atan2"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("y", node, tensorMap, context)
),
];
case "Atanh":
return [
dist["atanh"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Ceil":
return [
dist["ceil"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Complex":
return [
dist["complex"](
Object(utils["b" /* getParamValue */])("real", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("imag", node, tensorMap, context)
),
];
case "Cos":
return [
dist["cos"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Cosh":
return [
dist["cosh"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Elu":
return [
dist["elu"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Erf":
return [
dist["erf"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Exp":
return [
dist["exp"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Expm1": {
return [
dist["expm1"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "Floor":
return [
dist["floor"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Log":
return [
dist["log"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Log1p": {
return [
dist["log1p"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "Imag":
return [
dist["imag"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Neg":
return [
dist["neg"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Reciprocal": {
return [
dist["reciprocal"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)
),
];
}
case "Real":
return [
dist["real"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Relu":
return [
dist["relu"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Round": {
return [
dist["round"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "Selu":
return [
dist["selu"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Sigmoid":
return [
dist["sigmoid"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)
),
];
case "Sin":
return [
dist["sin"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Sign": {
return [
dist["sign"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "Sinh": {
return [
dist["sinh"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "Softplus": {
return [
dist["softplus"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)
),
];
}
case "Sqrt": {
return [
dist["sqrt"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "Square": {
return [
dist["square"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "Tanh": {
return [
dist["tanh"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "Tan":
return [
dist["tan"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
case "Relu6":
case "ClipByValue":
return [
dist["clipByValue"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("clipValueMin", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("clipValueMax", node, tensorMap, context)
),
];
case "Rsqrt":
return [
dist["rsqrt"](
Object(utils["c" /* getTensor */])(node.inputNames[0], tensorMap, context)
),
];
case "Prod":
return [
dist["prod"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("axes", node, tensorMap, context)
),
];
case "LeakyRelu":
return [
dist["leakyRelu"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("alpha", node, tensorMap, context)
),
];
case "Prelu":
return [
dist["prelu"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("alpha", node, tensorMap, context)
),
];
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const basic_math_executor_CATEGORY = "basic_math";
//# sourceMappingURL=basic_math_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/tensor_utils.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* This differs from util.assertShapesMatch in that it allows values of
* negative one, an undefined size of a dimensinon, in a shape to match
* anything.
*/
function assertShapesMatchAllowUndefinedSize(shapeA, shapeB, errorMessagePrefix = "") {
dist["util"].assert(
shapesEqualAllowUndefinedSize(shapeA, shapeB),
() => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`
);
}
function shapesEqualAllowUndefinedSize(n1, n2) {
if (n1.length !== n2.length) {
return false;
}
for (let i = 0; i < n1.length; i++) {
if (n1[i] !== -1 && n2[i] !== -1 && n1[i] !== n2[i]) {
return false;
}
}
return true;
}
//# sourceMappingURL=tensor_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/tensor_array.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* The TensorArray object keeps an array of Tensors. It
* allows reading from the array and writing to the array.
*/
class tensor_array_TensorArray {
constructor(
name,
dtype,
maxSize,
elementShape,
identicalElementShapes,
dynamicSize,
clearAfterRead
) {
this.name = name;
this.dtype = dtype;
this.maxSize = maxSize;
this.elementShape = elementShape;
this.identicalElementShapes = identicalElementShapes;
this.dynamicSize = dynamicSize;
this.clearAfterRead = clearAfterRead;
this.tensors = [];
this.closed_ = false;
this.id = tensor_array_TensorArray.nextId++;
}
get closed() {
return this.closed_;
}
/**
* Close the current TensorArray.
*/
clearAndClose() {
this.tensors.forEach((tensor) => tensor.tensor.dispose());
this.tensors = [];
this.closed_ = true;
}
size() {
return this.tensors.length;
}
/**
* Read the value at location index in the TensorArray.
* @param index Number the index to read from.
*/
read(index) {
if (this.closed_) {
throw new Error(`TensorArray ${this.name} has already been closed.`);
}
if (index < 0 || index >= this.size()) {
throw new Error(`Tried to read from index ${index}, but array size is: ${this.size()}`);
}
const tensorWithState = this.tensors[index];
if (tensorWithState.cleared) {
throw new Error(
`TensorArray ${this.name}: Could not read index ${index} twice because it was cleared after a previous read ` +
`(perhaps try setting clear_after_read = false?).`
);
}
if (this.clearAfterRead) {
tensorWithState.cleared = true;
}
tensorWithState.read = true;
return tensorWithState.tensor;
}
/**
* Helper method to read multiple tensors from the specified indices.
*/
readMany(indices) {
return indices.map((index) => this.read(index));
}
/**
* Write value into the index of the TensorArray.
* @param index number the index to write to.
* @param tensor
*/
write(index, tensor) {
if (this.closed_) {
throw new Error(`TensorArray ${this.name} has already been closed.`);
}
if (index < 0 || (!this.dynamicSize && index >= this.maxSize)) {
throw new Error(
`Tried to write to index ${index}, but array is not resizeable and size is: ${this.maxSize}`
);
}
const t = this.tensors[index] || {};
if (tensor.dtype !== this.dtype) {
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${index},
because the value dtype is ${tensor.dtype}, but TensorArray dtype is ${this.dtype}.`);
}
// Set the shape for the first time write to unknow shape tensor array
if (this.size() === 0 && (this.elementShape == null || this.elementShape.length === 0)) {
this.elementShape = tensor.shape;
}
assertShapesMatchAllowUndefinedSize(
this.elementShape,
tensor.shape,
`TensorArray ${this.name}: Could not write to TensorArray index ${index}.`
);
if (t && t.read) {
throw new Error(
`TensorArray ${this.name}: Could not write to TensorArray index ${index}, because it has already been read.`
);
}
if (t && t.written) {
throw new Error(
`TensorArray ${this.name}: Could not write to TensorArray index ${index}, because it has already been written.`
);
}
t.tensor = tensor;
t.written = true;
this.tensors[index] = t;
}
/**
* Helper method to write multiple tensors to the specified indices.
*/
writeMany(indices, tensors) {
if (indices.length !== tensors.length) {
throw new Error(
`TensorArray ${this.name}: could not write multiple tensors,` +
`because the index size: ${indices.length} is not the same as tensors size: ${tensors.length}.`
);
}
indices.forEach((i, index) => this.write(i, tensors[index]));
}
/**
* Return selected values in the TensorArray as a packed Tensor. All of
* selected values must have been written and their shapes must all match.
* @param [indices] number[] Optional. Taking values in [0, max_value). If the
* TensorArray is not dynamic, max_value=size(). If not specified returns
* all tensors in the original order.
* @param [dtype]
*/
gather(indices, dtype) {
if (!!dtype && dtype !== this.dtype) {
throw new Error(
`TensorArray dtype is ${this.dtype} but gather requested dtype ${dtype}`
);
}
if (!indices) {
indices = [];
for (let i = 0; i < this.size(); i++) {
indices.push(i);
}
} else {
indices = indices.slice(0, this.size());
}
if (indices.length === 0) {
return Object(dist["tensor"])([], [0].concat(this.elementShape));
}
// Read all the PersistentTensors into a vector to keep track of
// their memory.
const tensors = this.readMany(indices);
assertShapesMatchAllowUndefinedSize(
this.elementShape,
tensors[0].shape,
"TensorArray shape mismatch: "
);
return Object(dist["stack"])(tensors, 0);
}
/**
* Return the values in the TensorArray as a concatenated Tensor.
*/
concat(dtype) {
if (!!dtype && dtype !== this.dtype) {
throw new Error(
`TensorArray dtype is ${this.dtype} but concat requested dtype ${dtype}`
);
}
if (this.size() === 0) {
return Object(dist["tensor"])([], [0].concat(this.elementShape));
}
const indices = [];
for (let i = 0; i < this.size(); i++) {
indices.push(i);
}
// Collect all the tensors from the tensors array.
const tensors = this.readMany(indices);
assertShapesMatchAllowUndefinedSize(
this.elementShape,
tensors[0].shape,
`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${tensors[0].shape})`
);
return Object(dist["concat"])(tensors, 0);
}
/**
* Scatter the values of a Tensor in specific indices of a TensorArray.
* @param indices nummber[] values in [0, max_value). If the
* TensorArray is not dynamic, max_value=size().
* @param tensor Tensor input tensor.
*/
scatter(indices, tensor) {
if (tensor.dtype !== this.dtype) {
throw new Error(
`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor.dtype}`
);
}
if (indices.length !== tensor.shape[0]) {
throw new Error(
`Expected len(indices) == tensor.shape[0], but saw: ${indices.length} vs. ${tensor.shape[0]}`
);
}
const maxIndex = Math.max(...indices);
if (!this.dynamicSize && maxIndex >= this.maxSize) {
throw new Error(`Max index must be < array size (${maxIndex} vs. ${this.maxSize})`);
}
this.writeMany(indices, Object(dist["unstack"])(tensor, 0));
}
/**
* Split the values of a Tensor into the TensorArray.
* @param length number[] with the lengths to use when splitting value along
* its first dimension.
* @param tensor Tensor, the tensor to split.
*/
split(length, tensor) {
if (tensor.dtype !== this.dtype) {
throw new Error(
`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor.dtype}`
);
}
let totalLength = 0;
const cumulativeLengths = length.map((len) => {
totalLength += len;
return totalLength;
});
if (totalLength !== tensor.shape[0]) {
throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${totalLength}, and tensor's shape is: ${tensor.shape}`);
}
if (!this.dynamicSize && length.length !== this.maxSize) {
throw new Error(
`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${length.length}), ` +
"and the TensorArray is not marked as dynamically resizeable"
);
}
const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;
const tensors = [];
Object(dist["tidy"])(() => {
tensor = tensor.reshape([1, totalLength, elementPerRow]);
for (let i = 0; i < length.length; ++i) {
const previousLength = i === 0 ? 0 : cumulativeLengths[i - 1];
const indices = [0, previousLength, 0];
const sizes = [1, length[i], elementPerRow];
tensors[i] = Object(dist["slice"])(tensor, indices, sizes).reshape(this.elementShape);
}
return tensors;
});
const indices = [];
for (let i = 0; i < length.length; i++) {
indices[i] = i;
}
this.writeMany(indices, tensors);
}
}
tensor_array_TensorArray.nextId = 0;
//# sourceMappingURL=tensor_array.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/control_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const control_executor_executeOp = async (node, tensorMap, context) => {
switch (node.op) {
case "If":
case "StatelessIf": {
const thenFunc = Object(utils["b" /* getParamValue */])(
"thenBranch",
node,
tensorMap,
context
);
const elseFunc = Object(utils["b" /* getParamValue */])(
"elseBranch",
node,
tensorMap,
context
);
const cond = Object(utils["b" /* getParamValue */])("cond", node, tensorMap, context);
const args = Object(utils["b" /* getParamValue */])("args", node, tensorMap, context);
const condValue = await cond.data();
if (condValue[0]) {
return context.functionMap[thenFunc].executeFunctionAsync(args);
} else {
return context.functionMap[elseFunc].executeFunctionAsync(args);
}
}
case "While":
case "StatelessWhile": {
const bodyFunc = Object(utils["b" /* getParamValue */])(
"body",
node,
tensorMap,
context
);
const condFunc = Object(utils["b" /* getParamValue */])(
"cond",
node,
tensorMap,
context
);
const args = Object(utils["b" /* getParamValue */])("args", node, tensorMap, context);
const condTensor = (await context.functionMap[condFunc].executeFunctionAsync(args))[0];
let condValue = await condTensor.data();
let result = args;
while (condValue[0]) {
result = await context.functionMap[bodyFunc].executeFunctionAsync(result);
const condTensor = (
await context.functionMap[condFunc].executeFunctionAsync(result)
)[0];
condValue = await condTensor.data();
}
return result;
}
case "LoopCond":
return [
Object(utils["b" /* getParamValue */])("pred", node, tensorMap, context).clone(),
];
case "Switch": {
const pred = Object(utils["b" /* getParamValue */])("pred", node, tensorMap, context);
const data = Object(utils["b" /* getParamValue */])("data", node, tensorMap, context);
// Outputs nodes :0 => false, :1 => true
return (await pred.data())[0] ? [undefined, data.clone()] : [data.clone(), undefined];
}
case "Merge":
const inputName = node.inputNames.find(
(name) => Object(utils["c" /* getTensor */])(name, tensorMap, context) !== undefined
);
return inputName
? [Object(utils["c" /* getTensor */])(inputName, tensorMap, context).clone()]
: undefined;
case "Enter":
const frameId = Object(utils["b" /* getParamValue */])(
"frameName",
node,
tensorMap,
context
);
const data = Object(utils["b" /* getParamValue */])("tensor", node, tensorMap, context);
context.enterFrame(frameId);
return [data.clone()];
case "Exit":
const tensor = Object(utils["b" /* getParamValue */])(
"tensor",
node,
tensorMap,
context
);
context.exitFrame();
return [tensor.clone()];
case "NextIteration":
const input = Object(utils["b" /* getParamValue */])(
"tensor",
node,
tensorMap,
context
);
context.nextIteration();
return [input.clone()];
case "TensorArrayV3":
const size = Object(utils["b" /* getParamValue */])("size", node, tensorMap, context);
const dtype = Object(utils["b" /* getParamValue */])("dtype", node, tensorMap, context);
const elementShape = Object(utils["b" /* getParamValue */])(
"elementShape",
node,
tensorMap,
context
);
const dynamicSize = Object(utils["b" /* getParamValue */])(
"dynamicSize",
node,
tensorMap,
context
);
const clearAfterRead = Object(utils["b" /* getParamValue */])(
"clearAfterRead",
node,
tensorMap,
context
);
const identicalElementShapes = Object(utils["b" /* getParamValue */])(
"identicalElementShapes",
node,
tensorMap,
context
);
const name = Object(utils["b" /* getParamValue */])("name", node, tensorMap, context);
const tensorArray = new tensor_array_TensorArray(
name,
dtype,
size,
elementShape,
identicalElementShapes,
dynamicSize,
clearAfterRead
);
context.addTensorArray(tensorArray);
return [Object(dist["scalar"])(tensorArray.id), Object(dist["scalar"])(1.0)];
case "TensorArrayWriteV3":
const id = Object(utils["b" /* getParamValue */])(
"tensorArrayId",
node,
tensorMap,
context
);
const index = Object(utils["b" /* getParamValue */])("index", node, tensorMap, context);
const writeTensor = Object(utils["b" /* getParamValue */])(
"tensor",
node,
tensorMap,
context
);
const writeTensorArray = context.getTensorArray(id);
writeTensorArray.write(index, writeTensor);
return [Object(dist["scalar"])(1.0)];
case "TensorArrayReadV3":
const readId = Object(utils["b" /* getParamValue */])(
"tensorArrayId",
node,
tensorMap,
context
);
const readIndex = Object(utils["b" /* getParamValue */])(
"index",
node,
tensorMap,
context
);
const readTensorArray = context.getTensorArray(readId);
return [readTensorArray.read(readIndex)];
case "TensorArrayGatherV3":
const gatherId = Object(utils["b" /* getParamValue */])(
"tensorArrayId",
node,
tensorMap,
context
);
const gatherIndices = Object(utils["b" /* getParamValue */])(
"indices",
node,
tensorMap,
context
);
const gatherDtype = Object(utils["b" /* getParamValue */])(
"dtype",
node,
tensorMap,
context
);
const gatherTensorArray = context.getTensorArray(gatherId);
return [gatherTensorArray.gather(gatherIndices, gatherDtype)];
case "TensorArrayScatterV3":
const scatterId = Object(utils["b" /* getParamValue */])(
"tensorArrayId",
node,
tensorMap,
context
);
const scatterIndices = Object(utils["b" /* getParamValue */])(
"indices",
node,
tensorMap,
context
);
const scatterTensor = Object(utils["b" /* getParamValue */])(
"tensor",
node,
tensorMap,
context
);
const scatterTensorArray = context.getTensorArray(scatterId);
scatterTensorArray.scatter(scatterIndices, scatterTensor);
return [Object(dist["scalar"])(1.0)];
case "TensorArrayConcatV3":
const concatId = Object(utils["b" /* getParamValue */])(
"tensorArrayId",
node,
tensorMap,
context
);
const concatTensorArray = context.getTensorArray(concatId);
const concatDtype = Object(utils["b" /* getParamValue */])(
"dtype",
node,
tensorMap,
context
);
return [concatTensorArray.concat(concatDtype)];
case "TensorArraySplitV3":
const splitId = Object(utils["b" /* getParamValue */])(
"tensorArrayId",
node,
tensorMap,
context
);
const splitTensor = Object(utils["b" /* getParamValue */])(
"tensor",
node,
tensorMap,
context
);
const lengths = Object(utils["b" /* getParamValue */])(
"lengths",
node,
tensorMap,
context
);
const splitTensorArray = context.getTensorArray(splitId);
splitTensorArray.split(lengths, splitTensor);
return [Object(dist["scalar"])(1.0)];
case "TensorArraySizeV3":
const sizeId = Object(utils["b" /* getParamValue */])(
"tensorArrayId",
node,
tensorMap,
context
);
const sizeTensorArray = context.getTensorArray(sizeId);
return [Object(dist["scalar"])(sizeTensorArray.size(), "int32")];
case "TensorArrayCloseV3":
const closeId = Object(utils["b" /* getParamValue */])(
"tensorArrayId",
node,
tensorMap,
context
);
const closeTensorArray = context.getTensorArray(closeId);
closeTensorArray.clearAndClose();
return [Object(dist["scalar"])(0)];
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const control_executor_CATEGORY = "control";
//# sourceMappingURL=control_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/convolution_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const convolution_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "Conv1D": {
const stride = Object(utils["b" /* getParamValue */])(
"stride",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const dataFormat = Object(utils["b" /* getParamValue */])(
"dataFormat",
node,
tensorMap,
context
).toUpperCase();
const dilation = Object(utils["b" /* getParamValue */])(
"dilation",
node,
tensorMap,
context
);
return [
dist["conv1d"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("filter", node, tensorMap, context),
stride,
pad,
dataFormat,
dilation
),
];
}
case "Conv2D": {
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const dataFormat = Object(utils["b" /* getParamValue */])(
"dataFormat",
node,
tensorMap,
context
).toUpperCase();
const dilations = Object(utils["b" /* getParamValue */])(
"dilations",
node,
tensorMap,
context
);
return [
dist["conv2d"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("filter", node, tensorMap, context),
[stride[1], stride[2]],
pad,
dataFormat,
[dilations[1], dilations[2]]
),
];
}
case "_FusedConv2D":
case "FusedDepthwiseConv2dNative": {
const [extraOp, activationFunc] = Object(utils["b" /* getParamValue */])(
"fusedOps",
node,
tensorMap,
context
);
const isBiasAdd = extraOp === "biasadd";
const isPrelu = activationFunc === "prelu";
const isBatchNorm = extraOp === "fusedbatchnorm";
const numArgs = Object(utils["b" /* getParamValue */])(
"numArgs",
node,
tensorMap,
context
);
if (isBiasAdd) {
if (isPrelu && numArgs !== 2) {
throw new Error(
"FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu " +
"must have two extra arguments: bias and alpha."
);
}
if (!isPrelu && numArgs !== 1) {
throw new Error(
"FusedConv2d and DepthwiseConv2d with BiasAdd must have " +
"one extra argument: bias."
);
}
}
if (isBatchNorm) {
throw new Error(
"FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported."
);
}
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const dataFormat = Object(utils["b" /* getParamValue */])(
"dataFormat",
node,
tensorMap,
context
).toUpperCase();
const dilations = Object(utils["b" /* getParamValue */])(
"dilations",
node,
tensorMap,
context
);
const [biasArg, preluArg] = Object(utils["b" /* getParamValue */])(
"args",
node,
tensorMap,
context
);
const kernelMethod =
node.op === "_FusedConv2D" ? dist["fused"].conv2d : dist["fused"].depthwiseConv2d;
return [
kernelMethod({
x: Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
filter: Object(utils["b" /* getParamValue */])("filter", node, tensorMap, context),
strides: [stride[1], stride[2]],
pad: pad,
dataFormat: dataFormat,
dilations: [dilations[1], dilations[2]],
bias: biasArg,
activation: activationFunc,
preluActivationWeights: preluArg,
}),
];
}
case "Conv2DBackpropInput":
case "Conv2dTranspose": {
const shape = Object(utils["b" /* getParamValue */])(
"outputShape",
node,
tensorMap,
context
);
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
return [
dist["conv2dTranspose"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("filter", node, tensorMap, context),
shape,
[stride[1], stride[2]],
pad
),
];
}
case "DepthwiseConv2dNative":
case "DepthwiseConv2d": {
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const dilations = Object(utils["b" /* getParamValue */])(
"dilations",
node,
tensorMap,
context
);
const dataFormat = Object(utils["b" /* getParamValue */])(
"dataFormat",
node,
tensorMap,
context
).toUpperCase();
return [
dist["depthwiseConv2d"](
Object(utils["b" /* getParamValue */])("input", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("filter", node, tensorMap, context),
[stride[1], stride[2]],
pad,
dataFormat,
[dilations[1], dilations[2]]
),
];
}
case "Conv3D": {
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const dataFormat = Object(utils["b" /* getParamValue */])(
"dataFormat",
node,
tensorMap,
context
).toUpperCase();
const dilations = Object(utils["b" /* getParamValue */])(
"dilations",
node,
tensorMap,
context
);
return [
dist["conv3d"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("filter", node, tensorMap, context),
[stride[1], stride[2], stride[3]],
pad,
dataFormat,
[dilations[1], dilations[2], dilations[3]]
),
];
}
case "AvgPool": {
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const kernelSize = Object(utils["b" /* getParamValue */])(
"kernelSize",
node,
tensorMap,
context
);
return [
dist["avgPool"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
[kernelSize[1], kernelSize[2]],
[stride[1], stride[2]],
pad
),
];
}
case "MaxPool": {
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const kernelSize = Object(utils["b" /* getParamValue */])(
"kernelSize",
node,
tensorMap,
context
);
return [
dist["maxPool"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
[kernelSize[1], kernelSize[2]],
[stride[1], stride[2]],
pad
),
];
}
case "MaxPoolWithArgmax": {
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const kernelSize = Object(utils["b" /* getParamValue */])(
"kernelSize",
node,
tensorMap,
context
);
const includeBatchInIndex = Object(utils["b" /* getParamValue */])(
"includeBatchInIndex",
node,
tensorMap,
context
);
const { result, indexes } = dist["maxPoolWithArgmax"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
[kernelSize[1], kernelSize[2]],
[stride[1], stride[2]],
pad,
includeBatchInIndex
);
return [result, indexes];
}
case "AvgPool3D": {
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const kernelSize = Object(utils["b" /* getParamValue */])(
"kernelSize",
node,
tensorMap,
context
);
return [
dist["avgPool3d"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
[kernelSize[1], kernelSize[2], kernelSize[3]],
[stride[1], stride[2], stride[3]],
pad
),
];
}
case "MaxPool3D": {
const stride = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const pad = Object(utils["b" /* getParamValue */])("pad", node, tensorMap, context);
const kernelSize = Object(utils["b" /* getParamValue */])(
"kernelSize",
node,
tensorMap,
context
);
return [
dist["maxPool3d"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
[kernelSize[1], kernelSize[2], kernelSize[3]],
[stride[1], stride[2], stride[3]],
pad
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const convolution_executor_CATEGORY = "convolution";
//# sourceMappingURL=convolution_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/creation_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const creation_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "Fill": {
const shape = Object(utils["b" /* getParamValue */])("shape", node, tensorMap, context);
const dtype = Object(utils["b" /* getParamValue */])("dtype", node, tensorMap, context);
const value = Object(utils["b" /* getParamValue */])("value", node, tensorMap, context);
return [dist["fill"](shape, value, dtype)];
}
case "LinSpace": {
const start = Object(utils["b" /* getParamValue */])("start", node, tensorMap, context);
const stop = Object(utils["b" /* getParamValue */])("stop", node, tensorMap, context);
const num = Object(utils["b" /* getParamValue */])("num", node, tensorMap, context);
return [dist["linspace"](start, stop, num)];
}
case "Multinomial": {
const logits = Object(utils["b" /* getParamValue */])(
"logits",
node,
tensorMap,
context
);
const numSamples = Object(utils["b" /* getParamValue */])(
"numSamples",
node,
tensorMap,
context
);
const seed = Object(utils["b" /* getParamValue */])("seed", node, tensorMap, context);
return [dist["multinomial"](logits, numSamples, seed)];
}
case "OneHot": {
const indices = Object(utils["b" /* getParamValue */])(
"indices",
node,
tensorMap,
context
);
const depth = Object(utils["b" /* getParamValue */])("depth", node, tensorMap, context);
const onValue = Object(utils["b" /* getParamValue */])(
"onValue",
node,
tensorMap,
context
);
const offValue = Object(utils["b" /* getParamValue */])(
"offValue",
node,
tensorMap,
context
);
return [dist["oneHot"](indices, depth, onValue, offValue)];
}
case "Ones": {
return [
dist["ones"](
Object(utils["b" /* getParamValue */])("shape", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("dtype", node, tensorMap, context)
),
];
}
case "OnesLike": {
return [
dist["onesLike"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)
),
];
}
case "RandomUniform": {
return [
dist["randomUniform"](
// tslint:disable-next-line:no-any
Object(utils["b" /* getParamValue */])("shape", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("minval", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("maxval", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("dtype", node, tensorMap, context)
),
];
}
case "Range": {
const start = Object(utils["b" /* getParamValue */])("start", node, tensorMap, context);
const stop = Object(utils["b" /* getParamValue */])("stop", node, tensorMap, context);
const step = Object(utils["b" /* getParamValue */])("step", node, tensorMap, context);
return [
dist["range"](
start,
stop,
step,
Object(utils["b" /* getParamValue */])("dtype", node, tensorMap, context)
),
];
}
case "TruncatedNormal": {
const shape = Object(utils["b" /* getParamValue */])("shape", node, tensorMap, context);
const mean = Object(utils["b" /* getParamValue */])("mean", node, tensorMap, context);
const stdDev = Object(utils["b" /* getParamValue */])(
"stdDev",
node,
tensorMap,
context
);
const seed = Object(utils["b" /* getParamValue */])("seed", node, tensorMap, context);
return [
dist["truncatedNormal"](
shape,
mean,
stdDev,
Object(utils["b" /* getParamValue */])("dtype", node, tensorMap, context),
seed
),
];
}
case "Zeros": {
return [
dist["zeros"](
Object(utils["b" /* getParamValue */])("shape", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("dtype", node, tensorMap, context)
),
];
}
case "ZerosLike": {
return [
dist["zerosLike"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const creation_executor_CATEGORY = "creation";
//# sourceMappingURL=creation_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/dynamic_executor.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const dynamic_executor_executeOp = async (node, tensorMap, context) => {
switch (node.op) {
case "NonMaxSuppressionV5":
case "NonMaxSuppressionV3":
case "NonMaxSuppressionV2": {
const boxes = Object(utils["b" /* getParamValue */])("boxes", node, tensorMap, context);
const scores = Object(utils["b" /* getParamValue */])(
"scores",
node,
tensorMap,
context
);
const maxOutputSize = Object(utils["b" /* getParamValue */])(
"maxOutputSize",
node,
tensorMap,
context
);
const iouThreshold = Object(utils["b" /* getParamValue */])(
"iouThreshold",
node,
tensorMap,
context
);
const scoreThreshold = Object(utils["b" /* getParamValue */])(
"scoreThreshold",
node,
tensorMap,
context
);
if (node.op === "NonMaxSuppressionV5") {
const softNmsSigma = Object(utils["b" /* getParamValue */])(
"softNmsSigma",
node,
tensorMap,
context
);
const result = await dist["image"].nonMaxSuppressionWithScoreAsync(
boxes,
scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma
);
return [result.selectedIndices, result.selectedScores];
}
return [
await dist["image"].nonMaxSuppressionAsync(
boxes,
scores,
maxOutputSize,
iouThreshold,
scoreThreshold
),
];
}
case "Where": {
const condition = Object(utils["b" /* getParamValue */])(
"condition",
node,
tensorMap,
context
).asType("bool");
const result = [await dist["whereAsync"](condition)];
condition.dispose();
return result;
}
case "ListDiff": {
return dist["setdiff1dAsync"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("y", node, tensorMap, context)
);
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const dynamic_executor_CATEGORY = "dynamic";
//# sourceMappingURL=dynamic_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/evaluation_executor.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const evaluation_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "TopKV2": {
const x = Object(utils["b" /* getParamValue */])("x", node, tensorMap, context);
const k = Object(utils["b" /* getParamValue */])("k", node, tensorMap, context);
const sorted = Object(utils["b" /* getParamValue */])(
"sorted",
node,
tensorMap,
context
);
const result = dist["topk"](x, k, sorted);
return [result.values, result.indices];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const evaluation_executor_CATEGORY = "evaluation";
//# sourceMappingURL=evaluation_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/graph_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const graph_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "Const": {
return tensorMap[node.name];
}
case "PlaceholderWithDefault":
const def = Object(utils["b" /* getParamValue */])("default", node, tensorMap, context);
return [Object(utils["c" /* getTensor */])(node.name, tensorMap, context) || def];
case "Placeholder":
return [Object(utils["c" /* getTensor */])(node.name, tensorMap, context)];
case "Identity":
case "StopGradient":
case "FakeQuantWithMinMaxVars": // This op is currently ignored.
return [Object(utils["b" /* getParamValue */])("x", node, tensorMap, context).clone()];
case "IdentityN":
return Object(utils["b" /* getParamValue */])("x", node, tensorMap, context).map((t) =>
t.clone()
);
case "Snapshot":
const snapshot = Object(utils["b" /* getParamValue */])("x", node, tensorMap, context);
return [snapshot.clone()];
case "Shape":
return [
dist["tensor1d"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context).shape,
"int32"
),
];
case "ShapeN":
return Object(utils["b" /* getParamValue */])("x", node, tensorMap, context).map((t) =>
dist["tensor1d"](t.shape)
);
case "Size":
return [
dist["scalar"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context).size,
"int32"
),
];
case "Rank":
return [
dist["scalar"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context).rank,
"int32"
),
];
case "NoOp":
return [dist["scalar"](1)];
case "Print":
const input = Object(utils["b" /* getParamValue */])("x", node, tensorMap, context);
const data = Object(utils["b" /* getParamValue */])("data", node, tensorMap, context);
const message = Object(utils["b" /* getParamValue */])(
"message",
node,
tensorMap,
context
);
const summarize = Object(utils["b" /* getParamValue */])(
"summarize",
node,
tensorMap,
context
);
console.warn(
"The graph has a tf.print() operation," +
"usually used for debugging, which slows down performance."
);
console.log(message);
for (let i = 0; i < data.length; i++) {
console.log(Array.prototype.slice.call(data[i].dataSync()).slice(0, summarize));
}
return [input];
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const graph_executor_CATEGORY = "graph";
//# sourceMappingURL=graph_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/image_executor.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const image_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "ResizeBilinear": {
const images = Object(utils["b" /* getParamValue */])(
"images",
node,
tensorMap,
context
);
const size = Object(utils["b" /* getParamValue */])("size", node, tensorMap, context);
const alignCorners = Object(utils["b" /* getParamValue */])(
"alignCorners",
node,
tensorMap,
context
);
return [dist["image"].resizeBilinear(images, [size[0], size[1]], alignCorners)];
}
case "ResizeNearestNeighbor": {
const images = Object(utils["b" /* getParamValue */])(
"images",
node,
tensorMap,
context
);
const size = Object(utils["b" /* getParamValue */])("size", node, tensorMap, context);
const alignCorners = Object(utils["b" /* getParamValue */])(
"alignCorners",
node,
tensorMap,
context
);
return [dist["image"].resizeNearestNeighbor(images, [size[0], size[1]], alignCorners)];
}
case "CropAndResize": {
const image = Object(utils["b" /* getParamValue */])("image", node, tensorMap, context);
const boxes = Object(utils["b" /* getParamValue */])("boxes", node, tensorMap, context);
const boxInd = Object(utils["b" /* getParamValue */])(
"boxInd",
node,
tensorMap,
context
);
const cropSize = Object(utils["b" /* getParamValue */])(
"cropSize",
node,
tensorMap,
context
);
const method = Object(utils["b" /* getParamValue */])(
"method",
node,
tensorMap,
context
);
const extrapolationValue = Object(utils["b" /* getParamValue */])(
"extrapolationValue",
node,
tensorMap,
context
);
return [
dist["image"].cropAndResize(
image,
boxes,
boxInd,
cropSize,
method,
extrapolationValue
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const image_executor_CATEGORY = "image";
//# sourceMappingURL=image_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/logical_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const logical_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "Equal": {
return [
dist["equal"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "NotEqual": {
return [
dist["notEqual"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "Greater": {
return [
dist["greater"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "GreaterEqual": {
return [
dist["greaterEqual"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "Less": {
return [
dist["less"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "LessEqual": {
return [
dist["lessEqual"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "LogicalAnd": {
return [
dist["logicalAnd"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "LogicalNot": {
return [
dist["logicalNot"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context)
),
];
}
case "LogicalOr": {
return [
dist["logicalOr"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
case "Select":
case "SelectV2": {
return [
dist["where"](
Object(utils["b" /* getParamValue */])("condition", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context)
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const logical_executor_CATEGORY = "logical";
//# sourceMappingURL=logical_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/matrices_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const matrices_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "BatchMatMul":
case "BatchMatMulV2":
case "MatMul":
return [
dist["matMul"](
Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("b", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("transposeA", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("transposeB", node, tensorMap, context)
),
];
case "Transpose":
return [
dist["transpose"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("perm", node, tensorMap, context)
),
];
case "_FusedMatMul":
const [extraOp, activationFunc] = Object(utils["b" /* getParamValue */])(
"fusedOps",
node,
tensorMap,
context
);
const isBiasAdd = extraOp === "biasadd";
const isPrelu = activationFunc === "prelu";
const numArgs = Object(utils["b" /* getParamValue */])(
"numArgs",
node,
tensorMap,
context
);
if (isBiasAdd) {
if (isPrelu && numArgs !== 2) {
throw new Error(
"Fused MatMul with BiasAdd and Prelu must have two " +
"extra arguments: bias and alpha."
);
}
if (!isPrelu && numArgs !== 1) {
throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.");
}
}
const [biasArg, preluArg] = Object(utils["b" /* getParamValue */])(
"args",
node,
tensorMap,
context
);
return [
dist["fused"].matMul({
a: Object(utils["b" /* getParamValue */])("a", node, tensorMap, context),
b: Object(utils["b" /* getParamValue */])("b", node, tensorMap, context),
transposeA: Object(utils["b" /* getParamValue */])(
"transposeA",
node,
tensorMap,
context
),
transposeB: Object(utils["b" /* getParamValue */])(
"transposeB",
node,
tensorMap,
context
),
bias: biasArg,
activation: activationFunc,
preluActivationWeights: preluArg,
}),
];
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const matrices_executor_CATEGORY = "matrices";
//# sourceMappingURL=matrices_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/normalization_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const normalization_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "FusedBatchNorm":
case "FusedBatchNormV2": {
return [
dist["batchNorm"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("mean", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("variance", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("offset", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("scale", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("epsilon", node, tensorMap, context)
),
];
}
case "FusedBatchNormV3": {
return [
dist["batchNorm"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("mean", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("variance", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("offset", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("scale", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("epsilon", node, tensorMap, context)
),
];
}
case "LRN": {
return [
dist["localResponseNormalization"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("radius", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("bias", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("alpha", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("beta", node, tensorMap, context)
),
];
}
case "Softmax": {
return [
dist["softmax"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)
),
];
}
case "LogSoftmax": {
return [
dist["logSoftmax"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)
),
];
}
case "SparseToDense": {
return [
dist["sparseToDense"](
Object(utils["b" /* getParamValue */])("sparseIndices", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("outputShape", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("sparseValues", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("defaultValue", node, tensorMap, context)
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const normalization_executor_CATEGORY = "normalization";
//# sourceMappingURL=normalization_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/reduction_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const reduction_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "Max": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const keepDims = Object(utils["b" /* getParamValue */])(
"keepDims",
node,
tensorMap,
context
);
return [
dist["max"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis,
keepDims
),
];
}
case "Mean": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const keepDims = Object(utils["b" /* getParamValue */])(
"keepDims",
node,
tensorMap,
context
);
return [
dist["mean"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis,
keepDims
),
];
}
case "Min": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const keepDims = Object(utils["b" /* getParamValue */])(
"keepDims",
node,
tensorMap,
context
);
return [
dist["min"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis,
keepDims
),
];
}
case "Sum": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const keepDims = Object(utils["b" /* getParamValue */])(
"keepDims",
node,
tensorMap,
context
);
return [
dist["sum"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis,
keepDims
),
];
}
case "All": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const keepDims = Object(utils["b" /* getParamValue */])(
"keepDims",
node,
tensorMap,
context
);
return [
dist["all"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis,
keepDims
),
];
}
case "Any": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const keepDims = Object(utils["b" /* getParamValue */])(
"keepDims",
node,
tensorMap,
context
);
return [
dist["any"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis,
keepDims
),
];
}
case "ArgMax": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
return [
dist["argMax"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis
),
];
}
case "ArgMin": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
return [
dist["argMin"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis
),
];
}
case "Prod": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const keepDims = Object(utils["b" /* getParamValue */])(
"keepDims",
node,
tensorMap,
context
);
return [
dist["prod"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis,
keepDims
),
];
}
case "Cumsum": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const exclusive = Object(utils["b" /* getParamValue */])(
"exclusive",
node,
tensorMap,
context
);
const reverse = Object(utils["b" /* getParamValue */])(
"reverse",
node,
tensorMap,
context
);
return [
dist["cumsum"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis,
exclusive,
reverse
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const reduction_executor_CATEGORY = "reduction";
//# sourceMappingURL=reduction_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/slice_join_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const slice_join_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "ConcatV2":
case "Concat": {
const n = Object(utils["b" /* getParamValue */])("n", node, tensorMap, context);
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
let inputs = Object(utils["b" /* getParamValue */])(
"tensors",
node,
tensorMap,
context
);
inputs = inputs.slice(0, n);
return [dist["concat"](inputs, axis)];
}
case "GatherV2":
case "Gather": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const input = Object(utils["b" /* getParamValue */])("x", node, tensorMap, context);
const indices = Object(utils["b" /* getParamValue */])(
"indices",
node,
tensorMap,
context
);
return [dist["gather"](input, indices.asType("int32"), axis)];
}
case "ReverseV2":
case "Reverse": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const input = Object(utils["b" /* getParamValue */])("x", node, tensorMap, context);
return [dist["reverse"](input, axis)];
}
case "Slice": {
// tslint:disable-next-line:no-any
const begin = Object(utils["b" /* getParamValue */])("begin", node, tensorMap, context);
// tslint:disable-next-line:no-any
const size = Object(utils["b" /* getParamValue */])("size", node, tensorMap, context);
return [
dist["slice"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
begin,
size
),
];
}
case "StridedSlice": {
const begin = Object(utils["b" /* getParamValue */])("begin", node, tensorMap, context);
const end = Object(utils["b" /* getParamValue */])("end", node, tensorMap, context);
const strides = Object(utils["b" /* getParamValue */])(
"strides",
node,
tensorMap,
context
);
const beginMask = Object(utils["b" /* getParamValue */])(
"beginMask",
node,
tensorMap,
context
);
const endMask = Object(utils["b" /* getParamValue */])(
"endMask",
node,
tensorMap,
context
);
const ellipsisMask = Object(utils["b" /* getParamValue */])(
"ellipsisMask",
node,
tensorMap,
context
);
const newAxisMask = Object(utils["b" /* getParamValue */])(
"newAxisMask",
node,
tensorMap,
context
);
const shrinkAxisMask = Object(utils["b" /* getParamValue */])(
"shrinkAxisMask",
node,
tensorMap,
context
);
const tensor = Object(utils["b" /* getParamValue */])("x", node, tensorMap, context);
if (begin.length === 1 && tensor.shape.length > 1) {
for (let i = 1; i < tensor.shape.length; i++) {
begin.push(0);
end.push(tensor.shape[i]);
strides.push(strides[0]);
}
}
return [
dist["stridedSlice"](
tensor,
begin,
end,
strides,
beginMask,
endMask,
ellipsisMask,
newAxisMask,
shrinkAxisMask
),
];
}
case "Pack": {
return dist["tidy"](() => {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const tensors = Object(utils["b" /* getParamValue */])(
"tensors",
node,
tensorMap,
context
);
// Reshape the tensors to the first tensor's shape if they don't match.
const shape = tensors[0].shape;
const squeezedShape = tensors[0].squeeze().shape;
const mapped = tensors.map((tensor) => {
const sameShape = dist["util"].arraysEqual(tensor.shape, shape);
if (
!sameShape &&
!dist["util"].arraysEqual(tensor.squeeze().shape, squeezedShape)
) {
throw new Error("the input tensors shape does not match");
}
return sameShape ? tensor : tensor.reshape(shape);
});
return [dist["stack"](mapped, axis)];
});
}
case "Unpack": {
return dist["tidy"](() => {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const tensor = Object(utils["b" /* getParamValue */])(
"tensor",
node,
tensorMap,
context
);
return dist["unstack"](tensor, axis);
});
}
case "Tile": {
const reps = Object(utils["b" /* getParamValue */])("reps", node, tensorMap, context);
return [
dist["tile"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
reps
),
];
}
case "Split":
case "SplitV": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
const numOrSizeSplits = Object(utils["b" /* getParamValue */])(
"numOrSizeSplits",
node,
tensorMap,
context
);
return dist["split"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
numOrSizeSplits,
axis
);
}
case "ScatterNd": {
const indices = Object(utils["b" /* getParamValue */])(
"indices",
node,
tensorMap,
context
);
const values = Object(utils["b" /* getParamValue */])(
"values",
node,
tensorMap,
context
);
const shape = Object(utils["b" /* getParamValue */])("shape", node, tensorMap, context);
return [dist["scatterND"](indices, values, shape)];
}
case "GatherNd": {
const x = Object(utils["b" /* getParamValue */])("x", node, tensorMap, context);
const indices = Object(utils["b" /* getParamValue */])(
"indices",
node,
tensorMap,
context
);
return [dist["gatherND"](x, indices)];
}
case "SparseToDense": {
const indices = Object(utils["b" /* getParamValue */])(
"sparseIndices",
node,
tensorMap,
context
);
const shape = Object(utils["b" /* getParamValue */])(
"outputShape",
node,
tensorMap,
context
);
const sparseValues = Object(utils["b" /* getParamValue */])(
"sparseValues",
node,
tensorMap,
context
);
const defaultValue = Object(utils["b" /* getParamValue */])(
"defaultValue",
node,
tensorMap,
context
);
return [
dist["sparseToDense"](
indices,
sparseValues,
shape,
sparseValues.dtype === defaultValue.dtype
? defaultValue
: defaultValue.asType(sparseValues.dtype)
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const slice_join_executor_CATEGORY = "slice_join";
//# sourceMappingURL=slice_join_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/spectral_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const spectral_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "FFT": {
return [
dist["fft"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "IFFT": {
return [
dist["ifft"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "RFFT": {
return [
dist["rfft"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
case "IRFFT": {
return [
dist["irfft"](Object(utils["b" /* getParamValue */])("x", node, tensorMap, context)),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const spectral_executor_CATEGORY = "spectral";
//# sourceMappingURL=spectral_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/transformation_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const transformation_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case "Cast": {
return [
dist["cast"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("dtype", node, tensorMap, context)
),
];
}
case "ExpandDims": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
return [
dist["expandDims"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis
),
];
}
case "Squeeze": {
const axis = Object(utils["b" /* getParamValue */])("axis", node, tensorMap, context);
return [
dist["squeeze"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
axis
),
];
}
case "Reshape": {
return [
dist["reshape"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("shape", node, tensorMap, context)
),
];
}
case "PadV2":
case "Pad": {
return [
dist["pad"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["f" /* split */])(
Object(utils["b" /* getParamValue */])("padding", node, tensorMap, context),
2
),
Object(utils["b" /* getParamValue */])("constantValue", node, tensorMap, context)
),
];
}
case "SpaceToBatchND": {
const blockShape = Object(utils["b" /* getParamValue */])(
"blockShape",
node,
tensorMap,
context
);
const paddings = Object(utils["f" /* split */])(
Object(utils["b" /* getParamValue */])("paddings", node, tensorMap, context),
2
);
return [
dist["spaceToBatchND"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
blockShape,
paddings
),
];
}
case "BatchToSpaceND": {
const blockShape = Object(utils["b" /* getParamValue */])(
"blockShape",
node,
tensorMap,
context
);
const crops = Object(utils["f" /* split */])(
Object(utils["b" /* getParamValue */])("crops", node, tensorMap, context),
2
);
return [
dist["batchToSpaceND"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
blockShape,
crops
),
];
}
case "DepthToSpace": {
const blockSize = Object(utils["b" /* getParamValue */])(
"blockSize",
node,
tensorMap,
context
);
const dataFormat = Object(utils["b" /* getParamValue */])(
"dataFormat",
node,
tensorMap,
context
).toUpperCase();
return [
dist["depthToSpace"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
blockSize,
dataFormat
),
];
}
case "BroadcastTo": {
return [
dist["broadcastTo"](
Object(utils["b" /* getParamValue */])("x", node, tensorMap, context),
Object(utils["b" /* getParamValue */])("shape", node, tensorMap, context)
),
];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const transformation_executor_CATEGORY = "transformation";
//# sourceMappingURL=transformation_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/operation_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Executes the op defined by the node object.
* @param node
* @param tensorMap contains tensors for executed nodes and weights
*/
function operation_executor_executeOp(node, tensorMap, context) {
const value = ((node, tensorMap, context) => {
switch (node.category) {
case "arithmetic":
return dist["tidy"](() => executeOp(node, tensorMap, context));
case "basic_math":
return dist["tidy"](() => basic_math_executor_executeOp(node, tensorMap, context));
case "control":
return control_executor_executeOp(node, tensorMap, context);
case "convolution":
return dist["tidy"](() => convolution_executor_executeOp(node, tensorMap, context));
case "creation":
return dist["tidy"](() => creation_executor_executeOp(node, tensorMap, context));
case "dynamic":
return dynamic_executor_executeOp(node, tensorMap, context);
case "evaluation":
return dist["tidy"](() => evaluation_executor_executeOp(node, tensorMap, context));
case "image":
return dist["tidy"](() => image_executor_executeOp(node, tensorMap, context));
case "graph":
return dist["tidy"](() => graph_executor_executeOp(node, tensorMap, context));
case "logical":
return dist["tidy"](() => logical_executor_executeOp(node, tensorMap, context));
case "matrices":
return dist["tidy"](() => matrices_executor_executeOp(node, tensorMap, context));
case "normalization":
return dist["tidy"](() => normalization_executor_executeOp(node, tensorMap, context));
case "reduction":
return dist["tidy"](() => reduction_executor_executeOp(node, tensorMap, context));
case "slice_join":
return dist["tidy"](() => slice_join_executor_executeOp(node, tensorMap, context));
case "spectral":
return dist["tidy"](() => spectral_executor_executeOp(node, tensorMap, context));
case "transformation":
return dist["tidy"](() =>
transformation_executor_executeOp(node, tensorMap, context)
);
case "custom":
const opMapper = Object(register["b" /* getRegisteredOp */])(node.op);
if (opMapper && opMapper.customExecutor) {
return opMapper.customExecutor(
new node_value_impl_NodeValueImpl(node, tensorMap, context)
);
} else {
throw TypeError(`Custom op ${node.op} is not registered.`);
}
default:
throw TypeError(
`Unknown op '${node.op}'. File an issue at ` +
`https://github.com/tensorflow/tfjs/issues so we can add it` +
`, or register a custom execution with tf.registerOp()`
);
}
})(node, tensorMap, context);
if (value instanceof Promise) {
return value.then((data) => [].concat(data));
}
return [].concat(value);
}
//# sourceMappingURL=operation_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/execution_context.js
/**
* ExecutionContext captures the runtime environment of the node. It keeps
* track of the current frame and iteration for the control flow ops.
*
* For example, typical Dynamic RNN model may contain loops, for which
* TensorFlow will generate graphs with Enter/Exit nodes to control the
* current execution frame, and NextIteration Nodes for iteration id increment.
* For model with branch logic, TensorFLow will generate Switch/Merge ops.
*/
class ExecutionContext {
constructor(weightMap, tensorArrayMap, functionMap = {}) {
this.weightMap = weightMap;
this.tensorArrayMap = tensorArrayMap;
this.functionMap = functionMap;
this.rootContext = { id: 0, frameName: "", iterationId: 0 };
this.contexts = [this.rootContext];
this.lastId = 0;
this.generateCurrentContextIds();
}
newFrame(id, frameName) {
return { id, frameName, iterationId: 0 };
}
/**
* Set the current context
* @param contexts: ExecutionContextInfo[] the current path of execution
* frames
*/
set currentContext(contexts) {
if (this.contexts !== contexts) {
this.contexts = contexts;
this.generateCurrentContextIds();
}
}
get currentContext() {
return this.contexts;
}
/**
* Returns the current context in string format.
*/
get currentContextId() {
return this._currentContextIds[0];
}
/**
* Returns the current context and all parent contexts in string format.
* This allow access to the nodes in the current and parent frames.
*/
get currentContextIds() {
return this._currentContextIds;
}
generateCurrentContextIds() {
const names = [];
for (let i = 0; i < this.contexts.length - 1; i++) {
const contexts = this.contexts.slice(0, this.contexts.length - i);
names.push(this.contextIdforContexts(contexts));
}
names.push("");
this._currentContextIds = names;
}
contextIdforContexts(contexts) {
return contexts
? contexts
.map((context) =>
context.id === 0 && context.iterationId === 0
? ""
: `${context.frameName}-${context.iterationId}`
)
.join("/")
: "";
}
/**
* Enter a new frame, a new context is pushed on the current context list.
* @param frameId new frame id
*/
enterFrame(frameId) {
if (this.contexts) {
this.lastId++;
this.contexts = this.contexts.slice();
this.contexts.push(this.newFrame(this.lastId, frameId));
this._currentContextIds.unshift(this.contextIdforContexts(this.contexts));
}
}
/**
* Exit the current frame, the last context is removed from the current
* context list.
*/
exitFrame() {
if (this.contexts && this.contexts.length > 1) {
this.contexts = this.contexts.slice();
this.contexts.splice(-1);
this.currentContextIds.shift();
} else {
throw new Error("Cannot exit frame, the context is empty");
}
}
/**
* Enter the next iteration of a loop, the iteration id of last context is
* increased.
*/
nextIteration() {
if (this.contexts && this.contexts.length > 0) {
this.contexts = this.contexts.slice();
this.lastId++;
const context = Object.assign({}, this.contexts[this.contexts.length - 1]);
context.iterationId += 1;
context.id = this.lastId;
this.contexts.splice(-1, 1, context);
this._currentContextIds.splice(0, 1, this.contextIdforContexts(this.contexts));
} else {
throw new Error("Cannot increase frame iteration, the context is empty");
}
}
getWeight(name) {
return this.weightMap[name];
}
addTensorArray(tensorArray) {
this.tensorArrayMap[tensorArray.id] = tensorArray;
}
getTensorArray(id) {
return this.tensorArrayMap[id];
}
}
//# sourceMappingURL=execution_context.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/model_analysis.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.
* =============================================================================
*/
/**
* Given graph inputs and desired outputs, find the minimal set of nodes
* to execute in order to compute the outputs. In addition return other useful
* info such:
* - Missing inputs needed to compute the output.
* - Whether the subgraph contains dynamic ops (control flow, dynamic shape).
* - Alternative inputs in order to avoid async (dynamic op) execution.
*/
function getExecutionSubgraph(inputs, outputs, weightMap) {
const usedNodes = new Set();
const missingInputs = [];
let dynamicNode = null;
let syncInputs = null;
// Start with the outputs, going backwards and find all the nodes that are
// needed to compute those outputs.
const seen = new Set();
const inputNodeNames = Object.keys(inputs).map(
(name) => Object(utils["e" /* parseNodeName */])(name)[0]
);
const frontier = [...outputs];
while (frontier.length > 0) {
const node = frontier.pop();
if (isControlFlow(node) || isDynamicShape(node)) {
if (dynamicNode == null) {
dynamicNode = node;
syncInputs = dynamicNode.children
.map((child) => child.name)
.filter((name) => usedNodes.has(name));
}
}
usedNodes.add(node.name);
// Weights are dead end since we already have their values.
if (weightMap[node.name] != null) {
continue;
}
// This node is a dead end since it's one of the user-provided inputs.
if (inputNodeNames.indexOf(node.name) !== -1) {
continue;
}
if (node.inputs.length === 0) {
missingInputs.push(node.name);
continue;
}
node.inputs.forEach((input) => {
// Don't add to the frontier if it is already there.
if (seen.has(input.name)) {
return;
}
seen.add(input.name);
frontier.push(input);
});
}
return { inputs, outputs, usedNodes, missingInputs, dynamicNode, syncInputs };
}
/**
* Given the execution info, return a list of nodes in topological order that
* need to be executed to compute the output.
*/
function getNodesInTopologicalOrder(graph, weightMap, executionInfo) {
const { usedNodes, inputs } = executionInfo;
const frontier = [];
const inputNodes = Object.keys(inputs)
.map((name) => Object(utils["e" /* parseNodeName */])(name)[0])
.map((name) => graph.nodes[name]);
inputNodes.forEach((input) => {
if (usedNodes.has(input.name)) {
frontier.push(input);
}
});
graph.weights.forEach((weight) => {
if (usedNodes.has(weight.name)) {
frontier.push(weight);
}
});
const seen = new Set();
const orderedNodes = [];
while (frontier.length > 0) {
const node = frontier.pop();
seen.add(node.name);
if (!weightMap[node.name]) {
orderedNodes.push(node);
}
node.children.forEach((child) => {
if (
!seen.has(child.name) &&
usedNodes.has(child.name) &&
child.inputs.every((input) => seen.has(input.name))
) {
frontier.push(child);
}
});
}
return orderedNodes;
}
const CONTROL_FLOW_OPS = [
"Switch",
"Merge",
"Enter",
"Exit",
"NextIteration",
"StatelessIf",
"StatelessWhile",
];
const DYNAMIC_SHAPE_OPS = [
"NonMaxSuppressionV2",
"NonMaxSuppressionV3",
"NonMaxSuppressionV5",
"Where",
];
function isControlFlow(node) {
return CONTROL_FLOW_OPS.indexOf(node.op) >= 0;
}
function isDynamicShape(node) {
return DYNAMIC_SHAPE_OPS.indexOf(node.op) >= 0;
}
//# sourceMappingURL=model_analysis.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/graph_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class graph_executor_GraphExecutor {
/**
*
* @param graph Graph the model or function graph to be executed.
* @param parent When building function exector you need to set the parent
* executor. Since the weights and function executor maps are set at parant
* level, that function executor can access the function maps and weight maps
* through the parent.
*/
constructor(graph, parent) {
this.graph = graph;
this.parent = parent;
this.compiledMap = new Map();
this._weightMap = {};
this.SEPERATOR = ",";
this._functions = {};
this._functionExecutorMap = {};
this._outputs = graph.outputs;
this._inputs = graph.inputs;
this._signature = graph.signature;
this._functions = graph.functions;
// create sub-graph executors
if (graph.functions != null) {
Object.keys(graph.functions).forEach((name) => {
this._functionExecutorMap[name] = new graph_executor_GraphExecutor(
graph.functions[name],
this
);
});
}
}
get weightIds() {
return this.parent ? this.parent.weightIds : this._weightIds;
}
get functionExecutorMap() {
return this.parent ? this.parent.functionExecutorMap : this._functionExecutorMap;
}
get weightMap() {
return this.parent ? this.parent.weightMap : this._weightMap;
}
set weightMap(weightMap) {
const weightIds = Object.keys(weightMap).map((key) =>
weightMap[key].map((tensor) => tensor.id)
);
this._weightIds = [].concat(...weightIds);
this._weightMap = weightMap;
}
get inputs() {
return this._inputs.map((node) => {
return {
name: node.name,
shape: node.attrParams["shape"] ? node.attrParams["shape"].value : undefined,
dtype: node.attrParams["dtype"] ? node.attrParams["dtype"].value : undefined,
};
});
}
get outputs() {
return this._outputs.map((node) => {
return {
name: node.name,
shape: node.attrParams["shape"] ? node.attrParams["shape"].value : undefined,
dtype: node.attrParams["dtype"] ? node.attrParams["dtype"].value : undefined,
};
});
}
get inputNodes() {
return this._inputs.map((node) => node.signatureKey || node.name);
}
get outputNodes() {
return this._outputs.map((node) => {
const name = node.signatureKey || node.name;
return node.defaultOutput ? `${name}:${node.defaultOutput}` : name;
});
}
get functions() {
return Object.keys(this._functions).reduce((map, key) => {
map[key] = this._functions[key].signature;
return map;
}, {});
}
getCompilationKey(inputs, outputs) {
const sortedInputs = inputs.map((node) => node.name).sort();
const sortedOutputs = outputs.map((node) => node.name).sort();
return sortedInputs.join(this.SEPERATOR) + "--" + sortedOutputs.join(this.SEPERATOR);
}
/**
* Compiles the inference graph and returns the minimal set of nodes that are
* required for execution, in the correct execution order.
*/
compile(inputs, outputs) {
const executionInfo = getExecutionSubgraph(inputs, outputs, this.weightMap);
const { missingInputs, dynamicNode, syncInputs } = executionInfo;
if (dynamicNode != null) {
throw new Error(
`This execution contains the node '${dynamicNode.name}', which has ` +
`the dynamic op '${dynamicNode.op}'. Please use ` +
`model.executeAsync() instead. Alternatively, to avoid the ` +
`dynamic ops, specify the inputs [${syncInputs}]`
);
}
if (missingInputs.length > 0) {
const outNames = outputs.map((n) => n.name);
const inNames = Object.keys(inputs);
throw new Error(
`Cannot compute the outputs [${outNames}] from the provided inputs ` +
`[${inNames}]. Missing the following inputs: [${missingInputs}]`
);
}
return getNodesInTopologicalOrder(this.graph, this.weightMap, executionInfo);
}
/**
* Executes the inference for given input tensors.
* @param inputs Tensor map for the model inputs, keyed by the input node
* names.
* @param outputs output node name from the Tensorflow model, if no outputs
* are specified, the default outputs of the model would be used. You can
* inspect intermediate nodes of the model by adding them to the outputs
* array.
*/
execute(inputs, outputs) {
inputs = this.mapInputs(inputs);
const names = Object.keys(inputs).sort();
this.checkInputs(inputs);
this.checkInputShapeAndType(inputs);
outputs = this.mapOutputs(outputs);
this.checkOutputs(outputs);
const inputNodes = names.map(
(name) => this.graph.nodes[Object(utils["e" /* parseNodeName */])(name)[0]]
);
const outputNodes = outputs.map(
(name) => this.graph.nodes[Object(utils["e" /* parseNodeName */])(name)[0]]
);
const compilationKey = this.getCompilationKey(inputNodes, outputNodes);
// Do nothing if the compiled graph cache contains the input.
let orderedNodes = this.compiledMap.get(compilationKey);
if (orderedNodes == null) {
orderedNodes = this.compile(inputs, outputNodes);
this.compiledMap.set(compilationKey, orderedNodes);
}
const tensorArrayMap = {};
return Object(dist["tidy"])(() => {
const context = new ExecutionContext(
this.weightMap,
tensorArrayMap,
this.functionExecutorMap
);
const tensorsMap = Object.assign({}, this.weightMap);
Object.keys(inputs).forEach((name) => {
const [nodeName, index] = Object(utils["e" /* parseNodeName */])(name);
const tensors = [];
tensors[index] = inputs[name];
tensorsMap[nodeName] = tensors;
});
const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);
const intermediateTensorConsumerCount = {};
for (let i = 0; i < orderedNodes.length; i++) {
const node = orderedNodes[i];
if (!tensorsMap[node.name]) {
const tensors = operation_executor_executeOp(node, tensorsMap, context);
if (tensors instanceof Promise) {
throw new Error(
`The execution of the op '${node.op}' returned a promise. ` +
`Please use model.executeAsync() instead.`
);
}
tensorsMap[node.name] = tensors;
this.checkTensorForDisposal(
node.name,
node,
tensorsMap,
context,
tensorsToKeep,
outputs,
intermediateTensorConsumerCount
);
}
}
return outputs.map((name) =>
Object(utils["c" /* getTensor */])(name, tensorsMap, context)
);
});
}
getFrozenTensorIds(tensorMap) {
const ids = [].concat.apply(
[],
Object.keys(tensorMap)
.map((key) => tensorMap[key])
.map((tensors) => tensors.map((tensor) => tensor.id))
);
return new Set(ids);
}
checkTensorForDisposal(
nodeName,
node,
tensorMap,
context,
tensorsToKeep,
outputNames,
intermediateTensorConsumerCount
) {
// Skip output nodes and any control flow nodes, since its dependency is
// tricky to track correctly.
if (node.category === "control" || outputNames.indexOf(nodeName) !== -1) {
return;
}
tensorMap[nodeName].forEach((tensor) => {
if (tensor != null) {
intermediateTensorConsumerCount[tensor.id] =
(intermediateTensorConsumerCount[tensor.id] || 0) + node.children.length;
}
});
node.inputs.forEach((input) => {
// Skip any control flow nodes, since its dependency is tricky to track
// correctly.
if (input.category !== "control") {
const tensors = Object(utils["d" /* getTensorsForCurrentContenxt */])(
input.name,
tensorMap,
context
);
if (tensors != null) {
tensors.forEach((tensor) => {
if (tensor && !tensorsToKeep.has(tensor.id)) {
const count = intermediateTensorConsumerCount[tensor.id];
if (count === 1) {
tensor.dispose();
delete intermediateTensorConsumerCount[tensor.id];
} else if (count != null) {
// only intermediate nodes has count set, inputs and weights are
// not.
intermediateTensorConsumerCount[tensor.id]--;
}
}
});
}
}
});
}
/**
* Executes the inference for given input tensors in Async fashion.
* @param inputs Tensor map for the model inputs, keyed by the input node
* names.
* @param outputs output node name from the Tensorflow model, if no outputs
* are specified, the default outputs of the model would be used. You can
* inspect intermediate nodes of the model by adding them to the outputs
* array.
* @param disableWarning disable the no dynamic ops warning message, default
* to false
*/
async executeAsync(inputs, outputs, disableWarning = false) {
inputs = this.mapInputs(inputs);
this.checkInputs(inputs);
this.checkInputShapeAndType(inputs);
outputs = this.mapOutputs(outputs);
this.checkOutputs(outputs);
const tensorArrayMap = {};
const context = new ExecutionContext(
this.weightMap,
tensorArrayMap,
this.functionExecutorMap
);
// Graph with control flow op requires runtime evaluation of the execution
// order, while without control flow the execution order is pre-determined
// in the compile method.
const tensorMap = await this.executeWithControlFlow(
inputs,
context,
outputs,
disableWarning
);
const results = outputs.map((name) =>
Object(utils["c" /* getTensor */])(name, tensorMap, context)
);
// dispose all the intermediate tensors
const outputIds = new Set(results.map((t) => t.id));
const inputIds = new Set(Object.keys(inputs).map((name) => inputs[name].id));
Object.keys(tensorMap).forEach((key) => {
const tensorArray = tensorMap[key];
tensorArray.forEach((tensor) => {
if (
tensor &&
!tensor.isDisposed &&
!outputIds.has(tensor.id) &&
!inputIds.has(tensor.id) &&
this.weightIds.indexOf(tensor.id) === -1
) {
tensor.dispose();
}
});
});
return results;
}
async executeFunctionAsync(inputs) {
const mappedInputs = inputs.reduce((map, tensor, index) => {
map[this.inputs[index].name] = tensor;
return map;
}, {});
return this.executeAsync(mappedInputs, this.outputNodes, true);
}
/**
* When there are control flow nodes in the graph, the graph execution use
* ExecutionContext to keep track of the frames and loop iterators.
* @param inputs placeholder tensors for the graph.
* @param context the execution context object for current execution.
* @param disableWarning disable no async op warning
*/
async executeWithControlFlow(inputs, context, outputNames, disableWarning) {
const names = Object.keys(inputs);
const inputNodes = names.map(
(name) => this.graph.nodes[Object(utils["e" /* parseNodeName */])(name)[0]]
);
const outputNodes = outputNames.map(
(name) => this.graph.nodes[Object(utils["e" /* parseNodeName */])(name)[0]]
);
const { usedNodes, missingInputs, dynamicNode, syncInputs } = getExecutionSubgraph(
inputs,
outputNodes,
this.weightMap
);
const stack = [...inputNodes, ...this.graph.weights].map((node) => {
return { node, contexts: context.currentContext };
});
const tensorsMap = Object.assign({}, this.weightMap);
Object.keys(inputs).forEach((name) => {
const [nodeName, index] = Object(utils["e" /* parseNodeName */])(name);
const tensors = [];
tensors[index] = inputs[name];
tensorsMap[nodeName] = tensors;
});
const intermediateTensorConsumerCount = {};
const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);
const added = {};
while (stack.length > 0) {
const promises = this.processStack(
inputNodes,
stack,
context,
tensorsMap,
added,
tensorsToKeep,
outputNames,
intermediateTensorConsumerCount,
usedNodes
);
await Promise.all(promises);
}
if (dynamicNode == null && !disableWarning) {
console.warn(
`This model execution did not contain any nodes with control flow ` +
`or dynamic output shapes. You can use model.execute() instead.`
);
}
const missingOutputs = outputNodes
.filter(
(node) =>
!isControlFlow(node) &&
!Object(utils["c" /* getTensor */])(node.name, tensorsMap, context)
)
.map((node) => node.name);
if (missingOutputs.length > 0) {
let alternativeMsg = "";
if (dynamicNode != null) {
alternativeMsg =
`Alternatively, to avoid the dynamic ops, use model.execute() ` +
`and specify the inputs [${syncInputs}]`;
}
throw new Error(
`Cannot compute the outputs [${missingOutputs}] from the provided ` +
`inputs [${names}]. Consider providing the following inputs: ` +
`[${missingInputs}]. ${alternativeMsg}`
);
}
return tensorsMap;
}
processStack(
inputNodes,
stack,
context,
tensorMap,
added,
tensorsToKeep,
outputNames,
intermediateTensorConsumerCount,
usedNodes
) {
const promises = [];
while (stack.length > 0) {
const item = stack.pop();
context.currentContext = item.contexts;
let nodeName = "";
// The tensor of the Enter op with isConstant set should be set
// in the parent scope, so it will be available as constant for the
// whole loop.
if (
item.node.op === "Enter" &&
Object(utils["b" /* getParamValue */])("isConstant", item.node, tensorMap, context)
) {
[nodeName] = Object(utils["a" /* getNodeNameAndIndex */])(item.node.name, context);
}
// only process nodes that are not provided as input nodes.
if (inputNodes.indexOf(item.node) === -1) {
const tensors = operation_executor_executeOp(item.node, tensorMap, context);
if (!nodeName) {
[nodeName] = Object(utils["a" /* getNodeNameAndIndex */])(item.node.name, context);
}
const currentContext = context.currentContext;
if (tensors instanceof Promise) {
promises.push(
tensors.then((t) => {
tensorMap[nodeName] = t;
context.currentContext = currentContext;
this.checkTensorForDisposal(
nodeName,
item.node,
tensorMap,
context,
tensorsToKeep,
outputNames,
intermediateTensorConsumerCount
);
this.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
return t;
})
);
} else {
tensorMap[nodeName] = tensors;
this.checkTensorForDisposal(
nodeName,
item.node,
tensorMap,
context,
tensorsToKeep,
outputNames,
intermediateTensorConsumerCount
);
this.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
}
} else {
this.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
}
}
return promises;
}
processChildNodes(node, stack, context, tensorMap, added, usedNodes) {
node.children.forEach((childNode) => {
const [nodeName] = Object(utils["a" /* getNodeNameAndIndex */])(
childNode.name,
context
);
if (added[nodeName] || !usedNodes.has(childNode.name)) {
return;
}
// Merge op can be pushed if any of its inputs has value.
if (childNode.op === "Merge") {
if (
childNode.inputNames.some((name) => {
return !!Object(utils["c" /* getTensor */])(name, tensorMap, context);
})
) {
added[nodeName] = true;
stack.push({ contexts: context.currentContext, node: childNode });
}
} // Otherwise all inputs must to have value.
else if (
childNode.inputNames.every((name) => {
return !!Object(utils["c" /* getTensor */])(name, tensorMap, context);
})
) {
added[nodeName] = true;
stack.push({ contexts: context.currentContext, node: childNode });
}
});
}
/**
* Releases the memory used by the weight tensors.
*/
dispose() {
Object.keys(this.weightMap).forEach((key) =>
this.weightMap[key].forEach((tensor) => tensor.dispose())
);
}
checkInputShapeAndType(inputs) {
Object.keys(inputs).forEach((name) => {
const input = inputs[name];
const [nodeName] = Object(utils["e" /* parseNodeName */])(name);
const node = this.graph.nodes[nodeName];
if (node.attrParams["shape"] && node.attrParams["shape"].value) {
const shape = node.attrParams["shape"].value;
const match =
shape.length === input.shape.length &&
input.shape.every((dim, index) => shape[index] === -1 || shape[index] === dim);
dist["util"].assert(
match,
() =>
`The shape of dict['${node.name}'] provided in ` +
`model.execute(dict) must be [${shape}], but was ` +
`[${input.shape}]`
);
}
if (node.attrParams["dtype"] && node.attrParams["dtype"].value) {
dist["util"].assert(
input.dtype === node.attrParams["dtype"].value,
() =>
`The dtype of dict['${node.name}'] provided in ` +
`model.execute(dict) must be ` +
`${node.attrParams["dtype"].value}, but was ${input.dtype}`
);
}
});
}
mapInputs(inputs) {
const result = {};
for (const inputName in inputs) {
if (
this._signature != null &&
this._signature.inputs != null &&
this._signature.inputs[inputName] != null
) {
const tensor = this._signature.inputs[inputName];
result[tensor.name] = inputs[inputName];
} else {
result[inputName] = inputs[inputName];
}
}
return result;
}
checkInputs(inputs) {
const notInGraph = Object.keys(inputs).filter((name) => {
const [nodeName] = Object(utils["e" /* parseNodeName */])(name);
return this.graph.nodes[nodeName] == null;
});
if (notInGraph.length > 0) {
throw new Error(
`The dict provided in model.execute(dict) has ` +
`keys: [${notInGraph}] that are not part of graph`
);
}
}
mapOutputs(outputs) {
return outputs.map((name) => {
if (
this._signature != null &&
this._signature.outputs != null &&
this._signature.outputs[name] != null
) {
const tensor = this._signature.outputs[name];
return tensor.name;
}
return name;
}, {});
}
checkOutputs(outputs) {
outputs.forEach((name) => {
const [normalizedName] = Object(utils["e" /* parseNodeName */])(name);
if (!this.graph.nodes[normalizedName]) {
throw new Error(`The output '${name}' is not found in the graph`);
}
});
}
}
//# sourceMappingURL=graph_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/graph_model.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const TFHUB_SEARCH_PARAM = "?tfjs-format=file";
const DEFAULT_MODEL_NAME = "model.json";
/**
* A `tf.GraphModel` is a directed, acyclic graph built from a
* SavedModel GraphDef and allows inference execution.
*
* A `tf.GraphModel` can only be created by loading from a model converted from
* a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using
* the command line converter tool and loaded via `tf.loadGraphModel`.
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
class graph_model_GraphModel {
/**
* @param modelUrl url for the model, or an `io.IOHandler`.
* @param weightManifestUrl url for the weight file generated by
* scripts/convert.py script.
* @param requestOption options for Request, which allows to send credentials
* and custom headers.
* @param onProgress Optional, progress callback function, fired periodically
* before the load is completed.
*/
constructor(modelUrl, loadOptions = {}) {
this.modelUrl = modelUrl;
this.loadOptions = loadOptions;
this.version = "n/a";
if (loadOptions == null) {
this.loadOptions = {};
}
}
// Returns the version information for the tensorflow model GraphDef.
get modelVersion() {
return this.version;
}
get inputNodes() {
return this.executor.inputNodes;
}
get outputNodes() {
return this.executor.outputNodes;
}
get inputs() {
return this.executor.inputs;
}
get outputs() {
return this.executor.outputs;
}
get weights() {
return this.executor.weightMap;
}
findIOHandler() {
const path = this.modelUrl;
if (path.load != null) {
// Path is an IO Handler.
this.handler = path;
} else if (this.loadOptions.requestInit != null) {
this.handler = dist["io"].browserHTTPRequest(path, this.loadOptions);
} else {
const handlers = dist["io"].getLoadHandlers(path, this.loadOptions);
if (handlers.length === 0) {
// For backward compatibility: if no load handler can be found,
// assume it is a relative http path.
handlers.push(dist["io"].browserHTTPRequest(path, this.loadOptions));
} else if (handlers.length > 1) {
throw new Error(
`Found more than one (${handlers.length}) load handlers for ` + `URL '${[path]}'`
);
}
this.handler = handlers[0];
}
}
/**
* Loads the model and weight files, construct the in memory weight map and
* compile the inference graph.
*/
async load() {
this.findIOHandler();
if (this.handler.load == null) {
throw new Error(
"Cannot proceed with model loading because the IOHandler provided " +
"does not have the `load` method implemented."
);
}
const artifacts = await this.handler.load();
return this.loadSync(artifacts);
}
/**
* Synchronously construct the in memory weight map and
* compile the inference graph.
*/
/** @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true} */
loadSync(artifacts) {
this.artifacts = artifacts;
const graph = this.artifacts.modelTopology;
let signature = {};
if (this.artifacts.userDefinedMetadata != null) {
signature = this.artifacts.userDefinedMetadata.signature; // tslint:disable-next-line:no-any
}
this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`;
const weightMap = dist["io"].decodeWeights(
this.artifacts.weightData,
this.artifacts.weightSpecs
);
this.executor = new graph_executor_GraphExecutor(
operation_mapper["a" /* OperationMapper */].Instance.transformGraph(graph, signature)
);
this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);
return true;
}
/**
* Save the configuration and/or weights of the GraphModel.
*
* An `IOHandler` is an object that has a `save` method of the proper
* signature defined. The `save` method manages the storing or
* transmission of serialized data ("artifacts") that represent the
* model's topology and weights onto or via a specific medium, such as
* file downloads, local storage, IndexedDB in the web browser and HTTP
* requests to a server. TensorFlow.js provides `IOHandler`
* implementations for a number of frequently used saving mediums, such as
* `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`
* for more details.
*
* This method also allows you to refer to certain types of `IOHandler`s
* as URL-like string shortcuts, such as 'localstorage://' and
* 'indexeddb://'.
*
* Example 1: Save `model`'s topology and weights to browser [local
* storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
* then load it back.
*
* ```js
* const modelUrl =
* 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
* const model = await tf.loadGraphModel(modelUrl);
* const zeros = tf.zeros([1, 224, 224, 3]);
* model.predict(zeros).print();
*
* const saveResults = await model.save('localstorage://my-model-1');
*
* const loadedModel = await tf.loadGraphModel('localstorage://my-model-1');
* console.log('Prediction from loaded model:');
* model.predict(zeros).print();
* ```
*
* @param handlerOrURL An instance of `IOHandler` or a URL-like,
* scheme-based string shortcut for `IOHandler`.
* @param config Options for saving the model.
* @returns A `Promise` of `SaveResult`, which summarizes the result of
* the saving, such as byte sizes of the saved artifacts for the model's
* topology and weight values.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
*/
async save(handlerOrURL, config) {
if (typeof handlerOrURL === "string") {
const handlers = dist["io"].getSaveHandlers(handlerOrURL);
if (handlers.length === 0) {
throw new Error(`Cannot find any save handlers for URL '${handlerOrURL}'`);
} else if (handlers.length > 1) {
throw new Error(
`Found more than one (${handlers.length}) save handlers for ` +
`URL '${handlerOrURL}'`
);
}
handlerOrURL = handlers[0];
}
if (handlerOrURL.save == null) {
throw new Error(
"GraphModel.save() cannot proceed because the IOHandler " +
"provided does not have the `save` attribute defined."
);
}
return handlerOrURL.save(this.artifacts);
}
/**
* Execute the inference for the input tensors.
*
* @param input The input tensors, when there is single input for the model,
* inputs param should be a `tf.Tensor`. For models with mutliple inputs,
* inputs params should be in either `tf.Tensor`[] if the input order is
* fixed, or otherwise NamedTensorMap format.
*
* For model with multiple inputs, we recommend you use NamedTensorMap as the
* input type, if you use `tf.Tensor`[], the order of the array needs to
* follow the
* order of inputNodes array. @see {@link GraphModel.inputNodes}
*
* You can also feed any intermediate nodes using the NamedTensorMap as the
* input type. For example, given the graph
* InputNode => Intermediate => OutputNode,
* you can execute the subgraph Intermediate => OutputNode by calling
* model.execute('IntermediateNode' : tf.tensor(...));
*
* This is useful for models that uses tf.dynamic_rnn, where the intermediate
* state needs to be fed manually.
*
* For batch inference execution, the tensors for each input need to be
* concatenated together. For example with mobilenet, the required input shape
* is [1, 244, 244, 3], which represents the [batch, height, width, channel].
* If we are provide a batched data of 100 images, the input tensor should be
* in the shape of [100, 244, 244, 3].
*
* @param config Prediction configuration for specifying the batch size and
* output node names. Currently the batch size option is ignored for graph
* model.
*
* @returns Inference result tensors. The output would be single `tf.Tensor`
* if model has single output node, otherwise Tensor[] or NamedTensorMap[]
* will be returned for model with multiple outputs.
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
predict(inputs, config) {
return this.execute(inputs, this.outputNodes);
}
normalizeInputs(inputs) {
if (!(inputs instanceof dist["Tensor"]) && !Array.isArray(inputs)) {
// The input is already a NamedTensorMap.
return inputs;
}
inputs = Array.isArray(inputs) ? inputs : [inputs];
if (inputs.length !== this.inputNodes.length) {
throw new Error(
"Input tensor count mismatch," +
`the graph model has ${this.inputNodes.length} placeholders, ` +
`while there are ${inputs.length} input tensors.`
);
}
return this.inputNodes.reduce((map, inputName, i) => {
map[inputName] = inputs[i];
return map;
}, {});
}
normalizeOutputs(outputs) {
outputs = outputs || this.outputNodes;
return !Array.isArray(outputs) ? [outputs] : outputs;
}
/**
* Executes inference for the model for given input tensors.
* @param inputs tensor, tensor array or tensor map of the inputs for the
* model, keyed by the input node names.
* @param outputs output node name from the Tensorflow model, if no
* outputs are specified, the default outputs of the model would be used.
* You can inspect intermediate nodes of the model by adding them to the
* outputs array.
*
* @returns A single tensor if provided with a single output or no outputs
* are provided and there is only one default output, otherwise return a
* tensor array. The order of the tensor array is the same as the outputs
* if provided, otherwise the order of outputNodes attribute of the model.
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
execute(inputs, outputs) {
inputs = this.normalizeInputs(inputs);
outputs = this.normalizeOutputs(outputs);
const result = this.executor.execute(inputs, outputs);
return result.length > 1 ? result : result[0];
}
/**
* Executes inference for the model for given input tensors in async
* fashion, use this method when your model contains control flow ops.
* @param inputs tensor, tensor array or tensor map of the inputs for the
* model, keyed by the input node names.
* @param outputs output node name from the Tensorflow model, if no outputs
* are specified, the default outputs of the model would be used. You can
* inspect intermediate nodes of the model by adding them to the outputs
* array.
*
* @returns A Promise of single tensor if provided with a single output or
* no outputs are provided and there is only one default output, otherwise
* return a tensor map.
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
async executeAsync(inputs, outputs) {
inputs = this.normalizeInputs(inputs);
outputs = this.normalizeOutputs(outputs);
const result = await this.executor.executeAsync(inputs, outputs);
return result.length > 1 ? result : result[0];
}
convertTensorMapToTensorsMap(map) {
return Object.keys(map).reduce((newMap, key) => {
newMap[key] = [map[key]];
return newMap;
}, {});
}
/**
* Releases the memory used by the weight tensors.
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
dispose() {
this.executor.dispose();
}
}
/**
* Load a graph model given a URL to the model definition.
*
* Example of loading MobileNetV2 from a URL and making a prediction with a
* zeros input:
*
* ```js
* const modelUrl =
* 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
* const model = await tf.loadGraphModel(modelUrl);
* const zeros = tf.zeros([1, 224, 224, 3]);
* model.predict(zeros).print();
* ```
*
* Example of loading MobileNetV2 from a TF Hub URL and making a prediction with
* a zeros input:
*
* ```js
* const modelUrl =
* 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';
* const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});
* const zeros = tf.zeros([1, 224, 224, 3]);
* model.predict(zeros).print();
* ```
* @param modelUrl The url or an `io.IOHandler` that loads the model.
* @param options Options for the HTTP request, which allows to send credentials
* and custom headers.
*/
/** @doc {heading: 'Models', subheading: 'Loading'} */
async function loadGraphModel(modelUrl, options = {}) {
if (modelUrl == null) {
throw new Error(
"modelUrl in loadGraphModel() cannot be null. Please provide a url " +
"or an IOHandler that loads the model"
);
}
if (options == null) {
options = {};
}
if (options.fromTFHub) {
if (modelUrl.load == null) {
if (!modelUrl.endsWith("/")) {
modelUrl = modelUrl + "/";
}
modelUrl = `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`;
}
}
const model = new graph_model_GraphModel(modelUrl, options);
await model.load();
return model;
}
//# sourceMappingURL=graph_model.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/version.js
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
const version = "2.0.1";
//# sourceMappingURL=version.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/index.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
//# sourceMappingURL=index.js.map
/***/
},
/* 39 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (global) {
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(65);
var ieee754 = __webpack_require__(66);
var isArray = __webpack_require__(67);
exports.Buffer = Buffer;
exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50;
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT =
global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport();
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength();
function typedArraySupport() {
try {
var arr = new Uint8Array(1);
arr.__proto__ = {
__proto__: Uint8Array.prototype,
foo: function () {
return 42;
},
};
return (
arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === "function" && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0
); // ie10 has broken `subarray`
} catch (e) {
return false;
}
}
function kMaxLength() {
return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff;
}
function createBuffer(that, length) {
if (kMaxLength() < length) {
throw new RangeError("Invalid typed array length");
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length);
that.__proto__ = Buffer.prototype;
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length);
}
that.length = length;
}
return that;
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer(arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length);
}
// Common case.
if (typeof arg === "number") {
if (typeof encodingOrOffset === "string") {
throw new Error("If encoding is specified then the first argument must be a string");
}
return allocUnsafe(this, arg);
}
return from(this, arg, encodingOrOffset, length);
}
Buffer.poolSize = 8192; // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype;
return arr;
};
function from(that, value, encodingOrOffset, length) {
if (typeof value === "number") {
throw new TypeError('"value" argument must not be a number');
}
if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length);
}
if (typeof value === "string") {
return fromString(that, value, encodingOrOffset);
}
return fromObject(that, value);
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length);
};
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype;
Buffer.__proto__ = Uint8Array;
if (
typeof Symbol !== "undefined" &&
Symbol.species &&
Buffer[Symbol.species] === Buffer
) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
});
}
}
function assertSize(size) {
if (typeof size !== "number") {
throw new TypeError('"size" argument must be a number');
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative');
}
}
function alloc(that, size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(that, size);
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === "string"
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill);
}
return createBuffer(that, size);
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding);
};
function allocUnsafe(that, size) {
assertSize(size);
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0;
}
}
return that;
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size);
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size);
};
function fromString(that, string, encoding) {
if (typeof encoding !== "string" || encoding === "") {
encoding = "utf8";
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding');
}
var length = byteLength(string, encoding) | 0;
that = createBuffer(that, length);
var actual = that.write(string, encoding);
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual);
}
return that;
}
function fromArrayLike(that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0;
that = createBuffer(that, length);
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255;
}
return that;
}
function fromArrayBuffer(that, array, byteOffset, length) {
array.byteLength; // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError("'offset' is out of bounds");
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError("'length' is out of bounds");
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array);
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset);
} else {
array = new Uint8Array(array, byteOffset, length);
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array;
that.__proto__ = Buffer.prototype;
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array);
}
return that;
}
function fromObject(that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0;
that = createBuffer(that, len);
if (that.length === 0) {
return that;
}
obj.copy(that, 0, 0, len);
return that;
}
if (obj) {
if (
(typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer) ||
"length" in obj
) {
if (typeof obj.length !== "number" || isnan(obj.length)) {
return createBuffer(that, 0);
}
return fromArrayLike(that, obj);
}
if (obj.type === "Buffer" && isArray(obj.data)) {
return fromArrayLike(that, obj.data);
}
}
throw new TypeError(
"First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."
);
}
function checked(length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError(
"Attempt to allocate Buffer larger than maximum " +
"size: 0x" +
kMaxLength().toString(16) +
" bytes"
);
}
return length | 0;
}
function SlowBuffer(length) {
if (+length != length) {
// eslint-disable-line eqeqeq
length = 0;
}
return Buffer.alloc(+length);
}
Buffer.isBuffer = function isBuffer(b) {
return !!(b != null && b._isBuffer);
};
Buffer.compare = function compare(a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError("Arguments must be Buffers");
}
if (a === b) return 0;
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
Buffer.isEncoding = function isEncoding(encoding) {
switch (String(encoding).toLowerCase()) {
case "hex":
case "utf8":
case "utf-8":
case "ascii":
case "latin1":
case "binary":
case "base64":
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return true;
default:
return false;
}
};
Buffer.concat = function concat(list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
if (list.length === 0) {
return Buffer.alloc(0);
}
var i;
if (length === undefined) {
length = 0;
for (i = 0; i < list.length; ++i) {
length += list[i].length;
}
}
var buffer = Buffer.allocUnsafe(length);
var pos = 0;
for (i = 0; i < list.length; ++i) {
var buf = list[i];
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
buf.copy(buffer, pos);
pos += buf.length;
}
return buffer;
};
function byteLength(string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length;
}
if (
typeof ArrayBuffer !== "undefined" &&
typeof ArrayBuffer.isView === "function" &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)
) {
return string.byteLength;
}
if (typeof string !== "string") {
string = "" + string;
}
var len = string.length;
if (len === 0) return 0;
// Use a for loop to avoid recursion
var loweredCase = false;
for (;;) {
switch (encoding) {
case "ascii":
case "latin1":
case "binary":
return len;
case "utf8":
case "utf-8":
case undefined:
return utf8ToBytes(string).length;
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return len * 2;
case "hex":
return len >>> 1;
case "base64":
return base64ToBytes(string).length;
default:
if (loweredCase) return utf8ToBytes(string).length; // assume utf8
encoding = ("" + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer.byteLength = byteLength;
function slowToString(encoding, start, end) {
var loweredCase = false;
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0;
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return "";
}
if (end === undefined || end > this.length) {
end = this.length;
}
if (end <= 0) {
return "";
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0;
start >>>= 0;
if (end <= start) {
return "";
}
if (!encoding) encoding = "utf8";
while (true) {
switch (encoding) {
case "hex":
return hexSlice(this, start, end);
case "utf8":
case "utf-8":
return utf8Slice(this, start, end);
case "ascii":
return asciiSlice(this, start, end);
case "latin1":
case "binary":
return latin1Slice(this, start, end);
case "base64":
return base64Slice(this, start, end);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return utf16leSlice(this, start, end);
default:
if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
encoding = (encoding + "").toLowerCase();
loweredCase = true;
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true;
function swap(b, n, m) {
var i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer.prototype.swap16 = function swap16() {
var len = this.length;
if (len % 2 !== 0) {
throw new RangeError("Buffer size must be a multiple of 16-bits");
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1);
}
return this;
};
Buffer.prototype.swap32 = function swap32() {
var len = this.length;
if (len % 4 !== 0) {
throw new RangeError("Buffer size must be a multiple of 32-bits");
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this;
};
Buffer.prototype.swap64 = function swap64() {
var len = this.length;
if (len % 8 !== 0) {
throw new RangeError("Buffer size must be a multiple of 64-bits");
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this;
};
Buffer.prototype.toString = function toString() {
var length = this.length | 0;
if (length === 0) return "";
if (arguments.length === 0) return utf8Slice(this, 0, length);
return slowToString.apply(this, arguments);
};
Buffer.prototype.equals = function equals(b) {
if (!Buffer.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
if (this === b) return true;
return Buffer.compare(this, b) === 0;
};
Buffer.prototype.inspect = function inspect() {
var str = "";
var max = exports.INSPECT_MAX_BYTES;
if (this.length > 0) {
str = this.toString("hex", 0, max).match(/.{2}/g).join(" ");
if (this.length > max) str += " ... ";
}
return "<Buffer " + str + ">";
};
Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError("Argument must be a Buffer");
}
if (start === undefined) {
start = 0;
}
if (end === undefined) {
end = target ? target.length : 0;
}
if (thisStart === undefined) {
thisStart = 0;
}
if (thisEnd === undefined) {
thisEnd = this.length;
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError("out of range index");
}
if (thisStart >= thisEnd && start >= end) {
return 0;
}
if (thisStart >= thisEnd) {
return -1;
}
if (start >= end) {
return 1;
}
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0;
var x = thisEnd - thisStart;
var y = end - start;
var len = Math.min(x, y);
var thisCopy = this.slice(thisStart, thisEnd);
var targetCopy = target.slice(start, end);
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1;
// Normalize byteOffset
if (typeof byteOffset === "string") {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff;
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000;
}
byteOffset = +byteOffset; // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : buffer.length - 1;
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
if (byteOffset >= buffer.length) {
if (dir) return -1;
else byteOffset = buffer.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;
else return -1;
}
// Normalize val
if (typeof val === "string") {
val = Buffer.from(val, encoding);
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1;
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
} else if (typeof val === "number") {
val = val & 0xff; // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
}
}
return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
}
throw new TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
var indexSize = 1;
var arrLength = arr.length;
var valLength = val.length;
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase();
if (
encoding === "ucs2" ||
encoding === "ucs-2" ||
encoding === "utf16le" ||
encoding === "utf-16le"
) {
if (arr.length < 2 || val.length < 2) {
return -1;
}
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read(buf, i) {
if (indexSize === 1) {
return buf[i];
} else {
return buf.readUInt16BE(i * indexSize);
}
}
var i;
if (dir) {
var foundIndex = -1;
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for (i = byteOffset; i >= 0; i--) {
var found = true;
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false;
break;
}
}
if (found) return i;
}
}
return -1;
}
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
offset = Number(offset) || 0;
var remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
// must be an even number of digits
var strLen = string.length;
if (strLen % 2 !== 0) throw new TypeError("Invalid hex string");
if (length > strLen / 2) {
length = strLen / 2;
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16);
if (isNaN(parsed)) return i;
buf[offset + i] = parsed;
}
return i;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function latin1Write(buf, string, offset, length) {
return asciiWrite(buf, string, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer.prototype.write = function write(string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = "utf8";
length = this.length;
offset = 0;
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === "string") {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0;
if (isFinite(length)) {
length = length | 0;
if (encoding === undefined) encoding = "utf8";
} else {
encoding = length;
length = undefined;
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
"Buffer.write(string, encoding, offset[, length]) is no longer supported"
);
}
var remaining = this.length - offset;
if (length === undefined || length > remaining) length = remaining;
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError("Attempt to write outside buffer bounds");
}
if (!encoding) encoding = "utf8";
var loweredCase = false;
for (;;) {
switch (encoding) {
case "hex":
return hexWrite(this, string, offset, length);
case "utf8":
case "utf-8":
return utf8Write(this, string, offset, length);
case "ascii":
return asciiWrite(this, string, offset, length);
case "latin1":
case "binary":
return latin1Write(this, string, offset, length);
case "base64":
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return ucs2Write(this, string, offset, length);
default:
if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
encoding = ("" + encoding).toLowerCase();
loweredCase = true;
}
}
};
Buffer.prototype.toJSON = function toJSON() {
return {
type: "Buffer",
data: Array.prototype.slice.call(this._arr || this, 0),
};
};
function base64Slice(buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf);
} else {
return base64.fromByteArray(buf.slice(start, end));
}
}
function utf8Slice(buf, start, end) {
end = Math.min(buf.length, end);
var res = [];
var i = start;
while (i < end) {
var firstByte = buf[i];
var codePoint = null;
var bytesPerSequence =
firstByte > 0xef ? 4 : firstByte > 0xdf ? 3 : firstByte > 0xbf ? 2 : 1;
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte;
}
break;
case 2:
secondByte = buf[i + 1];
if ((secondByte & 0xc0) === 0x80) {
tempCodePoint = ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f);
if (tempCodePoint > 0x7f) {
codePoint = tempCodePoint;
}
}
break;
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {
tempCodePoint =
((firstByte & 0xf) << 0xc) |
((secondByte & 0x3f) << 0x6) |
(thirdByte & 0x3f);
if (
tempCodePoint > 0x7ff &&
(tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)
) {
codePoint = tempCodePoint;
}
}
break;
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if (
(secondByte & 0xc0) === 0x80 &&
(thirdByte & 0xc0) === 0x80 &&
(fourthByte & 0xc0) === 0x80
) {
tempCodePoint =
((firstByte & 0xf) << 0x12) |
((secondByte & 0x3f) << 0xc) |
((thirdByte & 0x3f) << 0x6) |
(fourthByte & 0x3f);
if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xfffd;
bytesPerSequence = 1;
} else if (codePoint > 0xffff) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000;
res.push(((codePoint >>> 10) & 0x3ff) | 0xd800);
codePoint = 0xdc00 | (codePoint & 0x3ff);
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000;
function decodeCodePointsArray(codePoints) {
var len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = "";
var i = 0;
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH))
);
}
return res;
}
function asciiSlice(buf, start, end) {
var ret = "";
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7f);
}
return ret;
}
function latin1Slice(buf, start, end) {
var ret = "";
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i]);
}
return ret;
}
function hexSlice(buf, start, end) {
var len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
var out = "";
for (var i = start; i < end; ++i) {
out += toHex(buf[i]);
}
return out;
}
function utf16leSlice(buf, start, end) {
var bytes = buf.slice(start, end);
var res = "";
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
}
return res;
}
Buffer.prototype.slice = function slice(start, end) {
var len = this.length;
start = ~~start;
end = end === undefined ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) {
end = len;
}
if (end < start) end = start;
var newBuf;
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end);
newBuf.__proto__ = Buffer.prototype;
} else {
var sliceLen = end - start;
newBuf = new Buffer(sliceLen, undefined);
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start];
}
}
return newBuf;
};
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
}
Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
return val;
};
Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
checkOffset(offset, byteLength, this.length);
}
var val = this[offset + --byteLength];
var mul = 1;
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul;
}
return val;
};
Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset];
};
Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | (this[offset + 1] << 8);
};
Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
return (this[offset] << 8) | this[offset + 1];
};
Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (
(this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) +
this[offset + 3] * 0x1000000
);
};
Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (
this[offset] * 0x1000000 +
((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3])
);
};
Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var i = byteLength;
var mul = 1;
var val = this[offset + --i];
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 0x80)) return this[offset];
return (0xff - this[offset] + 1) * -1;
};
Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset] | (this[offset + 1] << 8);
return val & 0x8000 ? val | 0xffff0000 : val;
};
Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset + 1] | (this[offset] << 8);
return val & 0x8000 ? val | 0xffff0000 : val;
};
Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (
this[offset] |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
);
};
Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (
(this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3]
);
};
Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, true, 23, 4);
};
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, false, 23, 4);
};
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, true, 52, 8);
};
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf))
throw new TypeError('"buffer" argument must be a Buffer instance');
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError("Index out of range");
}
Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var mul = 1;
var i = 0;
this[offset] = value & 0xff;
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xff;
}
return offset + byteLength;
};
Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var i = byteLength - 1;
var mul = 1;
this[offset + i] = value & 0xff;
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xff;
}
return offset + byteLength;
};
Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
this[offset] = value & 0xff;
return offset + 1;
};
function objectWriteUInt16(buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1;
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] =
(value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
((littleEndian ? i : 1 - i) * 8);
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
} else {
objectWriteUInt16(this, value, offset, true);
}
return offset + 2;
};
Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
} else {
objectWriteUInt16(this, value, offset, false);
}
return offset + 2;
};
function objectWriteUInt32(buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1;
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> ((littleEndian ? i : 3 - i) * 8)) & 0xff;
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = value >>> 24;
this[offset + 2] = value >>> 16;
this[offset + 1] = value >>> 8;
this[offset] = value & 0xff;
} else {
objectWriteUInt32(this, value, offset, true);
}
return offset + 4;
};
Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
} else {
objectWriteUInt32(this, value, offset, false);
}
return offset + 4;
};
Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = 0;
var mul = 1;
var sub = 0;
this[offset] = value & 0xff;
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1;
}
this[offset + i] = (((value / mul) >> 0) - sub) & 0xff;
}
return offset + byteLength;
};
Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = byteLength - 1;
var mul = 1;
var sub = 0;
this[offset + i] = value & 0xff;
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1;
}
this[offset + i] = (((value / mul) >> 0) - sub) & 0xff;
}
return offset + byteLength;
};
Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
if (value < 0) value = 0xff + value + 1;
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
} else {
objectWriteUInt16(this, value, offset, true);
}
return offset + 2;
};
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
} else {
objectWriteUInt16(this, value, offset, false);
}
return offset + 2;
};
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
this[offset + 2] = value >>> 16;
this[offset + 3] = value >>> 24;
} else {
objectWriteUInt32(this, value, offset, true);
}
return offset + 4;
};
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (value < 0) value = 0xffffffff + value + 1;
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
} else {
objectWriteUInt32(this, value, offset, false);
}
return offset + 4;
};
function checkIEEE754(buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError("Index out of range");
if (offset < 0) throw new RangeError("Index out of range");
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e38, -3.4028234663852886e38);
}
ieee754.write(buf, value, offset, littleEndian, 23, 4);
return offset + 4;
}
Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert);
};
Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157e308, -1.7976931348623157e308);
}
ieee754.write(buf, value, offset, littleEndian, 52, 8);
return offset + 8;
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert);
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert);
};
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy(target, targetStart, start, end) {
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
// Copy 0 bytes; we're done
if (end === start) return 0;
if (target.length === 0 || this.length === 0) return 0;
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError("targetStart out of bounds");
}
if (start < 0 || start >= this.length) throw new RangeError("sourceStart out of bounds");
if (end < 0) throw new RangeError("sourceEnd out of bounds");
// Are we oob?
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start;
}
var len = end - start;
var i;
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start];
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start];
}
} else {
Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
}
return len;
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill(val, start, end, encoding) {
// Handle string cases:
if (typeof val === "string") {
if (typeof start === "string") {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === "string") {
encoding = end;
end = this.length;
}
if (val.length === 1) {
var code = val.charCodeAt(0);
if (code < 256) {
val = code;
}
}
if (encoding !== undefined && typeof encoding !== "string") {
throw new TypeError("encoding must be a string");
}
if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) {
throw new TypeError("Unknown encoding: " + encoding);
}
} else if (typeof val === "number") {
val = val & 255;
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError("Out of range index");
}
if (end <= start) {
return this;
}
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
if (!val) val = 0;
var i;
if (typeof val === "number") {
for (i = start; i < end; ++i) {
this[i] = val;
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString());
var len = bytes.length;
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len];
}
}
return this;
};
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
function base64clean(str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, "");
// Node converts strings with length < 2 to ''
if (str.length < 2) return "";
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + "=";
}
return str;
}
function stringtrim(str) {
if (str.trim) return str.trim();
return str.replace(/^\s+|\s+$/g, "");
}
function toHex(n) {
if (n < 16) return "0" + n.toString(16);
return n.toString(16);
}
function utf8ToBytes(string, units) {
units = units || Infinity;
var codePoint;
var length = string.length;
var leadSurrogate = null;
var bytes = [];
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i);
// is surrogate component
if (codePoint > 0xd7ff && codePoint < 0xe000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xdbff) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd);
continue;
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd);
continue;
}
// valid lead
leadSurrogate = codePoint;
continue;
}
// 2 leads in a row
if (codePoint < 0xdc00) {
if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd);
leadSurrogate = codePoint;
continue;
}
// valid surrogate pair
codePoint = (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + 0x10000;
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd);
}
leadSurrogate = null;
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break;
bytes.push(codePoint);
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break;
bytes.push((codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80);
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break;
bytes.push(
(codePoint >> 0xc) | 0xe0,
((codePoint >> 0x6) & 0x3f) | 0x80,
(codePoint & 0x3f) | 0x80
);
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break;
bytes.push(
(codePoint >> 0x12) | 0xf0,
((codePoint >> 0xc) & 0x3f) | 0x80,
((codePoint >> 0x6) & 0x3f) | 0x80,
(codePoint & 0x3f) | 0x80
);
} else {
throw new Error("Invalid code point");
}
}
return bytes;
}
function asciiToBytes(str) {
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xff);
}
return byteArray;
}
function utf16leToBytes(str, units) {
var c, hi, lo;
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break;
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray;
}
function base64ToBytes(str) {
return base64.toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if (i + offset >= dst.length || i >= src.length) break;
dst[i + offset] = src[i];
}
return i;
}
function isnan(val) {
return val !== val; // eslint-disable-line no-self-compare
}
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(27)));
/***/
},
/* 40 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (setImmediate) {
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return nextFrame;
});
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const delayCallback = (() => {
if (typeof requestAnimationFrame !== "undefined") {
return requestAnimationFrame;
} else if (typeof setImmediate !== "undefined") {
return setImmediate;
}
return (f) => f(); // no delays
})();
/**
* Returns a promise that resolve when a requestAnimationFrame has completed.
*
* On Node.js this uses setImmediate instead of requestAnimationFrame.
*
* This is simply a sugar method so that users can do the following:
* `await tf.nextFrame();`
*/
/** @doc {heading: 'Performance', subheading: 'Timing'} */
function nextFrame() {
return new Promise((resolve) => delayCallback(() => resolve()));
}
//# sourceMappingURL=browser_util.js.map
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(76).setImmediate));
/***/
},
/* 41 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "Add",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "AddV2",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "AddN",
category: "arithmetic",
inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }],
},
{
tfOpName: "BiasAdd",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Sub",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "RealDiv",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Div",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "DivNoNan",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "FloorDiv",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Mul",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Maximum",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
},
{
tfOpName: "Minimum",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
},
{
tfOpName: "Pow",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "SquaredDifference",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Mod",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "FloorMod",
category: "arithmetic",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
];
//# sourceMappingURL=arithmetic.js.map
/***/
},
/* 42 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "Abs",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Acos",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Asin",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Atan",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Atan2",
category: "basic_math",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "y", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Ceil",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "ClipByValue",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "clip_value_min", name: "clipValueMin", type: "number" },
{ tfName: "clip_value_max", name: "clipValueMax", type: "number" },
],
},
{
tfOpName: "Complex",
category: "basic_math",
inputs: [
{ start: 0, name: "real", type: "tensor" },
{ start: 1, name: "imag", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "ComplexAbs",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Cos",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Cosh",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Elu",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Exp",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Floor",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Log",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Imag",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
{
tfName: "Tout",
name: "outputType",
type: "dtype",
notSupported: true,
},
],
},
{
tfOpName: "Neg",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Real",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
{
tfName: "Tout",
name: "outputType",
type: "dtype",
notSupported: true,
},
],
},
{
tfOpName: "Prelu",
category: "basic_math",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "alpha", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Relu",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Relu6",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
{
tfName: "clipValueMin",
name: "clipValueMin",
type: "number",
defaultValue: 0,
},
{
tfName: "clipValueMax",
name: "clipValueMax",
type: "number",
defaultValue: 6,
},
],
},
{
tfOpName: "Selu",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Sigmoid",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Sin",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Sinh",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Sqrt",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Rsqrt",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Square",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Tan",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Tanh",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Sign",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Round",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Expm1",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Log1p",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Reciprocal",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Softplus",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Asinh",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Acosh",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Atanh",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Erf",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Prod",
category: "basic_math",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axes", type: "number[]" },
],
attrs: [
{
tfName: "keep_dims",
name: "keepDims",
type: "bool",
notSupported: true,
},
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "LeakyRelu",
category: "basic_math",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{
tfName: "alpha",
name: "alpha",
type: "number",
defaultValue: 0.2,
},
{
tfName: "T",
name: "dtype",
type: "dtype",
notSupported: true,
},
],
},
];
//# sourceMappingURL=basic_math.js.map
/***/
},
/* 43 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "LoopCond",
category: "control",
inputs: [{ start: 0, name: "pred", type: "tensor" }],
},
{
tfOpName: "Switch",
category: "control",
inputs: [
{ start: 0, name: "data", type: "tensor" },
{ start: 1, name: "pred", type: "tensor" },
],
},
{
tfOpName: "Merge",
category: "control",
inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }],
},
{
tfOpName: "Enter",
category: "control",
inputs: [{ start: 0, name: "tensor", type: "tensor" }],
attrs: [
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
{ tfName: "frame_name", name: "frameName", type: "string" },
{ tfName: "is_constant", name: "isConstant", type: "bool" },
],
},
{
tfOpName: "Exit",
category: "control",
inputs: [{ start: 0, name: "tensor", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "NextIteration",
category: "control",
inputs: [{ start: 0, name: "tensor", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "TensorArrayV3",
category: "control",
inputs: [{ start: 0, name: "size", type: "number" }],
attrs: [
{ tfName: "dtype", name: "dtype", type: "dtype" },
{ tfName: "element_shape", name: "elementShape", type: "shape" },
{ tfName: "dynamic_size", name: "dynamicSize", type: "bool" },
{ tfName: "clear_after_read", name: "clearAfterRead", type: "bool" },
{
tfName: "identical_element_shapes",
name: "identicalElementShapes",
type: "bool",
},
{ tfName: "tensor_array_name", name: "name", type: "string" },
],
},
{
tfOpName: "TensorArrayWriteV3",
category: "control",
inputs: [
{ start: 0, name: "tensorArrayId", type: "number" },
{ start: 1, name: "index", type: "number" },
{ start: 2, name: "tensor", type: "tensor" },
{ start: 3, name: "flowIn", type: "number" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "TensorArrayReadV3",
category: "control",
inputs: [
{ start: 0, name: "tensorArrayId", type: "number" },
{ start: 1, name: "index", type: "number" },
{ start: 2, name: "flowIn", type: "number" },
],
attrs: [
{
tfName: "dtype",
name: "dtype",
type: "dtype",
notSupported: true,
},
],
},
{
tfOpName: "TensorArrayGatherV3",
category: "control",
inputs: [
{ start: 0, name: "tensorArrayId", type: "number" },
{ start: 1, name: "indices", type: "number[]" },
{ start: 2, name: "flowIn", type: "number" },
],
attrs: [
{ tfName: "dtype", name: "dtype", type: "dtype" },
{ tfName: "element_shape", name: "elementShape", type: "shape" },
],
},
{
tfOpName: "TensorArrayScatterV3",
category: "control",
inputs: [
{ start: 0, name: "tensorArrayId", type: "number" },
{ start: 1, name: "indices", type: "number[]" },
{ start: 2, name: "tensor", type: "tensor" },
{ start: 3, name: "flowIn", type: "number" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype" }],
},
{
tfOpName: "TensorArrayConcatV3",
category: "control",
inputs: [
{ start: 0, name: "tensorArrayId", type: "number" },
{ start: 1, name: "flowIn", type: "number" },
],
attrs: [
{ tfName: "dtype", name: "dtype", type: "dtype" },
{
tfName: "element_shape_except0",
name: "elementShapeExcept0",
type: "shape",
notSupported: true,
},
],
},
{
tfOpName: "TensorArraySplitV3",
category: "control",
inputs: [
{ start: 0, name: "tensorArrayId", type: "number" },
{ start: 1, name: "tensor", type: "tensor" },
{ start: 2, name: "lengths", type: "number[]" },
{ start: 3, name: "flowIn", type: "number" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype" }],
},
{
tfOpName: "TensorArraySizeV3",
category: "control",
inputs: [
{ start: 0, name: "tensorArrayId", type: "number" },
{ start: 1, name: "flowIn", type: "number" },
],
},
{
tfOpName: "TensorArrayCloseV3",
category: "control",
inputs: [{ start: 0, name: "tensorArrayId", type: "number" }],
},
{
tfOpName: "StatelessIf",
category: "control",
inputs: [
{ start: 0, name: "cond", type: "tensor" },
{ start: 1, end: 0, name: "args", type: "tensors" },
],
attrs: [
{ tfName: "then_branch", name: "thenBranch", type: "func" },
{ tfName: "else_branch", name: "elseBranch", type: "func" },
],
},
{
tfOpName: "If",
category: "control",
inputs: [
{ start: 0, name: "cond", type: "tensor" },
{ start: 1, end: 0, name: "args", type: "tensors" },
],
attrs: [
{ tfName: "then_branch", name: "thenBranch", type: "func" },
{ tfName: "else_branch", name: "elseBranch", type: "func" },
],
},
{
tfOpName: "StatelessWhile",
category: "control",
inputs: [{ start: 0, end: 0, name: "args", type: "tensors" }],
attrs: [
{ tfName: "cond", name: "cond", type: "func" },
{ tfName: "body", name: "body", type: "func" },
],
},
{
tfOpName: "While",
category: "control",
inputs: [{ start: 0, end: 0, name: "args", type: "tensors" }],
attrs: [
{ tfName: "cond", name: "cond", type: "func" },
{ tfName: "body", name: "body", type: "func" },
],
},
];
//# sourceMappingURL=control.js.map
/***/
},
/* 44 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "AvgPool",
category: "convolution",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
notSupported: true,
},
{ tfName: "ksize", name: "kernelSize", type: "number[]" },
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "MaxPool",
category: "convolution",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
notSupported: true,
},
{ tfName: "ksize", name: "kernelSize", type: "number[]" },
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "MaxPoolWithArgmax",
category: "convolution",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{ tfName: "ksize", name: "kernelSize", type: "number[]" },
{
tfName: "include_batch_in_index",
name: "includeBatchInIndex",
type: "bool",
},
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "AvgPool3D",
category: "convolution",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
notSupported: true,
},
{ tfName: "ksize", name: "kernelSize", type: "number[]" },
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "MaxPool3D",
category: "convolution",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
notSupported: true,
},
{ tfName: "ksize", name: "kernelSize", type: "number[]" },
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "Conv1D",
category: "convolution",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "filter", type: "tensor" },
],
attrs: [
{ tfName: "stride", name: "stride", type: "number" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
defaultValue: "NWC",
},
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
{
tfName: "dilation",
name: "dilation",
type: "number",
defaultValue: 1,
},
],
},
{
tfOpName: "Conv2D",
category: "convolution",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "filter", type: "tensor" },
],
attrs: [
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{ tfName: "useCudnnOnGpu", name: "useCudnnOnGpu", type: "bool" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
defaultValue: "NHWC",
},
{
tfName: "explicit_paddings",
name: "explicitPaddings",
type: "number[]",
defaultValue: [],
},
{ tfName: "dilations", name: "dilations", type: "number[]" },
],
},
{
tfOpName: "_FusedConv2D",
category: "convolution",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "filter", type: "tensor" },
{ start: 2, end: 0, name: "args", type: "tensors" },
],
attrs: [
{ tfName: "num_args", name: "numArgs", type: "number" },
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "explicit_paddings",
name: "explicitPaddings",
type: "number[]",
defaultValue: [],
},
{
tfName: "use_cudnn_on_gpu",
name: "useCudnnOnGpu",
type: "bool",
defaultValue: true,
},
{
tfName: "data_format",
name: "dataFormat",
type: "string",
defaultValue: "NHWC",
},
{
tfName: "dilations",
name: "dilations",
type: "number[]",
defaultValue: [1, 1, 1, 1],
},
{
tfName: "fused_ops",
name: "fusedOps",
type: "string[]",
defaultValue: [],
},
{
tfName: "epsilon",
name: "epsilon",
type: "number",
defaultValue: 0.0001,
},
],
},
{
tfOpName: "Conv2DBackpropInput",
category: "convolution",
inputs: [
{ start: 2, name: "x", type: "tensor" },
{ start: 1, name: "filter", type: "tensor" },
{ start: 0, name: "outputShape", type: "number[]" },
],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
notSupported: true,
},
{
tfName: "explicit_paddings",
name: "explicitPaddings",
type: "number[]",
defaultValue: [],
},
],
},
{
tfOpName: "DepthwiseConv2d",
category: "convolution",
inputs: [
{ start: 0, name: "input", type: "tensor" },
{ start: 1, name: "filter", type: "tensor" },
],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
defaultValue: "NHWC",
},
{
tfName: "explicit_paddings",
name: "explicitPaddings",
type: "number[]",
defaultValue: [],
},
{ tfName: "dilations", name: "dilations", type: "number[]" },
],
},
{
tfOpName: "DepthwiseConv2dNative",
category: "convolution",
inputs: [
{ start: 0, name: "input", type: "tensor" },
{ start: 1, name: "filter", type: "tensor" },
],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
defaultValue: "NHWC",
},
{
tfName: "explicit_paddings",
name: "explicitPaddings",
type: "number[]",
defaultValue: [],
},
{ tfName: "dilations", name: "dilations", type: "number[]" },
],
},
{
tfOpName: "FusedDepthwiseConv2dNative",
category: "convolution",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "filter", type: "tensor" },
{ start: 2, end: 0, name: "args", type: "tensors" },
],
attrs: [
{ tfName: "num_args", name: "numArgs", type: "number" },
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
defaultValue: "NHWC",
},
{
tfName: "dilations",
name: "dilations",
type: "number[]",
defaultValue: [1, 1, 1, 1],
},
{
tfName: "fused_ops",
name: "fusedOps",
type: "string[]",
defaultValue: [],
},
],
},
{
tfOpName: "Conv3D",
category: "convolution",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "filter", type: "tensor" },
],
attrs: [
{ tfName: "strides", name: "strides", type: "number[]" },
{ tfName: "padding", name: "pad", type: "string" },
{
tfName: "data_format",
name: "dataFormat",
type: "string",
defaultValue: "NHWC",
},
{ tfName: "dilations", name: "dilations", type: "number[]" },
],
},
];
//# sourceMappingURL=convolution.js.map
/***/
},
/* 45 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "Fill",
category: "creation",
inputs: [
{ start: 0, name: "shape", type: "number[]" },
{ start: 1, name: "value", type: "number" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype" }],
},
{
tfOpName: "LinSpace",
category: "creation",
inputs: [
{ start: 0, name: "start", type: "number" },
{ start: 1, name: "stop", type: "number" },
{ start: 2, name: "num", type: "number" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "OneHot",
category: "creation",
inputs: [
{ start: 0, name: "indices", type: "tensor" },
{ start: 1, name: "depth", type: "number" },
{ start: 2, name: "onValue", type: "number", defaultValue: 1 },
{ start: 3, name: "offValue", type: "number", defaultValue: 0 },
],
attrs: [
{
tfName: "axis",
name: "axis",
type: "number",
notSupported: true,
},
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "Ones",
category: "creation",
inputs: [{ start: 0, name: "shape", type: "number[]" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype" }],
},
{
tfOpName: "OnesLike",
category: "creation",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "dtype", name: "dtype", type: "dtype" }],
},
{
tfOpName: "RandomUniform",
category: "creation",
inputs: [{ start: 0, name: "shape", type: "number[]" }],
attrs: [
{
tfName: "minval",
name: "minval",
type: "number",
defaultValue: 0,
},
{
tfName: "maxval",
name: "maxval",
type: "number",
defaultValue: 1,
},
{ tfName: "dtype", name: "dtype", type: "dtype" },
{ tfName: "seed", name: "seed", type: "number", defaultValue: 0 },
{
tfName: "seed2",
name: "seed2",
type: "number",
defaultValue: 0,
notSupported: true,
},
{ tfName: "T", name: "T", type: "number", notSupported: true },
],
},
{
tfOpName: "Range",
category: "creation",
inputs: [
{ start: 0, name: "start", type: "number" },
{ start: 1, name: "stop", type: "number" },
{ start: 2, name: "step", type: "number", defaultValue: 0 },
],
attrs: [{ tfName: "Tidx", name: "dtype", type: "dtype" }],
},
{
tfOpName: "TruncatedNormal",
category: "creation",
inputs: [{ start: 0, name: "shape", type: "number[]" }],
attrs: [
{
tfName: "means",
name: "mean",
type: "number",
defaultValue: 0.0,
},
{
tfName: "stddev",
name: "stdDev",
type: "number",
defaultValue: 1.0,
},
{ tfName: "seed", name: "seed", type: "number" },
{
tfName: "seed2",
name: "seed2",
type: "number",
defaultValue: 0,
notSupported: true,
},
{ tfName: "dtype", name: "dtype", type: "dtype" },
{ tfName: "T", name: "T", type: "number", notSupported: true },
],
},
{
tfOpName: "Zeros",
category: "creation",
inputs: [{ start: 0, name: "shape", type: "number[]" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype" }],
},
{
tfOpName: "ZerosLike",
category: "creation",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype" }],
},
{
tfOpName: "Multinomial",
category: "creation",
inputs: [
{ start: 0, name: "logits", type: "tensor" },
{ start: 1, name: "numSamples", type: "number" },
],
attrs: [
{ tfName: "seed", name: "seed", type: "number" },
{ tfName: "seed2", name: "seed2", type: "number" },
{ tfName: "T", name: "dtype", type: "dtype" },
{ tfName: "output_dtype", name: "output_dtype", type: "dtype" },
],
},
];
//# sourceMappingURL=creation.js.map
/***/
},
/* 46 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "NonMaxSuppressionV2",
category: "dynamic",
inputs: [
{ start: 0, name: "boxes", type: "tensor" },
{ start: 1, name: "scores", type: "tensor" },
{ start: 2, name: "maxOutputSize", type: "number" },
{ start: 3, name: "iouThreshold", type: "number" },
],
},
{
tfOpName: "NonMaxSuppressionV3",
category: "dynamic",
inputs: [
{ start: 0, name: "boxes", type: "tensor" },
{ start: 1, name: "scores", type: "tensor" },
{ start: 2, name: "maxOutputSize", type: "number" },
{ start: 3, name: "iouThreshold", type: "number" },
{ start: 4, name: "scoreThreshold", type: "number" },
],
},
{
tfOpName: "NonMaxSuppressionV5",
category: "dynamic",
inputs: [
{ start: 0, name: "boxes", type: "tensor" },
{ start: 1, name: "scores", type: "tensor" },
{ start: 2, name: "maxOutputSize", type: "number" },
{ start: 3, name: "iouThreshold", type: "number" },
{ start: 4, name: "scoreThreshold", type: "number" },
{ start: 5, name: "softNmsSigma", type: "number" },
],
},
{
tfOpName: "Where",
category: "dynamic",
inputs: [{ start: 0, name: "condition", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "ListDiff",
category: "dynamic",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "y", type: "tensor" },
],
attrs: [
{
tfName: "T",
name: "dtype",
type: "dtype",
notSupported: true,
},
],
},
];
//# sourceMappingURL=dynamic.js.map
/***/
},
/* 47 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "TopKV2",
category: "evaluation",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "k", type: "number" },
],
attrs: [{ tfName: "sorted", name: "sorted", type: "bool" }],
},
];
//# sourceMappingURL=evaluation.js.map
/***/
},
/* 48 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "PlaceholderWithDefault",
category: "graph",
inputs: [{ start: 0, name: "default", type: "tensor" }],
attrs: [
{ tfName: "shape", name: "shape", type: "shape" },
{ tfName: "dtype", name: "dtype", type: "dtype" },
],
},
{
tfOpName: "Placeholder",
category: "graph",
attrs: [
{ tfName: "shape", name: "shape", type: "shape" },
{ tfName: "dtype", name: "dtype", type: "dtype" },
],
},
{ tfOpName: "Const", category: "graph" },
{
tfOpName: "Identity",
category: "graph",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "IdentityN",
category: "graph",
inputs: [{ start: 0, end: 0, name: "x", type: "tensors" }],
},
{
tfOpName: "Snapshot",
category: "graph",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "Rank",
category: "graph",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "Size",
category: "graph",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "Shape",
category: "graph",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "ShapeN",
category: "graph",
inputs: [{ start: 0, end: 0, name: "x", type: "tensors" }],
},
{
tfOpName: "Print",
category: "graph",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "data", type: "tensors" },
],
attrs: [
{ tfName: "message", name: "message", type: "string" },
{
tfName: "first_n",
name: "firstN",
type: "number",
notSupported: true,
},
{
tfName: "summarize",
name: "summarize",
type: "number",
defaultValue: 3,
},
],
},
{ tfOpName: "NoOp", category: "graph", inputs: [] },
{
tfOpName: "StopGradient",
category: "graph",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "FakeQuantWithMinMaxVars",
category: "graph",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "min", name: "min", type: "number" },
{ tfName: "max", name: "max", type: "number" },
],
},
];
//# sourceMappingURL=graph.js.map
/***/
},
/* 49 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "ResizeBilinear",
category: "image",
inputs: [
{ start: 0, name: "images", type: "tensor" },
{ start: 1, name: "size", type: "number[]" },
],
attrs: [
{ tfName: "align_corners", name: "alignCorners", type: "bool" },
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "ResizeNearestNeighbor",
category: "image",
inputs: [
{ start: 0, name: "images", type: "tensor" },
{ start: 1, name: "size", type: "number[]" },
],
attrs: [
{ tfName: "align_corners", name: "alignCorners", type: "bool" },
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "CropAndResize",
category: "image",
inputs: [
{ start: 0, name: "image", type: "tensor" },
{ start: 1, name: "boxes", type: "tensor" },
{ start: 2, name: "boxInd", type: "tensor" },
{ start: 3, name: "cropSize", type: "number[]" },
],
attrs: [
{ tfName: "method", name: "method", type: "string" },
{
tfName: "extrapolation_value",
name: "extrapolationValue",
type: "number",
},
],
},
];
//# sourceMappingURL=image.js.map
/***/
},
/* 50 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "Equal",
category: "logical",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "NotEqual",
category: "logical",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Greater",
category: "logical",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "GreaterEqual",
category: "logical",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Less",
category: "logical",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "LessEqual",
category: "logical",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "LogicalAnd",
category: "logical",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "LogicalNot",
category: "logical",
inputs: [{ start: 0, name: "a", type: "tensor" }],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "LogicalOr",
category: "logical",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "Select",
category: "logical",
inputs: [
{ start: 0, name: "condition", type: "tensor" },
{ start: 1, name: "a", type: "tensor" },
{ start: 2, name: "b", type: "tensor" },
],
attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }],
},
{
tfOpName: "SelectV2",
category: "logical",
inputs: [
{ start: 0, name: "condition", type: "tensor" },
{ start: 1, name: "a", type: "tensor" },
{ start: 2, name: "b", type: "tensor" },
],
attrs: [
{
tfName: "T",
name: "dtype",
type: "dtype",
notSupported: true,
},
],
},
];
//# sourceMappingURL=logical.js.map
/***/
},
/* 51 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "_FusedMatMul",
category: "matrices",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
{ start: 2, end: 0, name: "args", type: "tensors" },
],
attrs: [
{ tfName: "num_args", name: "numArgs", type: "number" },
{
tfName: "fused_ops",
name: "fusedOps",
type: "string[]",
defaultValue: [],
},
{
tfName: "epsilon",
name: "epsilon",
type: "number",
defaultValue: 0.0001,
},
{
tfName: "transpose_a",
name: "transposeA",
type: "bool",
defaultValue: false,
},
{
tfName: "transpose_b",
name: "transposeB",
type: "bool",
defaultValue: false,
},
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "MatMul",
category: "matrices",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [
{
tfName: "transpose_a",
name: "transposeA",
type: "bool",
defaultValue: false,
},
{
tfName: "transpose_b",
name: "transposeB",
type: "bool",
defaultValue: false,
},
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "BatchMatMul",
category: "matrices",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [
{
tfName: "adj_x",
name: "transposeA",
type: "bool",
defaultValue: false,
},
{
tfName: "adj_y",
name: "transposeB",
type: "bool",
defaultValue: false,
},
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "BatchMatMulV2",
category: "matrices",
inputs: [
{ start: 0, name: "a", type: "tensor" },
{ start: 1, name: "b", type: "tensor" },
],
attrs: [
{
tfName: "adj_x",
name: "transposeA",
type: "bool",
defaultValue: false,
},
{
tfName: "adj_y",
name: "transposeB",
type: "bool",
defaultValue: false,
},
{ tfName: "T", name: "dtype", type: "dtype", notSupported: true },
],
},
{
tfOpName: "Transpose",
category: "matrices",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "perm", type: "number[]" },
],
attrs: [
{
tfName: "T",
name: "dtype",
type: "dtype",
notSupported: true,
},
],
},
];
//# sourceMappingURL=matrices.js.map
/***/
},
/* 52 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "FusedBatchNorm",
category: "normalization",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "scale", type: "tensor" },
{ start: 2, name: "offset", type: "tensor" },
{ start: 3, name: "mean", type: "tensor" },
{ start: 4, name: "variance", type: "tensor" },
],
attrs: [
{
tfName: "epsilon",
name: "epsilon",
type: "number",
defaultValue: 0.001,
},
{
tfName: "data_format",
name: "dataFormat",
type: "string",
notSupported: true,
},
],
},
{
tfOpName: "FusedBatchNormV2",
category: "normalization",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "scale", type: "tensor" },
{ start: 2, name: "offset", type: "tensor" },
{ start: 3, name: "mean", type: "tensor" },
{ start: 4, name: "variance", type: "tensor" },
],
attrs: [
{
tfName: "epsilon",
name: "epsilon",
type: "number",
defaultValue: 0.001,
},
{
tfName: "data_format",
name: "dataFormat",
type: "string",
notSupported: true,
},
],
},
{
tfOpName: "FusedBatchNormV3",
category: "normalization",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "scale", type: "tensor" },
{ start: 2, name: "offset", type: "tensor" },
{ start: 3, name: "mean", type: "tensor" },
{ start: 4, name: "variance", type: "tensor" },
],
attrs: [
{
tfName: "epsilon",
name: "epsilon",
type: "number",
defaultValue: 0.001,
},
{
tfName: "data_format",
name: "dataFormat",
type: "string",
notSupported: true,
},
],
},
{
tfOpName: "LRN",
category: "normalization",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{
tfName: "depth_radius",
name: "radius",
type: "number",
defaultValue: 5,
},
{ tfName: "bias", name: "bias", type: "number", defaultValue: 1.0 },
{
tfName: "alpha",
name: "alpha",
type: "number",
defaultValue: 1.0,
},
{
tfName: "beta",
name: "beta",
type: "number",
defaultValue: 0.5,
},
],
},
{
tfOpName: "Softmax",
category: "normalization",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "LogSoftmax",
category: "normalization",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "SparseToDense",
category: "normalization",
inputs: [
{ start: 0, name: "sparseIndices", type: "tensor" },
{ start: 1, name: "outputShape", type: "number[]" },
{ start: 2, name: "sparseValues", type: "tensor" },
{ start: 3, name: "defaultValue", type: "tensor" },
],
attrs: [
{
tfName: "validate_indices",
name: "validateIndices",
type: "bool",
defaultValue: true,
notSupported: true,
},
],
},
];
//# sourceMappingURL=normalization.js.map
/***/
},
/* 53 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "Max",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number[]" },
],
attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }],
},
{
tfOpName: "Mean",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number[]" },
],
attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }],
},
{
tfOpName: "Min",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number[]" },
],
attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }],
},
{
tfOpName: "Sum",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number[]" },
],
attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }],
},
{
tfOpName: "All",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number[]" },
],
attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }],
},
{
tfOpName: "Any",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number[]" },
],
attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }],
},
{
tfOpName: "ArgMax",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number" },
],
},
{
tfOpName: "ArgMin",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number" },
],
},
{
tfOpName: "Prod",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number[]" },
],
attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }],
},
{
tfOpName: "Cumsum",
category: "reduction",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number" },
],
attrs: [
{ tfName: "exclusive", name: "exclusive", type: "bool" },
{ tfName: "reverse", name: "reverse", type: "bool" },
],
},
];
//# sourceMappingURL=reduction.js.map
/***/
},
/* 54 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "ConcatV2",
category: "slice_join",
inputs: [
{ start: 0, end: -1, name: "tensors", type: "tensors" },
{ start: -1, name: "axis", type: "number" },
],
attrs: [{ tfName: "N", name: "n", type: "number", defaultValue: 2 }],
},
{
tfOpName: "Concat",
category: "slice_join",
inputs: [
{ start: 1, end: 0, name: "tensors", type: "tensors" },
{ start: 0, name: "axis", type: "number" },
],
attrs: [{ tfName: "N", name: "n", type: "number", defaultValue: 2 }],
},
{
tfOpName: "GatherV2",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "indices", type: "tensor" },
{ start: 2, name: "axis", type: "number", defaultValue: 0 },
],
},
{
tfOpName: "Gather",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "indices", type: "tensor" },
],
attrs: [
{ tfName: "axis", name: "axis", type: "number", defaultValue: 0 },
{
tfName: "validate_indices",
name: "validateIndices",
type: "bool",
notSupported: true,
},
],
},
{
tfOpName: "Reverse",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "dims", type: "bool", notSupported: true },
],
},
{
tfOpName: "ReverseV2",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number[]" },
],
},
{
tfOpName: "Slice",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "begin", type: "number[]" },
{ start: 2, name: "size", type: "number[]" },
],
},
{
tfOpName: "StridedSlice",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "begin", type: "number[]" },
{ start: 2, name: "end", type: "number[]" },
{ start: 3, name: "strides", type: "number[]" },
],
attrs: [
{
tfName: "begin_mask",
name: "beginMask",
type: "number",
defaultValue: 0,
},
{
tfName: "end_mask",
name: "endMask",
type: "number",
defaultValue: 0,
},
{
tfName: "new_axis_mask",
name: "newAxisMask",
type: "number",
defaultValue: 0,
},
{
tfName: "ellipsis_mask",
name: "ellipsisMask",
type: "number",
defaultValue: 0,
},
{
tfName: "shrink_axis_mask",
name: "shrinkAxisMask",
type: "number",
defaultValue: 0,
},
],
},
{
tfOpName: "Pack",
category: "slice_join",
inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }],
attrs: [{ tfName: "axis", name: "axis", type: "number", defaultValue: 0 }],
},
{
tfOpName: "Unpack",
category: "slice_join",
inputs: [{ start: 0, name: "tensor", type: "tensor" }],
attrs: [
{ tfName: "axis", name: "axis", type: "number", defaultValue: 0 },
{
tfName: "num",
name: "num",
type: "number",
defaultValue: 0,
notSupported: true,
},
],
},
{
tfOpName: "Tile",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "reps", type: "number[]" },
],
},
{
tfOpName: "Split",
category: "slice_join",
inputs: [
{ start: 0, name: "axis", type: "number", defaultValue: 0 },
{ start: 1, name: "x", type: "tensor" },
],
attrs: [
{
tfName: "num_split",
name: "numOrSizeSplits",
type: "number",
defaultValue: 1,
},
],
},
{
tfOpName: "SplitV",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "numOrSizeSplits", type: "number[]" },
{ start: 2, name: "axis", type: "number", defaultValue: 0 },
],
},
{
tfOpName: "ScatterNd",
category: "slice_join",
inputs: [
{ start: 0, name: "indices", type: "tensor" },
{ start: 1, name: "values", type: "tensor" },
{ start: 2, name: "shape", type: "number[]" },
],
},
{
tfOpName: "GatherNd",
category: "slice_join",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "indices", type: "tensor" },
],
},
{
tfOpName: "SparseToDense",
category: "slice_join",
inputs: [
{ start: 0, name: "sparseIndices", type: "tensor" },
{ start: 1, name: "outputShape", type: "number[]" },
{ start: 2, name: "sparseValues", type: "tensor" },
{ start: 3, name: "defaultValue", type: "tensor" },
],
attrs: [
{
tfName: "validate_indices",
name: "validateIndices",
type: "bool",
defaultValue: false,
notSupported: true,
},
],
},
];
//# sourceMappingURL=slice_join.js.map
/***/
},
/* 55 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "FFT",
category: "spectral",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "IFFT",
category: "spectral",
inputs: [{ start: 0, name: "x", type: "tensor" }],
},
{
tfOpName: "RFFT",
category: "spectral",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{
start: 1,
name: "fft_length",
type: "number",
notSupported: true,
},
],
},
{
tfOpName: "IRFFT",
category: "spectral",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{
start: 1,
name: "fft_length",
type: "number",
notSupported: true,
},
],
},
];
//# sourceMappingURL=spectral.js.map
/***/
},
/* 56 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"json",
function () {
return json;
}
);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
tfOpName: "Cast",
category: "transformation",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{
tfName: "SrcT",
name: "sdtype",
type: "dtype",
notSupported: true,
},
{ tfName: "DstT", name: "dtype", type: "dtype" },
],
},
{
tfOpName: "ExpandDims",
category: "transformation",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "axis", type: "number" },
],
},
{
tfOpName: "Pad",
category: "transformation",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "padding", type: "number[]" },
],
attrs: [
{
tfName: "constant_value",
name: "constantValue",
type: "number",
defaultValue: 0,
},
],
},
{
tfOpName: "PadV2",
category: "transformation",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "padding", type: "number[]" },
{
start: 2,
name: "constantValue",
type: "number",
defaultValue: 0,
},
],
},
{
tfOpName: "Reshape",
category: "transformation",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "shape", type: "number[]" },
],
},
{
tfOpName: "Squeeze",
category: "transformation",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{
tfName: "axis",
tfDeprecatedName: "squeeze_dims",
name: "axis",
type: "number[]",
},
],
},
{
tfOpName: "SpaceToBatchND",
category: "transformation",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "blockShape", type: "number[]" },
{ start: 2, name: "paddings", type: "number[]" },
],
},
{
tfOpName: "BatchToSpaceND",
category: "transformation",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "blockShape", type: "number[]" },
{ start: 2, name: "crops", type: "number[]" },
],
},
{
tfOpName: "DepthToSpace",
category: "transformation",
inputs: [{ start: 0, name: "x", type: "tensor" }],
attrs: [
{ tfName: "block_size", name: "blockSize", type: "number" },
{ tfName: "data_format", name: "dataFormat", type: "string" },
],
},
{
tfOpName: "BroadcastTo",
category: "transformation",
inputs: [
{ start: 0, name: "x", type: "tensor" },
{ start: 1, name: "shape", type: "number[]" },
],
attrs: [],
},
];
//# sourceMappingURL=transformation.js.map
/***/
},
/* 57 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (Buffer) {
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return ByteChunkIterator;
});
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(0);
/* harmony import */ var _lazy_iterator__WEBPACK_IMPORTED_MODULE_1__ =
__webpack_require__(14);
/* harmony import */ var _string_iterator__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(58);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
class ByteChunkIterator extends _lazy_iterator__WEBPACK_IMPORTED_MODULE_1__[
/* LazyIterator */ "a"
] {
/**
* Decode a stream of UTF8-encoded byte arrays to a stream of strings.
*
* The byte arrays producetd from the ByteChunkIterator on which this is
* called will be interpreted as concatenated. No assumptions are made about
* the boundaries of the incoming chunks, so a multi-byte UTF8 encoding of a
* character may span the boundary between chunks. This naturally happens,
* for instance, when reading fixed-size byte arrays from a file.
*/
decodeUTF8() {
return new Utf8Iterator(this);
}
}
// ============================================================================
// The following private classes serve to implement the chainable methods
// on ByteChunkIterator. Unfortunately they can't be placed in separate files,
// due to resulting trouble with circular imports.
// ============================================================================
// We wanted multiple inheritance, e.g.
// class Utf8Iterator extends QueueIterator<string>, StringIterator
// but the TypeScript mixin approach is a bit hacky, so we take this adapter
// approach instead.
class Utf8Iterator extends _string_iterator__WEBPACK_IMPORTED_MODULE_2__[
/* StringIterator */ "a"
] {
constructor(upstream) {
super();
this.upstream = upstream;
this.impl = new Utf8IteratorImpl(upstream);
}
summary() {
return this.impl.summary();
}
async next() {
return this.impl.next();
}
}
/**
* Decode a stream of UTF8-encoded byte arrays to a stream of strings.
*
* This is tricky because the incoming byte array boundaries may disrupt a
* multi-byte UTF8 character. Thus any incomplete character data at the end of
* a chunk must be carried over and prepended to the next chunk before
* decoding. Luckily with native decoder, TextDecoder in browser and
* string_decoder in node, byte array boundaries are handled automatically.
*
* In the context of an input pipeline for machine learning, UTF8 decoding is
* needed to parse text files containing training examples or prediction
* requests (e.g., formatted as CSV or JSON). We cannot use the built-in
* decoding provided by FileReader.readAsText() because here we are in a
* streaming context, which FileReader does not support.
*
* @param upstream A `LazyIterator` of `Uint8Arrays` containing UTF8-encoded
* text, which should be interpreted as concatenated. No assumptions are
* made about the boundaries of the incoming chunks, so a multi-byte UTF8
* encoding of a character may span the boundary between chunks. This
* naturally happens, for instance, when reading fixed-size byte arrays from a
* file.
*/
class Utf8IteratorImpl extends _lazy_iterator__WEBPACK_IMPORTED_MODULE_1__[
/* OneToManyIterator */ "b"
] {
constructor(upstream) {
super();
this.upstream = upstream;
if (
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("IS_BROWSER")
) {
this.decoder = new TextDecoder("utf-8");
} else {
// tslint:disable-next-line:no-require-imports
const { StringDecoder } = __webpack_require__(78);
this.decoder = new StringDecoder("utf8");
}
}
summary() {
return `${this.upstream.summary()} -> Utf8`;
}
async pump() {
const chunkResult = await this.upstream.next();
let chunk;
if (chunkResult.done) {
return false;
} else {
chunk = chunkResult.value;
}
let text;
if (
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("IS_BROWSER")
) {
text = this.decoder.decode(chunk, { stream: true });
} else {
text = this.decoder.write(Buffer.from(chunk.buffer));
}
this.outputQueue.push(text);
return true;
}
}
//# sourceMappingURL=byte_chunk_iterator.js.map
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(39).Buffer));
/***/
},
/* 58 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function () {
return StringIterator;
});
/* harmony import */ var _lazy_iterator__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(14);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
class StringIterator extends _lazy_iterator__WEBPACK_IMPORTED_MODULE_0__[
/* LazyIterator */ "a"
] {
/**
* Splits a string stream on a given separator.
*
* It is assumed that the incoming chunk boundaries have no semantic meaning,
* so conceptually the incoming stream is treated simply as the concatenation
* of its elements.
*
* The outgoing stream provides chunks corresponding to the results of the
* standard string split() operation (even if such a chunk spanned incoming
* chunks). The separators are not included.
*
* A typical usage is to split a text file (represented as a stream with
* arbitrary chunk boundaries) into lines.
*
* @param upstream A readable stream of strings that can be treated as
* concatenated.
* @param separator A character to split on.
*/
split(separator) {
return new SplitIterator(this, separator);
}
}
// ============================================================================
// The following private classes serve to implement the chainable methods
// on StringIterator. Unfortunately they can't be placed in separate files, due
// to resulting trouble with circular imports.
// ============================================================================
// We wanted multiple inheritance, e.g.
// class SplitIterator extends QueueIterator<string>, StringIterator
// but the TypeScript mixin approach is a bit hacky, so we take this adapter
// approach instead.
class SplitIterator extends StringIterator {
constructor(upstream, separator) {
super();
this.upstream = upstream;
this.impl = new SplitIteratorImpl(upstream, separator);
}
summary() {
return this.impl.summary();
}
async next() {
return this.impl.next();
}
}
class SplitIteratorImpl extends _lazy_iterator__WEBPACK_IMPORTED_MODULE_0__[
/* OneToManyIterator */ "b"
] {
constructor(upstream, separator) {
super();
this.upstream = upstream;
this.separator = separator;
// A partial string at the end of an upstream chunk
this.carryover = "";
}
summary() {
return `${this.upstream.summary()} -> Split('${this.separator}')`;
}
async pump() {
const chunkResult = await this.upstream.next();
if (chunkResult.done) {
if (this.carryover === "") {
return false;
}
// Pretend that the pump succeeded in order to emit the small last batch.
// The next pump() call will actually fail.
this.outputQueue.push(this.carryover);
this.carryover = "";
return true;
}
const lines = chunkResult.value.split(this.separator);
// Note the behavior: " ab ".split(' ') === ['', 'ab', '']
// Thus the carryover may be '' if the separator falls on a chunk
// boundary; this produces the correct result.
lines[0] = this.carryover + lines[0];
for (const line of lines.slice(0, -1)) {
this.outputQueue.push(line);
}
this.carryover = lines[lines.length - 1];
return true;
}
}
//# sourceMappingURL=string_iterator.js.map
/***/
},
/* 59 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const blazeface = __webpack_require__(81);
const tfconv = __webpack_require__(38);
const tf = __webpack_require__(0);
const keypoints_1 = __webpack_require__(82);
const pipeline_1 = __webpack_require__(83);
const uv_coords_1 = __webpack_require__(85);
const FACEMESH_GRAPHMODEL_PATH =
"https://tfhub.dev/mediapipe/tfjs-model/facemesh/1/default/1";
const MESH_MODEL_INPUT_WIDTH = 192;
const MESH_MODEL_INPUT_HEIGHT = 192;
async function load({
maxContinuousChecks = 5,
detectionConfidence = 0.9,
maxFaces = 10,
iouThreshold = 0.3,
scoreThreshold = 0.75,
} = {}) {
const [blazeFace, blazeMeshModel] = await Promise.all([
loadDetectorModel(maxFaces, iouThreshold, scoreThreshold),
loadMeshModel(),
]);
const faceMesh = new FaceMesh(
blazeFace,
blazeMeshModel,
maxContinuousChecks,
detectionConfidence,
maxFaces
);
return faceMesh;
}
exports.load = load;
async function loadDetectorModel(maxFaces, iouThreshold, scoreThreshold) {
return blazeface.load({ maxFaces, iouThreshold, scoreThreshold });
}
async function loadMeshModel() {
return tfconv.loadGraphModel(FACEMESH_GRAPHMODEL_PATH, { fromTFHub: true });
}
function getInputTensorDimensions(input) {
return input instanceof tf.Tensor
? [input.shape[0], input.shape[1]]
: [input.height, input.width];
}
function flipFaceHorizontal(face, imageWidth) {
if (face.mesh instanceof tf.Tensor) {
const [topLeft, bottomRight, mesh, scaledMesh] = tf.tidy(() => {
const subtractBasis = tf.tensor1d([imageWidth - 1, 0, 0]);
const multiplyBasis = tf.tensor1d([1, -1, 1]);
return tf.tidy(() => {
return [
tf.concat([
tf.sub(imageWidth - 1, face.boundingBox.topLeft.slice(0, 1)),
face.boundingBox.topLeft.slice(1, 1),
]),
tf.concat([
tf.sub(imageWidth - 1, face.boundingBox.bottomRight.slice(0, 1)),
face.boundingBox.bottomRight.slice(1, 1),
]),
tf.sub(subtractBasis, face.mesh).mul(multiplyBasis),
tf.sub(subtractBasis, face.scaledMesh).mul(multiplyBasis),
];
});
});
return Object.assign({}, face, {
boundingBox: { topLeft, bottomRight },
mesh,
scaledMesh,
});
}
return Object.assign({}, face, {
boundingBox: {
topLeft: [imageWidth - 1 - face.boundingBox.topLeft[0], face.boundingBox.topLeft[1]],
bottomRight: [
imageWidth - 1 - face.boundingBox.bottomRight[0],
face.boundingBox.bottomRight[1],
],
},
mesh: face.mesh.map((coord) => {
const flippedCoord = coord.slice(0);
flippedCoord[0] = imageWidth - 1 - coord[0];
return flippedCoord;
}),
scaledMesh: face.scaledMesh.map((coord) => {
const flippedCoord = coord.slice(0);
flippedCoord[0] = imageWidth - 1 - coord[0];
return flippedCoord;
}),
});
}
class FaceMesh {
constructor(blazeFace, blazeMeshModel, maxContinuousChecks, detectionConfidence, maxFaces) {
this.pipeline = new pipeline_1.Pipeline(
blazeFace,
blazeMeshModel,
MESH_MODEL_INPUT_WIDTH,
MESH_MODEL_INPUT_HEIGHT,
maxContinuousChecks,
maxFaces
);
this.detectionConfidence = detectionConfidence;
}
static getAnnotations() {
return keypoints_1.MESH_ANNOTATIONS;
}
static getUVCoords() {
return uv_coords_1.UV_COORDS;
}
async estimateFaces(input, returnTensors = false, flipHorizontal = false) {
const [, width] = getInputTensorDimensions(input);
const image = tf.tidy(() => {
if (!(input instanceof tf.Tensor)) {
input = tf.browser.fromPixels(input);
}
return input.toFloat().expandDims(0);
});
const savedWebglPackDepthwiseConvFlag = tf.env().get("WEBGL_PACK_DEPTHWISECONV");
tf.env().set("WEBGL_PACK_DEPTHWISECONV", true);
const predictions = await this.pipeline.predict(image);
tf.env().set("WEBGL_PACK_DEPTHWISECONV", savedWebglPackDepthwiseConvFlag);
image.dispose();
if (predictions != null && predictions.length > 0) {
return Promise.all(
predictions.map(async (prediction, i) => {
const { coords, scaledCoords, box, flag } = prediction;
let tensorsToRead = [flag];
if (!returnTensors) {
tensorsToRead = tensorsToRead.concat([
coords,
scaledCoords,
box.startPoint,
box.endPoint,
]);
}
const tensorValues = await Promise.all(tensorsToRead.map(async (d) => d.array()));
const flagValue = tensorValues[0];
flag.dispose();
if (flagValue < this.detectionConfidence) {
this.pipeline.clearRegionOfInterest(i);
}
if (returnTensors) {
const annotatedPrediction = {
faceInViewConfidence: flagValue,
mesh: coords,
scaledMesh: scaledCoords,
boundingBox: {
topLeft: box.startPoint.squeeze(),
bottomRight: box.endPoint.squeeze(),
},
};
if (flipHorizontal) {
return flipFaceHorizontal(annotatedPrediction, width);
}
return annotatedPrediction;
}
const [coordsArr, coordsArrScaled, topLeft, bottomRight] = tensorValues.slice(1);
scaledCoords.dispose();
coords.dispose();
let annotatedPrediction = {
faceInViewConfidence: flagValue,
boundingBox: { topLeft, bottomRight },
mesh: coordsArr,
scaledMesh: coordsArrScaled,
};
if (flipHorizontal) {
annotatedPrediction = flipFaceHorizontal(annotatedPrediction, width);
}
const annotations = {};
for (const key in keypoints_1.MESH_ANNOTATIONS) {
annotations[key] = keypoints_1.MESH_ANNOTATIONS[key].map(
(index) => annotatedPrediction.scaledMesh[index]
);
}
annotatedPrediction["annotations"] = annotations;
return annotatedPrediction;
})
);
}
return [];
}
}
exports.FaceMesh = FaceMesh;
//# sourceMappingURL=index.js.map
/***/
},
/* 60 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tfjsCore = __webpack_require__(0);
var tfjsLayers = __webpack_require__(87);
var tfjsConverter = __webpack_require__(38);
var tfjsData = __webpack_require__(88);
var tfjsBackendCpu = __webpack_require__(89);
var tfjsBackendWebgl = __webpack_require__(86);
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
var version = "2.0.1";
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var version$1 = {
"tfjs-core": tfjsCore.version_core,
"tfjs-backend-cpu": tfjsBackendCpu.version_cpu,
"tfjs-backend-webgl": tfjsBackendWebgl.version_webgl,
"tfjs-data": tfjsData.version_data,
"tfjs-layers": tfjsLayers.version_layers,
"tfjs-converter": tfjsConverter.version_converter,
tfjs: version,
};
Object.keys(tfjsCore).forEach(function (k) {
if (k !== "default")
Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsCore[k];
},
});
});
Object.keys(tfjsLayers).forEach(function (k) {
if (k !== "default")
Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsLayers[k];
},
});
});
Object.keys(tfjsConverter).forEach(function (k) {
if (k !== "default")
Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsConverter[k];
},
});
});
exports.data = tfjsData;
exports.version = version$1;
//# sourceMappingURL=tf.node.js.map
/***/
},
/* 61 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (process) {
/* harmony import */ var _device_util__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(36);
/* harmony import */ var _environment__WEBPACK_IMPORTED_MODULE_1__ =
__webpack_require__(10);
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ENV = Object(_environment__WEBPACK_IMPORTED_MODULE_1__[/* env */ "c"])();
/**
* This file contains environment-related flag registrations.
*/
/** Whether to enable debug mode. */
ENV.registerFlag(
"DEBUG",
() => false,
(debugValue) => {
if (debugValue) {
console.warn(
"Debugging mode is ON. The output of every math call will " +
"be downloaded to CPU and checked for NaNs. " +
"This significantly impacts performance."
);
}
}
);
/** Whether we are in a browser (as versus, say, node.js) environment. */
ENV.registerFlag("IS_BROWSER", () =>
_device_util__WEBPACK_IMPORTED_MODULE_0__["isBrowser"]()
);
/** Whether we are in a browser (as versus, say, node.js) environment. */
ENV.registerFlag(
"IS_NODE",
() =>
typeof process !== "undefined" &&
typeof process.versions !== "undefined" &&
typeof process.versions.node !== "undefined"
);
/** Whether this browser is Chrome. */
ENV.registerFlag(
"IS_CHROME",
() =>
typeof navigator !== "undefined" &&
navigator != null &&
navigator.userAgent != null &&
/Chrome/.test(navigator.userAgent) &&
/Google Inc/.test(navigator.vendor)
);
/**
* True when the environment is "production" where we disable safety checks
* to gain performance.
*/
ENV.registerFlag("PROD", () => false);
/**
* Whether to do sanity checks when inferring a shape from user-provided
* values, used when creating a new tensor.
*/
ENV.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => ENV.getBool("DEBUG"));
/** Whether deprecation warnings are enabled. */
ENV.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true);
/** True if running unit tests. */
ENV.registerFlag("IS_TEST", () => false);
//# sourceMappingURL=flags.js.map
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(35)));
/***/
},
/* 62 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (process) {
/* unused harmony export getNodeFetch */
/* unused harmony export resetSystemFetch */
/* unused harmony export setSystemFetch */
/* unused harmony export getSystemFetch */
/* unused harmony export PlatformNode */
/* harmony import */ var _environment__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(10);
/**
* @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.
* =============================================================================
*/
// We are wrapping this within an object so it can be stubbed by Jasmine.
const getNodeFetch = {
// tslint:disable-next-line:no-require-imports
importFetch: () => __webpack_require__(63),
};
let systemFetch;
// These getters and setters are for testing so we don't export a mutable
// variable.
function resetSystemFetch() {
systemFetch = null;
}
function setSystemFetch(fetchFn) {
systemFetch = fetchFn;
}
function getSystemFetch() {
return systemFetch;
}
class PlatformNode {
constructor() {
// tslint:disable-next-line:no-require-imports
this.util = __webpack_require__(64);
// According to the spec, the built-in encoder can do only UTF-8 encoding.
// https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder
this.textEncoder = new this.util.TextEncoder();
}
fetch(path, requestInits) {
if (
Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().global.fetch !=
null
) {
return Object(
_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"]
)().global.fetch(path, requestInits);
}
if (systemFetch == null) {
systemFetch = getNodeFetch.importFetch();
}
return systemFetch(path, requestInits);
}
now() {
const time = process.hrtime();
return time[0] * 1000 + time[1] / 1000000;
}
encode(text, encoding) {
if (encoding !== "utf-8" && encoding !== "utf8") {
throw new Error(`Node built-in encoder only supports utf-8, but got ${encoding}`);
}
return this.textEncoder.encode(text);
}
decode(bytes, encoding) {
if (bytes.length === 0) {
return "";
}
return new this.util.TextDecoder(encoding).decode(bytes);
}
}
if (Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().get("IS_NODE")) {
Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().setPlatform(
"node",
new PlatformNode()
);
}
//# sourceMappingURL=platform_node.js.map
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(35)));
/***/
},
/* 63 */
/***/ function (module, exports) {
/* (ignored) */
/***/
},
/* 64 */
/***/ function (module, exports) {
/* (ignored) */
/***/
},
/* 65 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
exports.byteLength = byteLength;
exports.toByteArray = toByteArray;
exports.fromByteArray = fromByteArray;
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup["-".charCodeAt(0)] = 62;
revLookup["_".charCodeAt(0)] = 63;
function getLens(b64) {
var len = b64.length;
if (len % 4 > 0) {
throw new Error("Invalid string. Length must be a multiple of 4");
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf("=");
if (validLen === -1) validLen = len;
var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4);
return [validLen, placeHoldersLen];
}
// base64 is 4/3 + up to two characters of the original data
function byteLength(b64) {
var lens = getLens(b64);
var validLen = lens[0];
var placeHoldersLen = lens[1];
return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;
}
function _byteLength(b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;
}
function toByteArray(b64) {
var tmp;
var lens = getLens(b64);
var validLen = lens[0];
var placeHoldersLen = lens[1];
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
var curByte = 0;
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
var i;
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)];
arr[curByte++] = (tmp >> 16) & 0xff;
arr[curByte++] = (tmp >> 8) & 0xff;
arr[curByte++] = tmp & 0xff;
}
if (placeHoldersLen === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
arr[curByte++] = tmp & 0xff;
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2);
arr[curByte++] = (tmp >> 8) & 0xff;
arr[curByte++] = tmp & 0xff;
}
return arr;
}
function tripletToBase64(num) {
return (
lookup[(num >> 18) & 0x3f] +
lookup[(num >> 12) & 0x3f] +
lookup[(num >> 6) & 0x3f] +
lookup[num & 0x3f]
);
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xff0000) + ((uint8[i + 1] << 8) & 0xff00) + (uint8[i + 2] & 0xff);
output.push(tripletToBase64(tmp));
}
return output.join("");
}
function fromByteArray(uint8) {
var tmp;
var len = uint8.length;
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
var parts = [];
var maxChunkLength = 16383; // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
parts.push(lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3f] + "==");
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
parts.push(
lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3f] + lookup[(tmp << 2) & 0x3f] + "="
);
}
return parts.join("");
}
/***/
},
/* 66 */
/***/ function (module, exports) {
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & ((1 << -nBits) - 1);
s >>= -nBits;
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << -nBits) - 1);
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : (s ? -1 : 1) * Infinity;
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128;
};
/***/
},
/* 67 */
/***/ function (module, exports) {
var toString = {}.toString;
module.exports =
Array.isArray ||
function (arr) {
return toString.call(arr) == "[object Array]";
};
/***/
},
/* 68 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var __WEBPACK_AMD_DEFINE_RESULT__; // A port of an algorithm by Johannes Baagøe <baagoe@baagoe.com>, 2010
// http://baagoe.com/en/RandomMusings/javascript/
// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
// Original work is under MIT license -
// Copyright (C) 2010 by Johannes Baagøe <baagoe@baagoe.org>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
(function (global, module, define) {
function Alea(seed) {
var me = this,
mash = Mash();
me.next = function () {
var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32
me.s0 = me.s1;
me.s1 = me.s2;
return (me.s2 = t - (me.c = t | 0));
};
// Apply the seeding algorithm from Baagoe.
me.c = 1;
me.s0 = mash(" ");
me.s1 = mash(" ");
me.s2 = mash(" ");
me.s0 -= mash(seed);
if (me.s0 < 0) {
me.s0 += 1;
}
me.s1 -= mash(seed);
if (me.s1 < 0) {
me.s1 += 1;
}
me.s2 -= mash(seed);
if (me.s2 < 0) {
me.s2 += 1;
}
mash = null;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function impl(seed, opts) {
var xg = new Alea(seed),
state = opts && opts.state,
prng = xg.next;
prng.int32 = function () {
return (xg.next() * 0x100000000) | 0;
};
prng.double = function () {
return prng() + ((prng() * 0x200000) | 0) * 1.1102230246251565e-16; // 2^-53
};
prng.quick = prng;
if (state) {
if (typeof state == "object") copy(state, xg);
prng.state = function () {
return copy(xg, {});
};
}
return prng;
}
function Mash() {
var n = 0xefc8249d;
var mash = function (data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(16) && __webpack_require__(29)) {
!((__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return impl;
}.call(exports, __webpack_require__, exports, module)),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined &&
(module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.alea = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(16) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(28)(module)));
/***/
},
/* 69 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var __WEBPACK_AMD_DEFINE_RESULT__; // A Javascript implementaion of the "xor128" prng algorithm by
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
(function (global, module, define) {
function XorGen(seed) {
var me = this,
strseed = "";
me.x = 0;
me.y = 0;
me.z = 0;
me.w = 0;
// Set up generator function.
me.next = function () {
var t = me.x ^ (me.x << 11);
me.x = me.y;
me.y = me.z;
me.z = me.w;
return (me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8));
};
if (seed === (seed | 0)) {
// Integer seed.
me.x = seed;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 64; k++) {
me.x ^= strseed.charCodeAt(k) | 0;
me.next();
}
}
function copy(f, t) {
t.x = f.x;
t.y = f.y;
t.z = f.z;
t.w = f.w;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function () {
return (xg.next() >>> 0) / 0x100000000;
};
prng.double = function () {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof state == "object") copy(state, xg);
prng.state = function () {
return copy(xg, {});
};
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(16) && __webpack_require__(29)) {
!((__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return impl;
}.call(exports, __webpack_require__, exports, module)),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined &&
(module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.xor128 = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(16) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(28)(module)));
/***/
},
/* 70 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var __WEBPACK_AMD_DEFINE_RESULT__; // A Javascript implementaion of the "xorwow" prng algorithm by
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
(function (global, module, define) {
function XorGen(seed) {
var me = this,
strseed = "";
// Set up generator function.
me.next = function () {
var t = me.x ^ (me.x >>> 2);
me.x = me.y;
me.y = me.z;
me.z = me.w;
me.w = me.v;
return (
((me.d = (me.d + 362437) | 0) + (me.v = me.v ^ (me.v << 4) ^ (t ^ (t << 1)))) | 0
);
};
me.x = 0;
me.y = 0;
me.z = 0;
me.w = 0;
me.v = 0;
if (seed === (seed | 0)) {
// Integer seed.
me.x = seed;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 64; k++) {
me.x ^= strseed.charCodeAt(k) | 0;
if (k == strseed.length) {
me.d = (me.x << 10) ^ (me.x >>> 4);
}
me.next();
}
}
function copy(f, t) {
t.x = f.x;
t.y = f.y;
t.z = f.z;
t.w = f.w;
t.v = f.v;
t.d = f.d;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function () {
return (xg.next() >>> 0) / 0x100000000;
};
prng.double = function () {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof state == "object") copy(state, xg);
prng.state = function () {
return copy(xg, {});
};
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(16) && __webpack_require__(29)) {
!((__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return impl;
}.call(exports, __webpack_require__, exports, module)),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined &&
(module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.xorwow = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(16) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(28)(module)));
/***/
},
/* 71 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var __WEBPACK_AMD_DEFINE_RESULT__; // A Javascript implementaion of the "xorshift7" algorithm by
// François Panneton and Pierre L'ecuyer:
// "On the Xorgshift Random Number Generators"
// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf
(function (global, module, define) {
function XorGen(seed) {
var me = this;
// Set up generator function.
me.next = function () {
// Update xor generator.
var X = me.x,
i = me.i,
t,
v,
w;
t = X[i];
t ^= t >>> 7;
v = t ^ (t << 24);
t = X[(i + 1) & 7];
v ^= t ^ (t >>> 10);
t = X[(i + 3) & 7];
v ^= t ^ (t >>> 3);
t = X[(i + 4) & 7];
v ^= t ^ (t << 7);
t = X[(i + 7) & 7];
t = t ^ (t << 13);
v ^= t ^ (t << 9);
X[i] = v;
me.i = (i + 1) & 7;
return v;
};
function init(me, seed) {
var j,
w,
X = [];
if (seed === (seed | 0)) {
// Seed state array using a 32-bit integer.
w = X[0] = seed;
} else {
// Seed state using a string.
seed = "" + seed;
for (j = 0; j < seed.length; ++j) {
X[j & 7] = (X[j & 7] << 15) ^ ((seed.charCodeAt(j) + X[(j + 1) & 7]) << 13);
}
}
// Enforce an array length of 8, not all zeroes.
while (X.length < 8) X.push(0);
for (j = 0; j < 8 && X[j] === 0; ++j);
if (j == 8) w = X[7] = -1;
else w = X[j];
me.x = X;
me.i = 0;
// Discard an initial 256 values.
for (j = 256; j > 0; --j) {
me.next();
}
}
init(me, seed);
}
function copy(f, t) {
t.x = f.x.slice();
t.i = f.i;
return t;
}
function impl(seed, opts) {
if (seed == null) seed = +new Date();
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function () {
return (xg.next() >>> 0) / 0x100000000;
};
prng.double = function () {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (state.x) copy(state, xg);
prng.state = function () {
return copy(xg, {});
};
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(16) && __webpack_require__(29)) {
!((__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return impl;
}.call(exports, __webpack_require__, exports, module)),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined &&
(module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.xorshift7 = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(16) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(28)(module)));
/***/
},
/* 72 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var __WEBPACK_AMD_DEFINE_RESULT__; // A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.
//
// This fast non-cryptographic random number generator is designed for
// use in Monte-Carlo algorithms. It combines a long-period xorshift
// generator with a Weyl generator, and it passes all common batteries
// of stasticial tests for randomness while consuming only a few nanoseconds
// for each prng generated. For background on the generator, see Brent's
// paper: "Some long-period random number generators using shifts and xors."
// http://arxiv.org/pdf/1004.3115v1.pdf
//
// Usage:
//
// var xor4096 = require('xor4096');
// random = xor4096(1); // Seed with int32 or string.
// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.
// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.
//
// For nonzero numeric keys, this impelementation provides a sequence
// identical to that by Brent's xorgens 3 implementaion in C. This
// implementation also provides for initalizing the generator with
// string seeds, or for saving and restoring the state of the generator.
//
// On Chrome, this prng benchmarks about 2.1 times slower than
// Javascript's built-in Math.random().
(function (global, module, define) {
function XorGen(seed) {
var me = this;
// Set up generator function.
me.next = function () {
var w = me.w,
X = me.X,
i = me.i,
t,
v;
// Update Weyl generator.
me.w = w = (w + 0x61c88647) | 0;
// Update xor generator.
v = X[(i + 34) & 127];
t = X[(i = (i + 1) & 127)];
v ^= v << 13;
t ^= t << 17;
v ^= v >>> 15;
t ^= t >>> 12;
// Update Xor generator array state.
v = X[i] = v ^ t;
me.i = i;
// Result is the combination.
return (v + (w ^ (w >>> 16))) | 0;
};
function init(me, seed) {
var t,
v,
i,
j,
w,
X = [],
limit = 128;
if (seed === (seed | 0)) {
// Numeric seeds initialize v, which is used to generates X.
v = seed;
seed = null;
} else {
// String seeds are mixed into v and X one character at a time.
seed = seed + "\0";
v = 0;
limit = Math.max(limit, seed.length);
}
// Initialize circular array and weyl value.
for (i = 0, j = -32; j < limit; ++j) {
// Put the unicode characters into the array, and shuffle them.
if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);
// After 32 shuffles, take v as the starting w value.
if (j === 0) w = v;
v ^= v << 10;
v ^= v >>> 15;
v ^= v << 4;
v ^= v >>> 13;
if (j >= 0) {
w = (w + 0x61c88647) | 0; // Weyl.
t = X[j & 127] ^= v + w; // Combine xor and weyl to init array.
i = 0 == t ? i + 1 : 0; // Count zeroes.
}
}
// We have detected all zeroes; make the key nonzero.
if (i >= 128) {
X[((seed && seed.length) || 0) & 127] = -1;
}
// Run the generator 512 times to further mix the state before using it.
// Factoring this as a function slows the main generator, so it is just
// unrolled here. The weyl generator is not advanced while warming up.
i = 127;
for (j = 4 * 128; j > 0; --j) {
v = X[(i + 34) & 127];
t = X[(i = (i + 1) & 127)];
v ^= v << 13;
t ^= t << 17;
v ^= v >>> 15;
t ^= t >>> 12;
X[i] = v ^ t;
}
// Storing state as object members is faster than using closure variables.
me.w = w;
me.X = X;
me.i = i;
}
init(me, seed);
}
function copy(f, t) {
t.i = f.i;
t.w = f.w;
t.X = f.X.slice();
return t;
}
function impl(seed, opts) {
if (seed == null) seed = +new Date();
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function () {
return (xg.next() >>> 0) / 0x100000000;
};
prng.double = function () {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (state.X) copy(state, xg);
prng.state = function () {
return copy(xg, {});
};
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(16) && __webpack_require__(29)) {
!((__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return impl;
}.call(exports, __webpack_require__, exports, module)),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined &&
(module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.xor4096 = impl;
}
})(
this, // window object or global
true && module, // present in node.js
__webpack_require__(16) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(28)(module)));
/***/
},
/* 73 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var __WEBPACK_AMD_DEFINE_RESULT__; // A Javascript implementaion of the "Tyche-i" prng algorithm by
// Samuel Neves and Filipe Araujo.
// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
(function (global, module, define) {
function XorGen(seed) {
var me = this,
strseed = "";
// Set up generator function.
me.next = function () {
var b = me.b,
c = me.c,
d = me.d,
a = me.a;
b = (b << 25) ^ (b >>> 7) ^ c;
c = (c - d) | 0;
d = (d << 24) ^ (d >>> 8) ^ a;
a = (a - b) | 0;
me.b = b = (b << 20) ^ (b >>> 12) ^ c;
me.c = c = (c - d) | 0;
me.d = (d << 16) ^ (c >>> 16) ^ a;
return (me.a = (a - b) | 0);
};
/* The following is non-inverted tyche, which has better internal
* bit diffusion, but which is about 25% slower than tyche-i in JS.
me.next = function() {
var a = me.a, b = me.b, c = me.c, d = me.d;
a = (me.a + me.b | 0) >>> 0;
d = me.d ^ a; d = d << 16 ^ d >>> 16;
c = me.c + d | 0;
b = me.b ^ c; b = b << 12 ^ d >>> 20;
me.a = a = a + b | 0;
d = d ^ a; me.d = d = d << 8 ^ d >>> 24;
me.c = c = c + d | 0;
b = b ^ c;
return me.b = (b << 7 ^ b >>> 25);
}
*/
me.a = 0;
me.b = 0;
me.c = 2654435769 | 0;
me.d = 1367130551;
if (seed === Math.floor(seed)) {
// Integer seed.
me.a = (seed / 0x100000000) | 0;
me.b = seed | 0;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 20; k++) {
me.b ^= strseed.charCodeAt(k) | 0;
me.next();
}
}
function copy(f, t) {
t.a = f.a;
t.b = f.b;
t.c = f.c;
t.d = f.d;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function () {
return (xg.next() >>> 0) / 0x100000000;
};
prng.double = function () {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof state == "object") copy(state, xg);
prng.state = function () {
return copy(xg, {});
};
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(16) && __webpack_require__(29)) {
!((__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return impl;
}.call(exports, __webpack_require__, exports, module)),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined &&
(module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.tychei = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(16) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(28)(module)));
/***/
},
/* 74 */
/***/ function (module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__; /*
Copyright 2014 David Bau.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function (pool, math) {
//
// The following constants are related to IEEE 754 limits.
//
var global = this,
width = 256, // each RC4 output is 0 <= x < 256
chunks = 6, // at least six RC4 outputs for each double
digits = 52, // there are 52 significant digits in a double
rngname = "random", // rngname: name for Math.random and Math.seedrandom
startdenom = math.pow(width, chunks),
significance = math.pow(2, digits),
overflow = significance * 2,
mask = width - 1,
nodecrypto; // node.js crypto module, initialized at the bottom.
//
// seedrandom()
// This is the seedrandom function described above.
//
function seedrandom(seed, options, callback) {
var key = [];
options = options == true ? { entropy: true } : options || {};
// Flatten the seed string or build one from local entropy if needed.
var shortseed = mixkey(
flatten(options.entropy ? [seed, tostring(pool)] : seed == null ? autoseed() : seed, 3),
key
);
// Use the seed to initialize an ARC4 generator.
var arc4 = new ARC4(key);
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
var prng = function () {
var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
d = startdenom, // and denominator d = 2 ^ 48.
x = 0; // and no 'extra last byte'.
while (n < significance) {
// Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) {
// To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
prng.int32 = function () {
return arc4.g(4) | 0;
};
prng.quick = function () {
return arc4.g(4) / 0x100000000;
};
prng.double = prng;
// Mix the randomness into accumulated entropy.
mixkey(tostring(arc4.S), pool);
// Calling convention: what to return as a function of prng, seed, is_math.
return (
options.pass ||
callback ||
function (prng, seed, is_math_call, state) {
if (state) {
// Load the arc4 state from the given state if it has an S array.
if (state.S) {
copy(state, arc4);
}
// Only provide the .state method if requested via options.state.
prng.state = function () {
return copy(arc4, {});
};
}
// If called as a method of Math (Math.seedrandom()), mutate
// Math.random because that is how seedrandom.js has worked since v1.0.
if (is_math_call) {
math[rngname] = prng;
return seed;
}
// Otherwise, it is a newer calling convention, so return the
// prng directly.
else return prng;
}
)(prng, shortseed, "global" in options ? options.global : this == math, options.state);
}
math["seed" + rngname] = seedrandom;
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
function ARC4(key) {
var t,
keylen = key.length,
me = this,
i = 0,
j = (me.i = me.j = 0),
s = (me.S = []);
// The empty key [] is treated as [0].
if (!keylen) {
key = [keylen++];
}
// Set up S using the standard key scheduling algorithm.
while (i < width) {
s[i] = i++;
}
for (i = 0; i < width; i++) {
s[i] = s[(j = mask & (j + key[i % keylen] + (t = s[i])))];
s[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
(me.g = function (count) {
// Using instance members instead of closure state nearly doubles speed.
var t,
r = 0,
i = me.i,
j = me.j,
s = me.S;
while (count--) {
t = s[(i = mask & (i + 1))];
r = r * width + s[mask & ((s[i] = s[(j = mask & (j + t))]) + (s[j] = t))];
}
me.i = i;
me.j = j;
return r;
// For robust unpredictability, the function call below automatically
// discards an initial batch of values. This is called RC4-drop[256].
// See http://google.com/search?q=rsa+fluhrer+response&btnI
})(width);
}
//
// copy()
// Copies internal state of ARC4 to or from a plain object.
//
function copy(f, t) {
t.i = f.i;
t.j = f.j;
t.S = f.S.slice();
return t;
}
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
function flatten(obj, depth) {
var result = [],
typ = typeof obj,
prop;
if (depth && typ == "object") {
for (prop in obj) {
try {
result.push(flatten(obj[prop], depth - 1));
} catch (e) {}
}
}
return result.length ? result : typ == "string" ? obj : obj + "\0";
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
function mixkey(seed, key) {
var stringseed = seed + "",
smear,
j = 0;
while (j < stringseed.length) {
key[mask & j] = mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
}
return tostring(key);
}
//
// autoseed()
// Returns an object for autoseeding, using window.crypto and Node crypto
// module if available.
//
function autoseed() {
try {
var out;
if (nodecrypto && (out = nodecrypto.randomBytes)) {
// The use of 'out' to remember randomBytes makes tight minified code.
out = out(width);
} else {
out = new Uint8Array(width);
(global.crypto || global.msCrypto).getRandomValues(out);
}
return tostring(out);
} catch (e) {
var browser = global.navigator,
plugins = browser && browser.plugins;
return [+new Date(), global, plugins, global.screen, tostring(pool)];
}
}
//
// tostring()
// Converts an array of charcodes to a string
//
function tostring(a) {
return String.fromCharCode.apply(0, a);
}
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to interfere with deterministic PRNG state later,
// seedrandom will not call math.random on its own again after
// initialization.
//
mixkey(math.random(), pool);
//
// Nodejs and AMD support: export the implementation as a module using
// either convention.
//
if (true && module.exports) {
module.exports = seedrandom;
// When in node.js, try using crypto package for autoseeding.
try {
nodecrypto = __webpack_require__(75);
} catch (ex) {}
} else if (true) {
!((__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return seedrandom;
}.call(exports, __webpack_require__, exports, module)),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined &&
(module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
// End anonymous scope, and pass initial values.
})(
[], // pool: entropy pool starts empty
Math // math: package containing random, pow, and seedrandom
);
/***/
},
/* 75 */
/***/ function (module, exports) {
/* (ignored) */
/***/
},
/* 76 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (global) {
var scope =
(typeof global !== "undefined" && global) ||
(typeof self !== "undefined" && self) ||
window;
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function () {
return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function () {
return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout = exports.clearInterval = function (timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function () {};
Timeout.prototype.close = function () {
this._clearFn.call(scope, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function (item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function (item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function (item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout) item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(77);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate =
(typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate =
(typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(27)));
/***/
},
/* 77 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (global, process) {
(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function (handle) {
process.nextTick(function () {
runIfPresent(handle);
});
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function () {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function (event) {
if (
event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0
) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function (handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function (event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function (handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function (handle) {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var script = doc.createElement("script");
script.onreadystatechange = function () {
runIfPresent(handle);
script.onreadystatechange = null;
html.removeChild(script);
script = null;
};
html.appendChild(script);
};
}
function installSetTimeoutImplementation() {
registerImmediate = function (handle) {
setTimeout(runIfPresent, 0, handle);
};
}
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
// Don't get fooled by e.g. browserify environments.
if ({}.toString.call(global.process) === "[object process]") {
// For Node.js before 0.9
installNextTickImplementation();
} else if (canUsePostMessage()) {
// For non-IE10 modern browsers
installPostMessageImplementation();
} else if (global.MessageChannel) {
// For web workers, where supported
installMessageChannelImplementation();
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
// For IE 68
installReadyStateChangeImplementation();
} else {
// For older browsers
installSetTimeoutImplementation();
}
attachTo.setImmediate = setImmediate;
attachTo.clearImmediate = clearImmediate;
})(typeof self === "undefined" ? (typeof global === "undefined" ? this : global) : self);
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(27), __webpack_require__(35)));
/***/
},
/* 78 */
/***/ function (module, exports) {
/* (ignored) */
/***/
},
/* 79 */
/***/ function (module, exports) {
/* (ignored) */
/***/
},
/* 80 */
/***/ function (module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__,
__WEBPACK_AMD_DEFINE_ARRAY__,
__WEBPACK_AMD_DEFINE_RESULT__;
(function (global, factory) {
if (true) {
!((__WEBPACK_AMD_DEFINE_ARRAY__ = [module]),
(__WEBPACK_AMD_DEFINE_FACTORY__ = factory),
(__WEBPACK_AMD_DEFINE_RESULT__ =
typeof __WEBPACK_AMD_DEFINE_FACTORY__ === "function"
? __WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)
: __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined &&
(module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
var mod;
}
})(this, function (module) {
"use strict";
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
var _extends =
Object.assign ||
function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return Array.from(arr);
}
}
var DEFAULT_OPTIONS = { order: 2, precision: 2, period: null };
/**
* Determine the coefficient of determination (r^2) of a fit from the observations
* and predictions.
*
* @param {Array<Array<number>>} data - Pairs of observed x-y values
* @param {Array<Array<number>>} results - Pairs of observed predicted x-y values
*
* @return {number} - The r^2 value, or NaN if one cannot be calculated.
*/
function determinationCoefficient(data, results) {
var predictions = [];
var observations = [];
data.forEach(function (d, i) {
if (d[1] !== null) {
observations.push(d);
predictions.push(results[i]);
}
});
var sum = observations.reduce(function (a, observation) {
return a + observation[1];
}, 0);
var mean = sum / observations.length;
var ssyy = observations.reduce(function (a, observation) {
var difference = observation[1] - mean;
return a + difference * difference;
}, 0);
var sse = observations.reduce(function (accum, observation, index) {
var prediction = predictions[index];
var residual = observation[1] - prediction[1];
return accum + residual * residual;
}, 0);
return 1 - sse / ssyy;
}
/**
* Determine the solution of a system of linear equations A * x = b using
* Gaussian elimination.
*
* @param {Array<Array<number>>} input - A 2-d matrix of data in row-major form [ A | b ]
* @param {number} order - How many degrees to solve for
*
* @return {Array<number>} - Vector of normalized solution coefficients matrix (x)
*/
function gaussianElimination(input, order) {
var matrix = input;
var n = input.length - 1;
var coefficients = [order];
for (var i = 0; i < n; i++) {
var maxrow = i;
for (var j = i + 1; j < n; j++) {
if (Math.abs(matrix[i][j]) > Math.abs(matrix[i][maxrow])) {
maxrow = j;
}
}
for (var k = i; k < n + 1; k++) {
var tmp = matrix[k][i];
matrix[k][i] = matrix[k][maxrow];
matrix[k][maxrow] = tmp;
}
for (var _j = i + 1; _j < n; _j++) {
for (var _k = n; _k >= i; _k--) {
matrix[_k][_j] -= (matrix[_k][i] * matrix[i][_j]) / matrix[i][i];
}
}
}
for (var _j2 = n - 1; _j2 >= 0; _j2--) {
var total = 0;
for (var _k2 = _j2 + 1; _k2 < n; _k2++) {
total += matrix[_k2][_j2] * coefficients[_k2];
}
coefficients[_j2] = (matrix[n][_j2] - total) / matrix[_j2][_j2];
}
return coefficients;
}
/**
* Round a number to a precision, specificed in number of decimal places
*
* @param {number} number - The number to round
* @param {number} precision - The number of decimal places to round to:
* > 0 means decimals, < 0 means powers of 10
*
*
* @return {numbr} - The number, rounded
*/
function round(number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
/**
* The set of all fitting methods
*
* @namespace
*/
var methods = {
linear: function linear(data, options) {
var sum = [0, 0, 0, 0, 0];
var len = 0;
for (var n = 0; n < data.length; n++) {
if (data[n][1] !== null) {
len++;
sum[0] += data[n][0];
sum[1] += data[n][1];
sum[2] += data[n][0] * data[n][0];
sum[3] += data[n][0] * data[n][1];
sum[4] += data[n][1] * data[n][1];
}
}
var run = len * sum[2] - sum[0] * sum[0];
var rise = len * sum[3] - sum[0] * sum[1];
var gradient = run === 0 ? 0 : round(rise / run, options.precision);
var intercept = round(sum[1] / len - (gradient * sum[0]) / len, options.precision);
var predict = function predict(x) {
return [
round(x, options.precision),
round(gradient * x + intercept, options.precision),
];
};
var points = data.map(function (point) {
return predict(point[0]);
});
return {
points: points,
predict: predict,
equation: [gradient, intercept],
r2: round(determinationCoefficient(data, points), options.precision),
string:
intercept === 0 ? "y = " + gradient + "x" : "y = " + gradient + "x + " + intercept,
};
},
exponential: function exponential(data, options) {
var sum = [0, 0, 0, 0, 0, 0];
for (var n = 0; n < data.length; n++) {
if (data[n][1] !== null) {
sum[0] += data[n][0];
sum[1] += data[n][1];
sum[2] += data[n][0] * data[n][0] * data[n][1];
sum[3] += data[n][1] * Math.log(data[n][1]);
sum[4] += data[n][0] * data[n][1] * Math.log(data[n][1]);
sum[5] += data[n][0] * data[n][1];
}
}
var denominator = sum[1] * sum[2] - sum[5] * sum[5];
var a = Math.exp((sum[2] * sum[3] - sum[5] * sum[4]) / denominator);
var b = (sum[1] * sum[4] - sum[5] * sum[3]) / denominator;
var coeffA = round(a, options.precision);
var coeffB = round(b, options.precision);
var predict = function predict(x) {
return [
round(x, options.precision),
round(coeffA * Math.exp(coeffB * x), options.precision),
];
};
var points = data.map(function (point) {
return predict(point[0]);
});
return {
points: points,
predict: predict,
equation: [coeffA, coeffB],
string: "y = " + coeffA + "e^(" + coeffB + "x)",
r2: round(determinationCoefficient(data, points), options.precision),
};
},
logarithmic: function logarithmic(data, options) {
var sum = [0, 0, 0, 0];
var len = data.length;
for (var n = 0; n < len; n++) {
if (data[n][1] !== null) {
sum[0] += Math.log(data[n][0]);
sum[1] += data[n][1] * Math.log(data[n][0]);
sum[2] += data[n][1];
sum[3] += Math.pow(Math.log(data[n][0]), 2);
}
}
var a = (len * sum[1] - sum[2] * sum[0]) / (len * sum[3] - sum[0] * sum[0]);
var coeffB = round(a, options.precision);
var coeffA = round((sum[2] - coeffB * sum[0]) / len, options.precision);
var predict = function predict(x) {
return [
round(x, options.precision),
round(round(coeffA + coeffB * Math.log(x), options.precision), options.precision),
];
};
var points = data.map(function (point) {
return predict(point[0]);
});
return {
points: points,
predict: predict,
equation: [coeffA, coeffB],
string: "y = " + coeffA + " + " + coeffB + " ln(x)",
r2: round(determinationCoefficient(data, points), options.precision),
};
},
power: function power(data, options) {
var sum = [0, 0, 0, 0, 0];
var len = data.length;
for (var n = 0; n < len; n++) {
if (data[n][1] !== null) {
sum[0] += Math.log(data[n][0]);
sum[1] += Math.log(data[n][1]) * Math.log(data[n][0]);
sum[2] += Math.log(data[n][1]);
sum[3] += Math.pow(Math.log(data[n][0]), 2);
}
}
var b = (len * sum[1] - sum[0] * sum[2]) / (len * sum[3] - Math.pow(sum[0], 2));
var a = (sum[2] - b * sum[0]) / len;
var coeffA = round(Math.exp(a), options.precision);
var coeffB = round(b, options.precision);
var predict = function predict(x) {
return [
round(x, options.precision),
round(round(coeffA * Math.pow(x, coeffB), options.precision), options.precision),
];
};
var points = data.map(function (point) {
return predict(point[0]);
});
return {
points: points,
predict: predict,
equation: [coeffA, coeffB],
string: "y = " + coeffA + "x^" + coeffB,
r2: round(determinationCoefficient(data, points), options.precision),
};
},
polynomial: function polynomial(data, options) {
var lhs = [];
var rhs = [];
var a = 0;
var b = 0;
var len = data.length;
var k = options.order + 1;
for (var i = 0; i < k; i++) {
for (var l = 0; l < len; l++) {
if (data[l][1] !== null) {
a += Math.pow(data[l][0], i) * data[l][1];
}
}
lhs.push(a);
a = 0;
var c = [];
for (var j = 0; j < k; j++) {
for (var _l = 0; _l < len; _l++) {
if (data[_l][1] !== null) {
b += Math.pow(data[_l][0], i + j);
}
}
c.push(b);
b = 0;
}
rhs.push(c);
}
rhs.push(lhs);
var coefficients = gaussianElimination(rhs, k).map(function (v) {
return round(v, options.precision);
});
var predict = function predict(x) {
return [
round(x, options.precision),
round(
coefficients.reduce(function (sum, coeff, power) {
return sum + coeff * Math.pow(x, power);
}, 0),
options.precision
),
];
};
var points = data.map(function (point) {
return predict(point[0]);
});
var string = "y = ";
for (var _i = coefficients.length - 1; _i >= 0; _i--) {
if (_i > 1) {
string += coefficients[_i] + "x^" + _i + " + ";
} else if (_i === 1) {
string += coefficients[_i] + "x + ";
} else {
string += coefficients[_i];
}
}
return {
string: string,
points: points,
predict: predict,
equation: [].concat(_toConsumableArray(coefficients)).reverse(),
r2: round(determinationCoefficient(data, points), options.precision),
};
},
};
function createWrapper() {
var reduce = function reduce(accumulator, name) {
return _extends(
{
_round: round,
},
accumulator,
_defineProperty({}, name, function (data, supplied) {
return methods[name](data, _extends({}, DEFAULT_OPTIONS, supplied));
})
);
};
return Object.keys(methods).reduce(reduce, {});
}
module.exports = createWrapper();
});
/***/
},
/* 81 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"load",
function () {
return load;
}
);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"BlazeFaceModel",
function () {
return BlazeFaceModel;
}
);
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(0);
/* harmony import */ var _tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__ =
__webpack_require__(38);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const disposeBox = (t) => {
t.startEndTensor.dispose(), t.startPoint.dispose(), t.endPoint.dispose();
},
createBox = (t) => ({
startEndTensor: t,
startPoint: Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(
t,
[0, 0],
[-1, 2]
),
endPoint: Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(
t,
[0, 2],
[-1, 2]
),
}),
scaleBox = (t, o) => {
const s = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(
t.startPoint,
o
),
e = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(t.endPoint, o),
i = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat2d"])([s, e], 1);
return createBox(i);
},
ANCHORS_CONFIG = { strides: [8, 16], anchors: [2, 6] },
NUM_LANDMARKS = 6;
function generateAnchors(t, o, s) {
const e = [];
for (let i = 0; i < s.strides.length; i++) {
const n = s.strides[i],
a = Math.floor((o + n - 1) / n),
r = Math.floor((t + n - 1) / n),
c = s.anchors[i];
for (let t = 0; t < a; t++) {
const o = n * (t + 0.5);
for (let t = 0; t < r; t++) {
const s = n * (t + 0.5);
for (let t = 0; t < c; t++) e.push([s, o]);
}
}
}
return e;
}
function decodeBounds(t, o, s) {
const e = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(
t,
[0, 1],
[-1, 2]
),
i = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(e, o),
n = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(
t,
[0, 3],
[-1, 2]
),
a = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(n, s),
r = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(i, s),
c = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(a, 2),
l = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(r, c),
d = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(r, c),
h = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(l, s),
p = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(d, s);
return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat2d"])([h, p], 1);
}
function getInputTensorDimensions(t) {
return t instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]
? [t.shape[0], t.shape[1]]
: [t.height, t.width];
}
function flipFaceHorizontal(t, o) {
let s, e, i;
if (
t.topLeft instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"] &&
t.bottomRight instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]
) {
const [n, a] = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(() => [
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])([
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(
o - 1,
t.topLeft.slice(0, 1)
),
t.topLeft.slice(1, 1),
]),
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])([
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(
o - 1,
t.bottomRight.slice(0, 1)
),
t.bottomRight.slice(1, 1),
]),
]);
(s = n),
(e = a),
null != t.landmarks &&
(i = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(() => {
const s = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([
o - 1,
0,
]),
t.landmarks
),
e = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([
1, -1,
]);
return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(s, e);
}));
} else {
const [n, a] = t.topLeft,
[r, c] = t.bottomRight;
(s = [o - 1 - n, a]),
(e = [o - 1 - r, c]),
null != t.landmarks && (i = t.landmarks.map((t) => [o - 1 - t[0], t[1]]));
}
const n = { topLeft: s, bottomRight: e };
return (
null != i && (n.landmarks = i),
null != t.probability &&
(n.probability =
t.probability instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]
? t.probability.clone()
: t.probability),
n
);
}
function scaleBoxFromPrediction(t, o) {
return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(() => {
let s;
return (s = t.hasOwnProperty("box") ? t.box : t), scaleBox(s, o).startEndTensor.squeeze();
});
}
class BlazeFaceModel {
constructor(t, o, s, e, i, n) {
(this.blazeFaceModel = t),
(this.width = o),
(this.height = s),
(this.maxFaces = e),
(this.anchorsData = generateAnchors(o, s, ANCHORS_CONFIG)),
(this.anchors = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])(
this.anchorsData
)),
(this.inputSizeData = [o, s]),
(this.inputSize = Object(
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"]
)([o, s])),
(this.iouThreshold = i),
(this.scoreThreshold = n);
}
async getBoundingBoxes(t, o, s = !0) {
const [e, i, n] = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(
() => {
const o = t.resizeBilinear([this.width, this.height]),
s = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(
o.div(255),
0.5
),
2
),
e = this.blazeFaceModel.predict(s).squeeze(),
i = decodeBounds(e, this.anchors, this.inputSize),
n = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(
e,
[0, 0],
[-1, 1]
);
return [
e,
i,
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sigmoid"])(
n
).squeeze(),
];
}
),
a = console.warn;
console.warn = () => {};
const r = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].nonMaxSuppression(
i,
n,
this.maxFaces,
this.iouThreshold,
this.scoreThreshold
);
console.warn = a;
const c = await r.array();
r.dispose();
let l = c.map((t) =>
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(i, [t, 0], [1, -1])
);
o ||
(l = await Promise.all(
l.map(async (t) => {
const o = await t.array();
return t.dispose(), o;
})
));
const d = t.shape[1],
h = t.shape[2];
let p;
p = o
? Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(
[h, d],
this.inputSize
)
: [h / this.inputSizeData[0], d / this.inputSizeData[1]];
const u = [];
for (let t = 0; t < l.length; t++) {
const i = l[t],
a = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(() => {
const a = createBox(
i instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]
? i
: Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])(i)
);
if (!s) return a;
const r = c[t];
let l;
return (
(l = o ? this.anchors.slice([r, 0], [1, 2]) : this.anchorsData[r]),
{
box: a,
landmarks: Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(
e,
[r, NUM_LANDMARKS - 1],
[1, -1]
)
.squeeze()
.reshape([NUM_LANDMARKS, -1]),
probability: Object(
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"]
)(n, [r], [1]),
anchor: l,
}
);
});
u.push(a);
}
return i.dispose(), n.dispose(), e.dispose(), { boxes: u, scaleFactor: p };
}
async estimateFaces(t, o = !1, s = !1, e = !0) {
const [, i] = getInputTensorDimensions(t),
n = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(
() => (
t instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"] ||
(t = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["browser"].fromPixels(t)),
t.toFloat().expandDims(0)
)
),
{ boxes: a, scaleFactor: r } = await this.getBoundingBoxes(n, o, e);
return (
n.dispose(),
o
? a.map((t) => {
const o = scaleBoxFromPrediction(t, r);
let n = { topLeft: o.slice([0], [2]), bottomRight: o.slice([2], [2]) };
if (e) {
const { landmarks: o, probability: s, anchor: e } = t,
i = o.add(e).mul(r);
(n.landmarks = i), (n.probability = s);
}
return s && (n = flipFaceHorizontal(n, i)), n;
})
: Promise.all(
a.map(async (t) => {
const o = scaleBoxFromPrediction(t, r);
let n;
if (e) {
const [s, e, i] = await Promise.all(
[t.landmarks, o, t.probability].map(async (t) => t.array())
),
a = t.anchor,
[c, l] = r,
d = s.map((t) => [(t[0] + a[0]) * c, (t[1] + a[1]) * l]);
(n = {
topLeft: e.slice(0, 2),
bottomRight: e.slice(2),
landmarks: d,
probability: i,
}),
disposeBox(t.box),
t.landmarks.dispose(),
t.probability.dispose();
} else {
const t = await o.array();
n = { topLeft: t.slice(0, 2), bottomRight: t.slice(2) };
}
return o.dispose(), s && (n = flipFaceHorizontal(n, i)), n;
})
)
);
}
}
const BLAZEFACE_MODEL_URL = "https://tfhub.dev/tensorflow/tfjs-model/blazeface/1/default/1";
async function load({
maxFaces: t = 10,
inputWidth: o = 128,
inputHeight: s = 128,
iouThreshold: e = 0.3,
scoreThreshold: i = 0.75,
} = {}) {
const n = await Object(
_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__["loadGraphModel"]
)(BLAZEFACE_MODEL_URL, { fromTFHub: !0 });
return new BlazeFaceModel(n, o, s, t, e, i);
}
/***/
},
/* 82 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MESH_ANNOTATIONS = {
silhouette: [
10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377,
152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,
],
lipsUpperOuter: [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291],
lipsLowerOuter: [146, 91, 181, 84, 17, 314, 405, 321, 375, 291],
lipsUpperInner: [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308],
lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],
rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],
rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],
rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],
rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],
rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],
rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],
rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],
rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],
rightEyebrowLower: [35, 124, 46, 53, 52, 65],
leftEyeUpper0: [466, 388, 387, 386, 385, 384, 398],
leftEyeLower0: [263, 249, 390, 373, 374, 380, 381, 382, 362],
leftEyeUpper1: [467, 260, 259, 257, 258, 286, 414],
leftEyeLower1: [359, 255, 339, 254, 253, 252, 256, 341, 463],
leftEyeUpper2: [342, 445, 444, 443, 442, 441, 413],
leftEyeLower2: [446, 261, 448, 449, 450, 451, 452, 453, 464],
leftEyeLower3: [372, 340, 346, 347, 348, 349, 350, 357, 465],
leftEyebrowUpper: [383, 300, 293, 334, 296, 336, 285, 417],
leftEyebrowLower: [265, 353, 276, 283, 282, 295],
midwayBetweenEyes: [168],
noseTip: [1],
noseBottom: [2],
noseRightCorner: [98],
noseLeftCorner: [327],
rightCheek: [205],
leftCheek: [425],
};
//# sourceMappingURL=keypoints.js.map
/***/
},
/* 83 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tf = __webpack_require__(0);
const box_1 = __webpack_require__(84);
const LANDMARKS_COUNT = 468;
const UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.25;
class Pipeline {
constructor(
boundingBoxDetector,
meshDetector,
meshWidth,
meshHeight,
maxContinuousChecks,
maxFaces
) {
this.regionsOfInterest = [];
this.runsWithoutFaceDetector = 0;
this.boundingBoxDetector = boundingBoxDetector;
this.meshDetector = meshDetector;
this.meshWidth = meshWidth;
this.meshHeight = meshHeight;
this.maxContinuousChecks = maxContinuousChecks;
this.maxFaces = maxFaces;
}
async predict(input) {
if (this.shouldUpdateRegionsOfInterest()) {
const returnTensors = true;
const annotateFace = false;
const { boxes, scaleFactor } = await this.boundingBoxDetector.getBoundingBoxes(
input,
returnTensors,
annotateFace
);
if (boxes.length === 0) {
scaleFactor.dispose();
this.clearAllRegionsOfInterest();
return null;
}
const scaledBoxes = boxes.map((prediction) =>
box_1.enlargeBox(box_1.scaleBoxCoordinates(prediction, scaleFactor))
);
boxes.forEach(box_1.disposeBox);
this.updateRegionsOfInterest(scaledBoxes);
this.runsWithoutFaceDetector = 0;
} else {
this.runsWithoutFaceDetector++;
}
return tf.tidy(() => {
return this.regionsOfInterest.map((box, i) => {
const face = box_1
.cutBoxFromImageAndResize(box, input, [this.meshHeight, this.meshWidth])
.div(255);
const [, flag, coords] = this.meshDetector.predict(face);
const coordsReshaped = tf.reshape(coords, [-1, 3]);
const normalizedBox = tf.div(box_1.getBoxSize(box), [
this.meshWidth,
this.meshHeight,
]);
const scaledCoords = tf
.mul(coordsReshaped, normalizedBox.concat(tf.tensor2d([1], [1, 1]), 1))
.add(box.startPoint.concat(tf.tensor2d([0], [1, 1]), 1));
const landmarksBox = this.calculateLandmarksBoundingBox(scaledCoords);
const previousBox = this.regionsOfInterest[i];
box_1.disposeBox(previousBox);
this.regionsOfInterest[i] = landmarksBox;
const prediction = {
coords: coordsReshaped,
scaledCoords,
box: landmarksBox,
flag: flag.squeeze(),
};
return prediction;
});
});
}
updateRegionsOfInterest(boxes) {
for (let i = 0; i < boxes.length; i++) {
const box = boxes[i];
const previousBox = this.regionsOfInterest[i];
let iou = 0;
if (previousBox && previousBox.startPoint) {
const [boxStartX, boxStartY, boxEndX, boxEndY] = box.startEndTensor.arraySync()[0];
const [previousBoxStartX, previousBoxStartY, previousBoxEndX, previousBoxEndY] =
previousBox.startEndTensor.arraySync()[0];
const xStartMax = Math.max(boxStartX, previousBoxStartX);
const yStartMax = Math.max(boxStartY, previousBoxStartY);
const xEndMin = Math.min(boxEndX, previousBoxEndX);
const yEndMin = Math.min(boxEndY, previousBoxEndY);
const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);
const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);
const previousBoxArea =
(previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);
iou = intersection / (boxArea + previousBoxArea - intersection);
}
if (iou > UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD) {
box_1.disposeBox(box);
} else {
this.regionsOfInterest[i] = box;
box_1.disposeBox(previousBox);
}
}
for (let i = boxes.length; i < this.regionsOfInterest.length; i++) {
box_1.disposeBox(this.regionsOfInterest[i]);
}
this.regionsOfInterest = this.regionsOfInterest.slice(0, boxes.length);
}
clearRegionOfInterest(index) {
if (this.regionsOfInterest[index] != null) {
box_1.disposeBox(this.regionsOfInterest[index]);
this.regionsOfInterest = [
...this.regionsOfInterest.slice(0, index),
...this.regionsOfInterest.slice(index + 1),
];
}
}
clearAllRegionsOfInterest() {
for (let i = 0; i < this.regionsOfInterest.length; i++) {
box_1.disposeBox(this.regionsOfInterest[i]);
}
this.regionsOfInterest = [];
}
shouldUpdateRegionsOfInterest() {
const roisCount = this.regionsOfInterest.length;
const noROIs = roisCount === 0;
if (this.maxFaces === 1 || noROIs) {
return noROIs;
}
return (
roisCount !== this.maxFaces && this.runsWithoutFaceDetector >= this.maxContinuousChecks
);
}
calculateLandmarksBoundingBox(landmarks) {
const xs = landmarks.slice([0, 0], [LANDMARKS_COUNT, 1]);
const ys = landmarks.slice([0, 1], [LANDMARKS_COUNT, 1]);
const boxMinMax = tf.stack([xs.min(), ys.min(), xs.max(), ys.max()]);
const box = box_1.createBox(boxMinMax.expandDims(0));
return box_1.enlargeBox(box);
}
}
exports.Pipeline = Pipeline;
//# sourceMappingURL=pipeline.js.map
/***/
},
/* 84 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tf = __webpack_require__(0);
function disposeBox(box) {
if (box != null && box.startPoint != null) {
box.startEndTensor.dispose();
box.startPoint.dispose();
box.endPoint.dispose();
}
}
exports.disposeBox = disposeBox;
function createBox(startEndTensor, startPoint, endPoint) {
return {
startEndTensor,
startPoint: startPoint != null ? startPoint : tf.slice(startEndTensor, [0, 0], [-1, 2]),
endPoint: endPoint != null ? endPoint : tf.slice(startEndTensor, [0, 2], [-1, 2]),
};
}
exports.createBox = createBox;
function scaleBoxCoordinates(box, factor) {
const newStart = tf.mul(box.startPoint, factor);
const newEnd = tf.mul(box.endPoint, factor);
return createBox(tf.concat2d([newStart, newEnd], 1));
}
exports.scaleBoxCoordinates = scaleBoxCoordinates;
function getBoxSize(box) {
return tf.tidy(() => {
const diff = tf.sub(box.endPoint, box.startPoint);
return tf.abs(diff);
});
}
exports.getBoxSize = getBoxSize;
function getBoxCenter(box) {
return tf.tidy(() => {
const halfSize = tf.div(tf.sub(box.endPoint, box.startPoint), 2);
return tf.add(box.startPoint, halfSize);
});
}
exports.getBoxCenter = getBoxCenter;
function cutBoxFromImageAndResize(box, image, cropSize) {
const height = image.shape[1];
const width = image.shape[2];
const xyxy = box.startEndTensor;
return tf.tidy(() => {
const yxyx = tf.concat2d(
[
xyxy.slice([0, 1], [-1, 1]),
xyxy.slice([0, 0], [-1, 1]),
xyxy.slice([0, 3], [-1, 1]),
xyxy.slice([0, 2], [-1, 1]),
],
0
);
const roundedCoords = tf.div(yxyx.transpose(), [height, width, height, width]);
return tf.image.cropAndResize(image, roundedCoords, [0], cropSize);
});
}
exports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;
function enlargeBox(box, factor = 1.5) {
return tf.tidy(() => {
const center = getBoxCenter(box);
const size = getBoxSize(box);
const newSize = tf.mul(tf.div(size, 2), factor);
const newStart = tf.sub(center, newSize);
const newEnd = tf.add(center, newSize);
return createBox(tf.concat2d([newStart, newEnd], 1), newStart, newEnd);
});
}
exports.enlargeBox = enlargeBox;
//# sourceMappingURL=box.js.map
/***/
},
/* 85 */
/***/ function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UV_COORDS = [
[0.499976992607117, 0.652534008026123],
[0.500025987625122, 0.547487020492554],
[0.499974012374878, 0.602371990680695],
[0.482113003730774, 0.471979022026062],
[0.500150978565216, 0.527155995368958],
[0.499909996986389, 0.498252987861633],
[0.499523013830185, 0.40106201171875],
[0.289712011814117, 0.380764007568359],
[0.499954998493195, 0.312398016452789],
[0.499987006187439, 0.269918978214264],
[0.500023007392883, 0.107050001621246],
[0.500023007392883, 0.666234016418457],
[0.5000159740448, 0.679224014282227],
[0.500023007392883, 0.692348003387451],
[0.499976992607117, 0.695277988910675],
[0.499976992607117, 0.70593398809433],
[0.499976992607117, 0.719385027885437],
[0.499976992607117, 0.737019002437592],
[0.499967992305756, 0.781370997428894],
[0.499816000461578, 0.562981009483337],
[0.473773002624512, 0.573909997940063],
[0.104906998574734, 0.254140973091125],
[0.365929991006851, 0.409575998783112],
[0.338757991790771, 0.41302502155304],
[0.311120003461838, 0.409460008144379],
[0.274657994508743, 0.389131009578705],
[0.393361985683441, 0.403706014156342],
[0.345234006643295, 0.344011008739471],
[0.370094001293182, 0.346076011657715],
[0.319321990013123, 0.347265005111694],
[0.297903001308441, 0.353591024875641],
[0.24779200553894, 0.410809993743896],
[0.396889001131058, 0.842755019664764],
[0.280097991228104, 0.375599980354309],
[0.106310002505779, 0.399955987930298],
[0.2099249958992, 0.391353011131287],
[0.355807989835739, 0.534406006336212],
[0.471751004457474, 0.65040397644043],
[0.474155008792877, 0.680191993713379],
[0.439785003662109, 0.657229006290436],
[0.414617002010345, 0.66654098033905],
[0.450374007225037, 0.680860996246338],
[0.428770989179611, 0.682690978050232],
[0.374971002340317, 0.727805018424988],
[0.486716985702515, 0.547628998756409],
[0.485300987958908, 0.527395009994507],
[0.257764995098114, 0.314490020275116],
[0.401223003864288, 0.455172002315521],
[0.429818987846375, 0.548614978790283],
[0.421351999044418, 0.533740997314453],
[0.276895999908447, 0.532056987285614],
[0.483370006084442, 0.499586999416351],
[0.33721199631691, 0.282882988452911],
[0.296391993761063, 0.293242990970612],
[0.169294998049736, 0.193813979625702],
[0.447580009698868, 0.302609980106354],
[0.392390012741089, 0.353887975215912],
[0.354490011930466, 0.696784019470215],
[0.067304998636246, 0.730105042457581],
[0.442739009857178, 0.572826027870178],
[0.457098007202148, 0.584792017936707],
[0.381974011659622, 0.694710969924927],
[0.392388999462128, 0.694203019142151],
[0.277076005935669, 0.271932005882263],
[0.422551989555359, 0.563233017921448],
[0.385919004678726, 0.281364023685455],
[0.383103013038635, 0.255840003490448],
[0.331431001424789, 0.119714021682739],
[0.229923993349075, 0.232002973556519],
[0.364500999450684, 0.189113974571228],
[0.229622006416321, 0.299540996551514],
[0.173287004232407, 0.278747975826263],
[0.472878992557526, 0.666198015213013],
[0.446828007698059, 0.668527007102966],
[0.422762006521225, 0.673889994621277],
[0.445307999849319, 0.580065965652466],
[0.388103008270264, 0.693961024284363],
[0.403039008378983, 0.706539988517761],
[0.403629004955292, 0.693953037261963],
[0.460041999816895, 0.557139039039612],
[0.431158006191254, 0.692366003990173],
[0.452181994915009, 0.692366003990173],
[0.475387006998062, 0.692366003990173],
[0.465828001499176, 0.779190003871918],
[0.472328990697861, 0.736225962638855],
[0.473087012767792, 0.717857003211975],
[0.473122000694275, 0.704625964164734],
[0.473033010959625, 0.695277988910675],
[0.427942007780075, 0.695277988910675],
[0.426479011774063, 0.703539967536926],
[0.423162013292313, 0.711845993995667],
[0.4183090031147, 0.720062971115112],
[0.390094995498657, 0.639572978019714],
[0.013953999616206, 0.560034036636353],
[0.499913990497589, 0.58014702796936],
[0.413199990987778, 0.69539999961853],
[0.409626007080078, 0.701822996139526],
[0.468080013990402, 0.601534962654114],
[0.422728985548019, 0.585985004901886],
[0.463079988956451, 0.593783974647522],
[0.37211999297142, 0.47341400384903],
[0.334562003612518, 0.496073007583618],
[0.411671012639999, 0.546965003013611],
[0.242175996303558, 0.14767599105835],
[0.290776997804642, 0.201445996761322],
[0.327338010072708, 0.256527006626129],
[0.399509996175766, 0.748921036720276],
[0.441727995872498, 0.261676013469696],
[0.429764986038208, 0.187834024429321],
[0.412198007106781, 0.108901023864746],
[0.288955003023148, 0.398952007293701],
[0.218936994671822, 0.435410976409912],
[0.41278201341629, 0.398970007896423],
[0.257135003805161, 0.355440020561218],
[0.427684992551804, 0.437960982322693],
[0.448339998722076, 0.536936044692993],
[0.178560003638268, 0.45755398273468],
[0.247308000922203, 0.457193970680237],
[0.286267012357712, 0.467674970626831],
[0.332827985286713, 0.460712015628815],
[0.368755996227264, 0.447206974029541],
[0.398963987827301, 0.432654976844788],
[0.476410001516342, 0.405806005001068],
[0.189241006970406, 0.523923993110657],
[0.228962004184723, 0.348950982093811],
[0.490725994110107, 0.562400996685028],
[0.404670000076294, 0.485132992267609],
[0.019469000399113, 0.401564002037048],
[0.426243007183075, 0.420431017875671],
[0.396993011236191, 0.548797011375427],
[0.266469985246658, 0.376977026462555],
[0.439121007919312, 0.51895797252655],
[0.032313998788595, 0.644356966018677],
[0.419054001569748, 0.387154996395111],
[0.462783008813858, 0.505746960639954],
[0.238978996872902, 0.779744982719421],
[0.198220998048782, 0.831938028335571],
[0.107550002634525, 0.540755033493042],
[0.183610007166862, 0.740257024765015],
[0.134409993886948, 0.333683013916016],
[0.385764002799988, 0.883153975009918],
[0.490967005491257, 0.579378008842468],
[0.382384985685349, 0.508572995662689],
[0.174399003386497, 0.397670984268188],
[0.318785011768341, 0.39623498916626],
[0.343364000320435, 0.400596976280212],
[0.396100014448166, 0.710216999053955],
[0.187885001301765, 0.588537991046906],
[0.430987000465393, 0.944064974784851],
[0.318993002176285, 0.898285031318665],
[0.266247987747192, 0.869701027870178],
[0.500023007392883, 0.190576016902924],
[0.499976992607117, 0.954452991485596],
[0.366169989109039, 0.398822009563446],
[0.393207013607025, 0.39553701877594],
[0.410373002290726, 0.391080021858215],
[0.194993004202843, 0.342101991176605],
[0.388664990663528, 0.362284004688263],
[0.365961998701096, 0.355970978736877],
[0.343364000320435, 0.355356991291046],
[0.318785011768341, 0.35834002494812],
[0.301414996385574, 0.363156020641327],
[0.058132998645306, 0.319076001644135],
[0.301414996385574, 0.387449026107788],
[0.499987989664078, 0.618434011936188],
[0.415838003158569, 0.624195992946625],
[0.445681989192963, 0.566076993942261],
[0.465844005346298, 0.620640993118286],
[0.49992299079895, 0.351523995399475],
[0.288718998432159, 0.819945991039276],
[0.335278987884521, 0.852819979190826],
[0.440512001514435, 0.902418971061707],
[0.128294005990028, 0.791940987110138],
[0.408771991729736, 0.373893976211548],
[0.455606997013092, 0.451801002025604],
[0.499877005815506, 0.908990025520325],
[0.375436991453171, 0.924192011356354],
[0.11421000212431, 0.615022003650665],
[0.448662012815475, 0.695277988910675],
[0.4480200111866, 0.704632043838501],
[0.447111994028091, 0.715808033943176],
[0.444831997156143, 0.730794012546539],
[0.430011987686157, 0.766808986663818],
[0.406787008047104, 0.685672998428345],
[0.400738000869751, 0.681069016456604],
[0.392399996519089, 0.677703022956848],
[0.367855995893478, 0.663918972015381],
[0.247923001646996, 0.601333022117615],
[0.452769994735718, 0.420849978923798],
[0.43639200925827, 0.359887003898621],
[0.416164010763168, 0.368713974952698],
[0.413385987281799, 0.692366003990173],
[0.228018000721931, 0.683571994304657],
[0.468268007040024, 0.352671027183533],
[0.411361992359161, 0.804327011108398],
[0.499989002943039, 0.469825029373169],
[0.479153990745544, 0.442654013633728],
[0.499974012374878, 0.439637005329132],
[0.432112008333206, 0.493588984012604],
[0.499886006116867, 0.866917014122009],
[0.49991300702095, 0.821729004383087],
[0.456548988819122, 0.819200992584229],
[0.344549000263214, 0.745438992977142],
[0.37890899181366, 0.574010014533997],
[0.374292999505997, 0.780184984207153],
[0.319687992334366, 0.570737957954407],
[0.357154995203018, 0.604269981384277],
[0.295284003019333, 0.621580958366394],
[0.447750002145767, 0.862477004528046],
[0.410986006259918, 0.508723020553589],
[0.31395098567009, 0.775308012962341],
[0.354128003120422, 0.812552988529205],
[0.324548006057739, 0.703992962837219],
[0.189096003770828, 0.646299958229065],
[0.279776990413666, 0.71465802192688],
[0.1338230073452, 0.682700991630554],
[0.336768001317978, 0.644733011722565],
[0.429883986711502, 0.466521978378296],
[0.455527991056442, 0.548622965812683],
[0.437114000320435, 0.558896005153656],
[0.467287987470627, 0.529924988746643],
[0.414712011814117, 0.335219979286194],
[0.37704598903656, 0.322777986526489],
[0.344107985496521, 0.320150971412659],
[0.312875986099243, 0.32233202457428],
[0.283526003360748, 0.333190023899078],
[0.241245999932289, 0.382785975933075],
[0.102986000478268, 0.468762993812561],
[0.267612010240555, 0.424560010433197],
[0.297879010438919, 0.433175981044769],
[0.333433985710144, 0.433878004550934],
[0.366427004337311, 0.426115989685059],
[0.396012008190155, 0.416696012020111],
[0.420121014118195, 0.41022801399231],
[0.007561000064015, 0.480777025222778],
[0.432949006557465, 0.569517970085144],
[0.458638995885849, 0.479089021682739],
[0.473466008901596, 0.545744001865387],
[0.476087987422943, 0.563830018043518],
[0.468472003936768, 0.555056989192963],
[0.433990985155106, 0.582361996173859],
[0.483518004417419, 0.562983989715576],
[0.482482999563217, 0.57784903049469],
[0.42645001411438, 0.389798998832703],
[0.438998997211456, 0.39649498462677],
[0.450067013502121, 0.400434017181396],
[0.289712011814117, 0.368252992630005],
[0.276670008897781, 0.363372981548309],
[0.517862021923065, 0.471948027610779],
[0.710287988185883, 0.380764007568359],
[0.526226997375488, 0.573909997940063],
[0.895093023777008, 0.254140973091125],
[0.634069979190826, 0.409575998783112],
[0.661242008209229, 0.41302502155304],
[0.688880026340485, 0.409460008144379],
[0.725341975688934, 0.389131009578705],
[0.606630027294159, 0.40370500087738],
[0.654766023159027, 0.344011008739471],
[0.629905998706818, 0.346076011657715],
[0.680678009986877, 0.347265005111694],
[0.702096998691559, 0.353591024875641],
[0.75221198797226, 0.410804986953735],
[0.602918028831482, 0.842862963676453],
[0.719901978969574, 0.375599980354309],
[0.893692970275879, 0.399959981441498],
[0.790081977844238, 0.391354024410248],
[0.643998026847839, 0.534487962722778],
[0.528249025344849, 0.65040397644043],
[0.525849997997284, 0.680191040039062],
[0.560214996337891, 0.657229006290436],
[0.585384011268616, 0.66654098033905],
[0.549625992774963, 0.680860996246338],
[0.57122802734375, 0.682691991329193],
[0.624852001667023, 0.72809898853302],
[0.513050019741058, 0.547281980514526],
[0.51509702205658, 0.527251958847046],
[0.742246985435486, 0.314507007598877],
[0.598631024360657, 0.454979002475739],
[0.570338010787964, 0.548575043678284],
[0.578631997108459, 0.533622980117798],
[0.723087012767792, 0.532054007053375],
[0.516445994377136, 0.499638974666595],
[0.662801027297974, 0.282917976379395],
[0.70362401008606, 0.293271005153656],
[0.830704987049103, 0.193813979625702],
[0.552385985851288, 0.302568018436432],
[0.607609987258911, 0.353887975215912],
[0.645429015159607, 0.696707010269165],
[0.932694971561432, 0.730105042457581],
[0.557260990142822, 0.572826027870178],
[0.542901992797852, 0.584792017936707],
[0.6180260181427, 0.694710969924927],
[0.607590973377228, 0.694203019142151],
[0.722943007946014, 0.271963000297546],
[0.577413976192474, 0.563166975975037],
[0.614082992076874, 0.281386971473694],
[0.616907000541687, 0.255886018276215],
[0.668509006500244, 0.119913995265961],
[0.770092010498047, 0.232020974159241],
[0.635536015033722, 0.189248979091644],
[0.77039098739624, 0.299556016921997],
[0.826722025871277, 0.278755009174347],
[0.527121007442474, 0.666198015213013],
[0.553171992301941, 0.668527007102966],
[0.577238023281097, 0.673889994621277],
[0.554691970348358, 0.580065965652466],
[0.611896991729736, 0.693961024284363],
[0.59696102142334, 0.706539988517761],
[0.596370995044708, 0.693953037261963],
[0.539958000183105, 0.557139039039612],
[0.568841993808746, 0.692366003990173],
[0.547818005084991, 0.692366003990173],
[0.52461302280426, 0.692366003990173],
[0.534089982509613, 0.779141008853912],
[0.527670979499817, 0.736225962638855],
[0.526912987232208, 0.717857003211975],
[0.526877999305725, 0.704625964164734],
[0.526966989040375, 0.695277988910675],
[0.572058022022247, 0.695277988910675],
[0.573521018028259, 0.703539967536926],
[0.57683801651001, 0.711845993995667],
[0.581691026687622, 0.720062971115112],
[0.609944999217987, 0.639909982681274],
[0.986046016216278, 0.560034036636353],
[0.5867999792099, 0.69539999961853],
[0.590372025966644, 0.701822996139526],
[0.531915009021759, 0.601536989212036],
[0.577268004417419, 0.585934996604919],
[0.536915004253387, 0.593786001205444],
[0.627542972564697, 0.473352015018463],
[0.665585994720459, 0.495950996875763],
[0.588353991508484, 0.546862006187439],
[0.757824003696442, 0.14767599105835],
[0.709249973297119, 0.201507985591888],
[0.672684013843536, 0.256581008434296],
[0.600408971309662, 0.74900496006012],
[0.55826598405838, 0.261672019958496],
[0.570303976535797, 0.187870979309082],
[0.588165998458862, 0.109044015407562],
[0.711045026779175, 0.398952007293701],
[0.781069993972778, 0.435405015945435],
[0.587247014045715, 0.398931980133057],
[0.742869973182678, 0.355445981025696],
[0.572156012058258, 0.437651991844177],
[0.55186802148819, 0.536570012569427],
[0.821442008018494, 0.457556009292603],
[0.752701997756958, 0.457181990146637],
[0.71375697851181, 0.467626988887787],
[0.66711300611496, 0.460672974586487],
[0.631101012229919, 0.447153985500336],
[0.6008620262146, 0.432473003864288],
[0.523481011390686, 0.405627012252808],
[0.810747981071472, 0.523926019668579],
[0.771045982837677, 0.348959028720856],
[0.509127020835876, 0.562718033790588],
[0.595292985439301, 0.485023975372314],
[0.980530977249146, 0.401564002037048],
[0.573499977588654, 0.420000016689301],
[0.602994978427887, 0.548687994480133],
[0.733529984951019, 0.376977026462555],
[0.560611009597778, 0.519016981124878],
[0.967685997486115, 0.644356966018677],
[0.580985009670258, 0.387160003185272],
[0.537728011608124, 0.505385041236877],
[0.760966002941132, 0.779752969741821],
[0.801778972148895, 0.831938028335571],
[0.892440974712372, 0.54076099395752],
[0.816350996494293, 0.740260004997253],
[0.865594983100891, 0.333687007427216],
[0.614073991775513, 0.883246004581451],
[0.508952975273132, 0.579437971115112],
[0.617941975593567, 0.508316040039062],
[0.825608015060425, 0.397674977779388],
[0.681214988231659, 0.39623498916626],
[0.656635999679565, 0.400596976280212],
[0.603900015354156, 0.710216999053955],
[0.81208598613739, 0.588539004325867],
[0.56801301240921, 0.944564998149872],
[0.681007981300354, 0.898285031318665],
[0.733752012252808, 0.869701027870178],
[0.633830010890961, 0.398822009563446],
[0.606792986392975, 0.39553701877594],
[0.589659988880157, 0.391062021255493],
[0.805015981197357, 0.342108011245728],
[0.611334979534149, 0.362284004688263],
[0.634037971496582, 0.355970978736877],
[0.656635999679565, 0.355356991291046],
[0.681214988231659, 0.35834002494812],
[0.698584973812103, 0.363156020641327],
[0.941866993904114, 0.319076001644135],
[0.698584973812103, 0.387449026107788],
[0.584177017211914, 0.624107003211975],
[0.554318010807037, 0.566076993942261],
[0.534153997898102, 0.62064003944397],
[0.711217999458313, 0.819975018501282],
[0.664629995822906, 0.852871000766754],
[0.559099972248077, 0.902631998062134],
[0.871706008911133, 0.791940987110138],
[0.591234028339386, 0.373893976211548],
[0.544341027736664, 0.451583981513977],
[0.624562978744507, 0.924192011356354],
[0.88577002286911, 0.615028977394104],
[0.551338016986847, 0.695277988910675],
[0.551980018615723, 0.704632043838501],
[0.552887976169586, 0.715808033943176],
[0.555167973041534, 0.730794012546539],
[0.569944024085999, 0.767035007476807],
[0.593203008174896, 0.685675978660583],
[0.599261999130249, 0.681069016456604],
[0.607599973678589, 0.677703022956848],
[0.631937980651855, 0.663500010967255],
[0.752032995223999, 0.601315021514893],
[0.547226011753082, 0.420395016670227],
[0.563543975353241, 0.359827995300293],
[0.583841025829315, 0.368713974952698],
[0.586614012718201, 0.692366003990173],
[0.771915018558502, 0.683578014373779],
[0.531597018241882, 0.352482974529266],
[0.588370978832245, 0.804440975189209],
[0.52079701423645, 0.442565023899078],
[0.567984998226166, 0.493479013442993],
[0.543282985687256, 0.819254994392395],
[0.655317008495331, 0.745514988899231],
[0.621008992195129, 0.574018001556396],
[0.625559985637665, 0.78031200170517],
[0.680198013782501, 0.570719003677368],
[0.64276397228241, 0.604337990283966],
[0.704662978649139, 0.621529996395111],
[0.552012026309967, 0.862591981887817],
[0.589071989059448, 0.508637011051178],
[0.685944974422455, 0.775357007980347],
[0.645735025405884, 0.812640011310577],
[0.675342977046967, 0.703978002071381],
[0.810858011245728, 0.646304965019226],
[0.72012197971344, 0.714666962623596],
[0.866151988506317, 0.682704985141754],
[0.663187026977539, 0.644596993923187],
[0.570082008838654, 0.466325998306274],
[0.544561982154846, 0.548375964164734],
[0.562758982181549, 0.558784961700439],
[0.531987011432648, 0.530140042304993],
[0.585271000862122, 0.335177004337311],
[0.622952997684479, 0.32277899980545],
[0.655896008014679, 0.320163011550903],
[0.687132000923157, 0.322345972061157],
[0.716481983661652, 0.333200991153717],
[0.758756995201111, 0.382786989212036],
[0.897013008594513, 0.468769013881683],
[0.732392013072968, 0.424547016620636],
[0.70211398601532, 0.433162987232208],
[0.66652500629425, 0.433866024017334],
[0.633504986763, 0.426087975502014],
[0.603875994682312, 0.416586995124817],
[0.579657971858978, 0.409945011138916],
[0.992439985275269, 0.480777025222778],
[0.567192018032074, 0.569419980049133],
[0.54136598110199, 0.478899002075195],
[0.526564002037048, 0.546118021011353],
[0.523913025856018, 0.563830018043518],
[0.531529009342194, 0.555056989192963],
[0.566035985946655, 0.582329034805298],
[0.51631098985672, 0.563053965568542],
[0.5174720287323, 0.577877044677734],
[0.573594987392426, 0.389806985855103],
[0.560697972774506, 0.395331978797913],
[0.549755990505219, 0.399751007556915],
[0.710287988185883, 0.368252992630005],
[0.723330020904541, 0.363372981548309],
];
//# sourceMappingURL=uv_coords.js.map
/***/
},
/* 86 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "version_webgl", function () {
return /* reexport */ version_version;
});
__webpack_require__.d(__webpack_exports__, "MathBackendWebGL", function () {
return /* reexport */ backend_webgl_MathBackendWebGL;
});
__webpack_require__.d(__webpack_exports__, "setWebGLContext", function () {
return /* reexport */ setWebGLContext;
});
__webpack_require__.d(__webpack_exports__, "GPGPUContext", function () {
return /* reexport */ gpgpu_context_GPGPUContext;
});
__webpack_require__.d(__webpack_exports__, "gpgpu_util", function () {
return /* reexport */ gpgpu_util_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "webgl_util", function () {
return /* reexport */ webgl_util_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "forceHalfFloat", function () {
return /* reexport */ forceHalfFloat;
});
__webpack_require__.d(__webpack_exports__, "webgl", function () {
return /* binding */ webgl;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/webgl_util.js
var webgl_util_namespaceObject = {};
__webpack_require__.r(webgl_util_namespaceObject);
__webpack_require__.d(webgl_util_namespaceObject, "callAndCheck", function () {
return callAndCheck;
});
__webpack_require__.d(webgl_util_namespaceObject, "canBeRepresented", function () {
return canBeRepresented;
});
__webpack_require__.d(webgl_util_namespaceObject, "getWebGLErrorMessage", function () {
return getWebGLErrorMessage;
});
__webpack_require__.d(webgl_util_namespaceObject, "getExtensionOrThrow", function () {
return getExtensionOrThrow;
});
__webpack_require__.d(webgl_util_namespaceObject, "createVertexShader", function () {
return createVertexShader;
});
__webpack_require__.d(webgl_util_namespaceObject, "createFragmentShader", function () {
return createFragmentShader;
});
__webpack_require__.d(webgl_util_namespaceObject, "createProgram", function () {
return createProgram;
});
__webpack_require__.d(webgl_util_namespaceObject, "linkProgram", function () {
return linkProgram;
});
__webpack_require__.d(webgl_util_namespaceObject, "validateProgram", function () {
return validateProgram;
});
__webpack_require__.d(webgl_util_namespaceObject, "createStaticVertexBuffer", function () {
return createStaticVertexBuffer;
});
__webpack_require__.d(webgl_util_namespaceObject, "createStaticIndexBuffer", function () {
return createStaticIndexBuffer;
});
__webpack_require__.d(webgl_util_namespaceObject, "getNumChannels", function () {
return getNumChannels;
});
__webpack_require__.d(webgl_util_namespaceObject, "createTexture", function () {
return createTexture;
});
__webpack_require__.d(webgl_util_namespaceObject, "validateTextureSize", function () {
return validateTextureSize;
});
__webpack_require__.d(webgl_util_namespaceObject, "createFramebuffer", function () {
return createFramebuffer;
});
__webpack_require__.d(
webgl_util_namespaceObject,
"bindVertexBufferToProgramAttribute",
function () {
return bindVertexBufferToProgramAttribute;
}
);
__webpack_require__.d(webgl_util_namespaceObject, "bindTextureUnit", function () {
return bindTextureUnit;
});
__webpack_require__.d(webgl_util_namespaceObject, "unbindTextureUnit", function () {
return unbindTextureUnit;
});
__webpack_require__.d(
webgl_util_namespaceObject,
"getProgramUniformLocationOrThrow",
function () {
return getProgramUniformLocationOrThrow;
}
);
__webpack_require__.d(webgl_util_namespaceObject, "getProgramUniformLocation", function () {
return getProgramUniformLocation;
});
__webpack_require__.d(
webgl_util_namespaceObject,
"bindTextureToProgramUniformSampler",
function () {
return bindTextureToProgramUniformSampler;
}
);
__webpack_require__.d(webgl_util_namespaceObject, "bindCanvasToFramebuffer", function () {
return bindCanvasToFramebuffer;
});
__webpack_require__.d(
webgl_util_namespaceObject,
"bindColorTextureToFramebuffer",
function () {
return bindColorTextureToFramebuffer;
}
);
__webpack_require__.d(
webgl_util_namespaceObject,
"unbindColorTextureFromFramebuffer",
function () {
return unbindColorTextureFromFramebuffer;
}
);
__webpack_require__.d(webgl_util_namespaceObject, "validateFramebuffer", function () {
return validateFramebuffer;
});
__webpack_require__.d(webgl_util_namespaceObject, "getFramebufferErrorMessage", function () {
return getFramebufferErrorMessage;
});
__webpack_require__.d(webgl_util_namespaceObject, "getBatchDim", function () {
return getBatchDim;
});
__webpack_require__.d(webgl_util_namespaceObject, "getRowsCols", function () {
return getRowsCols;
});
__webpack_require__.d(webgl_util_namespaceObject, "getShapeAs3D", function () {
return getShapeAs3D;
});
__webpack_require__.d(
webgl_util_namespaceObject,
"getTextureShapeFromLogicalShape",
function () {
return getTextureShapeFromLogicalShape;
}
);
__webpack_require__.d(webgl_util_namespaceObject, "isReshapeFree", function () {
return isReshapeFree;
});
__webpack_require__.d(webgl_util_namespaceObject, "getWebGLMaxTextureSize", function () {
return getWebGLMaxTextureSize;
});
__webpack_require__.d(webgl_util_namespaceObject, "resetMaxTextureSize", function () {
return resetMaxTextureSize;
});
__webpack_require__.d(webgl_util_namespaceObject, "resetMaxTexturesInShader", function () {
return resetMaxTexturesInShader;
});
__webpack_require__.d(webgl_util_namespaceObject, "getMaxTexturesInShader", function () {
return getMaxTexturesInShader;
});
__webpack_require__.d(
webgl_util_namespaceObject,
"getWebGLDisjointQueryTimerVersion",
function () {
return getWebGLDisjointQueryTimerVersion;
}
);
__webpack_require__.d(webgl_util_namespaceObject, "hasExtension", function () {
return hasExtension;
});
__webpack_require__.d(webgl_util_namespaceObject, "isWebGLVersionEnabled", function () {
return isWebGLVersionEnabled;
});
__webpack_require__.d(
webgl_util_namespaceObject,
"isCapableOfRenderingToFloatTexture",
function () {
return isCapableOfRenderingToFloatTexture;
}
);
__webpack_require__.d(
webgl_util_namespaceObject,
"isDownloadFloatTextureEnabled",
function () {
return isDownloadFloatTextureEnabled;
}
);
__webpack_require__.d(webgl_util_namespaceObject, "isWebGLFenceEnabled", function () {
return isWebGLFenceEnabled;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/gpgpu_util.js
var gpgpu_util_namespaceObject = {};
__webpack_require__.r(gpgpu_util_namespaceObject);
__webpack_require__.d(gpgpu_util_namespaceObject, "createVertexShader", function () {
return gpgpu_util_createVertexShader;
});
__webpack_require__.d(gpgpu_util_namespaceObject, "createVertexBuffer", function () {
return createVertexBuffer;
});
__webpack_require__.d(gpgpu_util_namespaceObject, "createIndexBuffer", function () {
return createIndexBuffer;
});
__webpack_require__.d(gpgpu_util_namespaceObject, "createFloat32MatrixTexture", function () {
return createFloat32MatrixTexture;
});
__webpack_require__.d(gpgpu_util_namespaceObject, "createFloat16MatrixTexture", function () {
return createFloat16MatrixTexture;
});
__webpack_require__.d(
gpgpu_util_namespaceObject,
"createUnsignedBytesMatrixTexture",
function () {
return createUnsignedBytesMatrixTexture;
}
);
__webpack_require__.d(gpgpu_util_namespaceObject, "createPackedMatrixTexture", function () {
return createPackedMatrixTexture;
});
__webpack_require__.d(
gpgpu_util_namespaceObject,
"createFloat16PackedMatrixTexture",
function () {
return createFloat16PackedMatrixTexture;
}
);
__webpack_require__.d(
gpgpu_util_namespaceObject,
"bindVertexProgramAttributeStreams",
function () {
return bindVertexProgramAttributeStreams;
}
);
__webpack_require__.d(gpgpu_util_namespaceObject, "uploadDenseMatrixToTexture", function () {
return uploadDenseMatrixToTexture;
});
__webpack_require__.d(gpgpu_util_namespaceObject, "uploadPixelDataToTexture", function () {
return uploadPixelDataToTexture;
});
__webpack_require__.d(
gpgpu_util_namespaceObject,
"createBufferFromOutputTexture",
function () {
return createBufferFromOutputTexture;
}
);
__webpack_require__.d(
gpgpu_util_namespaceObject,
"downloadFloat32MatrixFromBuffer",
function () {
return downloadFloat32MatrixFromBuffer;
}
);
__webpack_require__.d(
gpgpu_util_namespaceObject,
"downloadByteEncodedFloatMatrixFromOutputTexture",
function () {
return downloadByteEncodedFloatMatrixFromOutputTexture;
}
);
__webpack_require__.d(
gpgpu_util_namespaceObject,
"downloadPackedMatrixFromBuffer",
function () {
return downloadPackedMatrixFromBuffer;
}
);
__webpack_require__.d(
gpgpu_util_namespaceObject,
"downloadMatrixFromPackedOutputTexture",
function () {
return downloadMatrixFromPackedOutputTexture;
}
);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js + 269 modules
var dist = __webpack_require__(0);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/canvas_util.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const contexts = {};
const WEBGL_ATTRIBUTES = {
alpha: false,
antialias: false,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
depth: false,
stencil: false,
failIfMajorPerformanceCaveat: true,
};
function setWebGLContext(webGLVersion, gl) {
contexts[webGLVersion] = gl;
}
function getWebGLContext(webGLVersion) {
if (!(webGLVersion in contexts)) {
contexts[webGLVersion] = getWebGLRenderingContext(webGLVersion);
}
const gl = contexts[webGLVersion];
if (gl.isContextLost()) {
delete contexts[webGLVersion];
return getWebGLContext(webGLVersion);
}
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.STENCIL_TEST);
gl.disable(gl.BLEND);
gl.disable(gl.DITHER);
gl.disable(gl.POLYGON_OFFSET_FILL);
gl.disable(gl.SAMPLE_COVERAGE);
gl.enable(gl.SCISSOR_TEST);
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.BACK);
return contexts[webGLVersion];
}
function createCanvas(webGLVersion) {
if (typeof OffscreenCanvas !== "undefined" && webGLVersion === 2) {
return new OffscreenCanvas(300, 150);
} else if (typeof document !== "undefined") {
return document.createElement("canvas");
} else {
throw new Error("Cannot create a canvas in this context");
}
}
function getWebGLRenderingContext(webGLVersion) {
if (webGLVersion !== 1 && webGLVersion !== 2) {
throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");
}
const canvas = createCanvas(webGLVersion);
canvas.addEventListener(
"webglcontextlost",
(ev) => {
ev.preventDefault();
delete contexts[webGLVersion];
},
false
);
if (webGLVersion === 1) {
return (
canvas.getContext("webgl", WEBGL_ATTRIBUTES) ||
canvas.getContext("experimental-webgl", WEBGL_ATTRIBUTES)
);
}
return canvas.getContext("webgl2", WEBGL_ATTRIBUTES);
}
//# sourceMappingURL=canvas_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/tex_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var PackingScheme;
(function (PackingScheme) {
/**
* All values in a single texel are densely packed without any constraints.
*
* This is how the shader encodes a tensor with shape = [2, 3, 4]
* (indices are [batch, row, col]).
*
* 000|001 010|011 020|021
* ------- ------- -------
* 002|003 012|013 022|023
*
* 100|101 110|111 120|121
* ------- ------- -------
* 102|103 112|113 122|123
*
*/
PackingScheme[(PackingScheme["DENSE"] = 0)] = "DENSE";
/**
* Single texels contain only values from the same batch, and from adjacent
* rows and columns.
*
* This is how the shader encodes a tensor with shape = [2, 3, 5]
* (indices are [batch, row, col]).
*
* 000|001 002|003 004|xxx 020|021 022|023 024|xxx
* ------- ------- ------- ------- ------- -------
* 010|011 012|013 014|xxx xxx|xxx xxx|xxx xxx|xxx
*
* 100|101 102|103 104|xxx 120|121 122|123 124|xxx
* ------- ------- ------- ------- ------- -------
* 110|111 112|113 114|xxx xxx|xxx xxx|xxx xxx|xxx
*
*/
PackingScheme[(PackingScheme["SHARED_BATCH"] = 1)] = "SHARED_BATCH";
})(PackingScheme || (PackingScheme = {}));
var TextureUsage;
(function (TextureUsage) {
TextureUsage[(TextureUsage["RENDER"] = 0)] = "RENDER";
TextureUsage[(TextureUsage["UPLOAD"] = 1)] = "UPLOAD";
TextureUsage[(TextureUsage["PIXELS"] = 2)] = "PIXELS";
TextureUsage[(TextureUsage["DOWNLOAD"] = 3)] = "DOWNLOAD";
})(TextureUsage || (TextureUsage = {}));
var PhysicalTextureType;
(function (PhysicalTextureType) {
PhysicalTextureType[(PhysicalTextureType["UNPACKED_FLOAT16"] = 0)] = "UNPACKED_FLOAT16";
PhysicalTextureType[(PhysicalTextureType["UNPACKED_FLOAT32"] = 1)] = "UNPACKED_FLOAT32";
PhysicalTextureType[(PhysicalTextureType["PACKED_4X1_UNSIGNED_BYTE"] = 2)] =
"PACKED_4X1_UNSIGNED_BYTE";
PhysicalTextureType[(PhysicalTextureType["PACKED_2X2_FLOAT32"] = 3)] = "PACKED_2X2_FLOAT32";
PhysicalTextureType[(PhysicalTextureType["PACKED_2X2_FLOAT16"] = 4)] = "PACKED_2X2_FLOAT16";
})(PhysicalTextureType || (PhysicalTextureType = {}));
function getUnpackedMatrixTextureShapeWidthHeight(rows, columns) {
return [columns, rows];
}
function getUnpackedArraySizeFromMatrixSize(matrixSize, channelsPerTexture) {
return matrixSize * channelsPerTexture;
}
function getColorMatrixTextureShapeWidthHeight(rows, columns) {
return [columns * 4, rows];
}
/**
* Get shape for densely packed RGBA texture.
*/
function getDenseTexShape(shape) {
const size = dist["util"].sizeFromShape(shape);
const texelsNeeded = Math.ceil(size / 4);
return dist["util"].sizeToSquarishShape(texelsNeeded);
}
function getMatrixSizeFromUnpackedArraySize(unpackedSize, channelsPerTexture) {
if (unpackedSize % channelsPerTexture !== 0) {
throw new Error(
`unpackedSize (${unpackedSize}) must be a multiple of ` + `${channelsPerTexture}`
);
}
return unpackedSize / channelsPerTexture;
}
function decodeMatrixFromUnpackedColorRGBAArray(unpackedArray, matrix, channels) {
const requiredSize = (unpackedArray.length * channels) / 4;
if (matrix.length < requiredSize) {
throw new Error(`matrix length (${matrix.length}) must be >= ${requiredSize}`);
}
let dst = 0;
for (let src = 0; src < unpackedArray.length; src += 4) {
for (let c = 0; c < channels; c++) {
matrix[dst++] = unpackedArray[src + c];
}
}
}
function getPackedMatrixTextureShapeWidthHeight(rows, columns) {
return [Math.max(1, Math.ceil(columns / 2)), Math.max(1, Math.ceil(rows / 2))];
}
function getPackedRGBAArraySizeFromMatrixShape(rows, columns) {
const [w, h] = getPackedMatrixTextureShapeWidthHeight(rows, columns);
return w * h * 4;
}
function getTextureConfig(
// tslint:disable-next-line:no-any
gl,
textureHalfFloatExtension
) {
// tslint:disable-next-line:no-any
const glany = gl;
let internalFormatFloat;
let internalFormatHalfFloat;
let internalFormatPackedHalfFloat;
let internalFormatPackedFloat;
let textureFormatFloat;
let downloadTextureFormat;
let downloadUnpackNumChannels;
let defaultNumChannels;
let textureTypeHalfFloat;
let textureTypeFloat;
if (Object(dist["env"])().getNumber("WEBGL_VERSION") === 2) {
internalFormatFloat = glany.R32F;
internalFormatHalfFloat = glany.R16F;
internalFormatPackedHalfFloat = glany.RGBA16F;
internalFormatPackedFloat = glany.RGBA32F;
textureFormatFloat = glany.RED;
downloadUnpackNumChannels = 4;
defaultNumChannels = 1;
textureTypeHalfFloat = glany.HALF_FLOAT;
textureTypeFloat = glany.FLOAT;
} else {
internalFormatFloat = gl.RGBA;
internalFormatHalfFloat = gl.RGBA;
internalFormatPackedHalfFloat = gl.RGBA;
internalFormatPackedFloat = glany.RGBA;
textureFormatFloat = gl.RGBA;
downloadUnpackNumChannels = 4;
defaultNumChannels = 4;
textureTypeHalfFloat =
textureHalfFloatExtension != null ? textureHalfFloatExtension.HALF_FLOAT_OES : null;
textureTypeFloat = gl.FLOAT;
}
downloadTextureFormat = gl.RGBA;
return {
internalFormatFloat,
internalFormatHalfFloat,
internalFormatPackedHalfFloat,
internalFormatPackedFloat,
textureFormatFloat,
downloadTextureFormat,
downloadUnpackNumChannels,
defaultNumChannels,
textureTypeHalfFloat,
textureTypeFloat,
};
}
//# sourceMappingURL=tex_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/webgl_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function callAndCheck(gl, debugMode, func) {
const returnValue = func();
if (debugMode) {
checkWebGLError(gl);
}
return returnValue;
}
function checkWebGLError(gl) {
const error = gl.getError();
if (error !== gl.NO_ERROR) {
throw new Error("WebGL Error: " + getWebGLErrorMessage(gl, error));
}
}
// https://en.wikipedia.org/wiki/Half-precision_floating-point_format
const MIN_FLOAT16 = 5.96e-8;
const MAX_FLOAT16 = 65504;
function canBeRepresented(num) {
if (
Object(dist["env"])().getBool("WEBGL_RENDER_FLOAT32_ENABLED") ||
num === 0 ||
(MIN_FLOAT16 < Math.abs(num) && Math.abs(num) < MAX_FLOAT16)
) {
return true;
}
return false;
}
function getWebGLErrorMessage(gl, status) {
switch (status) {
case gl.NO_ERROR:
return "NO_ERROR";
case gl.INVALID_ENUM:
return "INVALID_ENUM";
case gl.INVALID_VALUE:
return "INVALID_VALUE";
case gl.INVALID_OPERATION:
return "INVALID_OPERATION";
case gl.INVALID_FRAMEBUFFER_OPERATION:
return "INVALID_FRAMEBUFFER_OPERATION";
case gl.OUT_OF_MEMORY:
return "OUT_OF_MEMORY";
case gl.CONTEXT_LOST_WEBGL:
return "CONTEXT_LOST_WEBGL";
default:
return `Unknown error code ${status}`;
}
}
function getExtensionOrThrow(gl, debug, extensionName) {
return throwIfNull(
gl,
debug,
() => gl.getExtension(extensionName),
'Extension "' + extensionName + '" not supported on this browser.'
);
}
function createVertexShader(gl, debug, vertexShaderSource) {
const vertexShader = throwIfNull(
gl,
debug,
() => gl.createShader(gl.VERTEX_SHADER),
"Unable to create vertex WebGLShader."
);
callAndCheck(gl, debug, () => gl.shaderSource(vertexShader, vertexShaderSource));
callAndCheck(gl, debug, () => gl.compileShader(vertexShader));
if (gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS) === false) {
console.log(gl.getShaderInfoLog(vertexShader));
throw new Error("Failed to compile vertex shader.");
}
return vertexShader;
}
function createFragmentShader(gl, debug, fragmentShaderSource) {
const fragmentShader = throwIfNull(
gl,
debug,
() => gl.createShader(gl.FRAGMENT_SHADER),
"Unable to create fragment WebGLShader."
);
callAndCheck(gl, debug, () => gl.shaderSource(fragmentShader, fragmentShaderSource));
callAndCheck(gl, debug, () => gl.compileShader(fragmentShader));
if (gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS) === false) {
logShaderSourceAndInfoLog(fragmentShaderSource, gl.getShaderInfoLog(fragmentShader));
throw new Error("Failed to compile fragment shader.");
}
return fragmentShader;
}
const lineNumberRegex = /ERROR: [0-9]+:([0-9]+):/g;
function logShaderSourceAndInfoLog(shaderSource, shaderInfoLog) {
const lineNumberRegexResult = lineNumberRegex.exec(shaderInfoLog);
if (lineNumberRegexResult == null) {
console.log(`Couldn't parse line number in error: ${shaderInfoLog}`);
console.log(shaderSource);
return;
}
const lineNumber = +lineNumberRegexResult[1];
const shaderLines = shaderSource.split("\n");
const pad = shaderLines.length.toString().length + 2;
const linesWithLineNumbers = shaderLines.map(
(line, lineNumber) => dist["util"].rightPad((lineNumber + 1).toString(), pad) + line
);
let maxLineLength = 0;
for (let i = 0; i < linesWithLineNumbers.length; i++) {
maxLineLength = Math.max(linesWithLineNumbers[i].length, maxLineLength);
}
const beforeErrorLines = linesWithLineNumbers.slice(0, lineNumber - 1);
const errorLine = linesWithLineNumbers.slice(lineNumber - 1, lineNumber);
const afterErrorLines = linesWithLineNumbers.slice(lineNumber);
console.log(beforeErrorLines.join("\n"));
console.log(shaderInfoLog.split("\n")[0]);
console.log(
`%c ${dist["util"].rightPad(errorLine[0], maxLineLength)}`,
"border:1px solid red; background-color:#e3d2d2; color:#a61717"
);
console.log(afterErrorLines.join("\n"));
}
function createProgram(gl, debug) {
return throwIfNull(gl, debug, () => gl.createProgram(), "Unable to create WebGLProgram.");
}
function linkProgram(gl, debug, program) {
callAndCheck(gl, debug, () => gl.linkProgram(program));
if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
console.log(gl.getProgramInfoLog(program));
throw new Error("Failed to link vertex and fragment shaders.");
}
}
function validateProgram(gl, debug, program) {
callAndCheck(gl, debug, () => gl.validateProgram(program));
if (gl.getProgramParameter(program, gl.VALIDATE_STATUS) === false) {
console.log(gl.getProgramInfoLog(program));
throw new Error("Shader program validation failed.");
}
}
function createStaticVertexBuffer(gl, debug, data) {
const buffer = throwIfNull(
gl,
debug,
() => gl.createBuffer(),
"Unable to create WebGLBuffer"
);
callAndCheck(gl, debug, () => gl.bindBuffer(gl.ARRAY_BUFFER, buffer));
callAndCheck(gl, debug, () => gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW));
return buffer;
}
function createStaticIndexBuffer(gl, debug, data) {
const buffer = throwIfNull(
gl,
debug,
() => gl.createBuffer(),
"Unable to create WebGLBuffer"
);
callAndCheck(gl, debug, () => gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer));
callAndCheck(gl, debug, () => gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW));
return buffer;
}
function getNumChannels() {
if (Object(dist["env"])().getNumber("WEBGL_VERSION") === 2) {
return 1;
}
return 4;
}
function createTexture(gl, debug) {
return throwIfNull(gl, debug, () => gl.createTexture(), "Unable to create WebGLTexture.");
}
function validateTextureSize(width, height) {
const maxTextureSize = Object(dist["env"])().getNumber("WEBGL_MAX_TEXTURE_SIZE");
if (width <= 0 || height <= 0) {
const requested = `[${width}x${height}]`;
throw new Error("Requested texture size " + requested + " is invalid.");
}
if (width > maxTextureSize || height > maxTextureSize) {
const requested = `[${width}x${height}]`;
const max = `[${maxTextureSize}x${maxTextureSize}]`;
throw new Error(
"Requested texture size " +
requested +
" greater than WebGL maximum on this browser / GPU " +
max +
"."
);
}
}
function createFramebuffer(gl, debug) {
return throwIfNull(
gl,
debug,
() => gl.createFramebuffer(),
"Unable to create WebGLFramebuffer."
);
}
function bindVertexBufferToProgramAttribute(
gl,
debug,
program,
attribute,
buffer,
arrayEntriesPerItem,
itemStrideInBytes,
itemOffsetInBytes
) {
const loc = gl.getAttribLocation(program, attribute);
if (loc === -1) {
// The GPU compiler decided to strip out this attribute because it's unused,
// thus no need to bind.
return false;
}
callAndCheck(gl, debug, () => gl.bindBuffer(gl.ARRAY_BUFFER, buffer));
callAndCheck(gl, debug, () =>
gl.vertexAttribPointer(
loc,
arrayEntriesPerItem,
gl.FLOAT,
false,
itemStrideInBytes,
itemOffsetInBytes
)
);
callAndCheck(gl, debug, () => gl.enableVertexAttribArray(loc));
return true;
}
function bindTextureUnit(gl, debug, texture, textureUnit) {
validateTextureUnit(gl, textureUnit);
callAndCheck(gl, debug, () => gl.activeTexture(gl.TEXTURE0 + textureUnit));
callAndCheck(gl, debug, () => gl.bindTexture(gl.TEXTURE_2D, texture));
}
function unbindTextureUnit(gl, debug, textureUnit) {
validateTextureUnit(gl, textureUnit);
callAndCheck(gl, debug, () => gl.activeTexture(gl.TEXTURE0 + textureUnit));
callAndCheck(gl, debug, () => gl.bindTexture(gl.TEXTURE_2D, null));
}
function getProgramUniformLocationOrThrow(gl, debug, program, uniformName) {
return throwIfNull(
gl,
debug,
() => gl.getUniformLocation(program, uniformName),
'uniform "' + uniformName + '" not present in program.'
);
}
function getProgramUniformLocation(gl, program, uniformName) {
return gl.getUniformLocation(program, uniformName);
}
function bindTextureToProgramUniformSampler(
gl,
debug,
program,
texture,
uniformSamplerLocation,
textureUnit
) {
callAndCheck(gl, debug, () => bindTextureUnit(gl, debug, texture, textureUnit));
callAndCheck(gl, debug, () => gl.uniform1i(uniformSamplerLocation, textureUnit));
}
function bindCanvasToFramebuffer(gl, debug) {
callAndCheck(gl, debug, () => gl.bindFramebuffer(gl.FRAMEBUFFER, null));
callAndCheck(gl, debug, () => gl.viewport(0, 0, gl.canvas.width, gl.canvas.height));
callAndCheck(gl, debug, () => gl.scissor(0, 0, gl.canvas.width, gl.canvas.height));
}
function bindColorTextureToFramebuffer(gl, debug, texture, framebuffer) {
callAndCheck(gl, debug, () => gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer));
callAndCheck(gl, debug, () =>
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0)
);
}
function unbindColorTextureFromFramebuffer(gl, debug, framebuffer) {
callAndCheck(gl, debug, () => gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer));
callAndCheck(gl, debug, () =>
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0)
);
}
function validateFramebuffer(gl) {
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
if (status !== gl.FRAMEBUFFER_COMPLETE) {
throw new Error("Error binding framebuffer: " + getFramebufferErrorMessage(gl, status));
}
}
function getFramebufferErrorMessage(gl, status) {
switch (status) {
case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
case gl.FRAMEBUFFER_UNSUPPORTED:
return "FRAMEBUFFER_UNSUPPORTED";
default:
return `unknown error ${status}`;
}
}
function throwIfNull(gl, debug, returnTOrNull, failureMessage) {
const tOrNull = callAndCheck(gl, debug, () => returnTOrNull());
if (tOrNull == null) {
throw new Error(failureMessage);
}
return tOrNull;
}
function validateTextureUnit(gl, textureUnit) {
const maxTextureUnit = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1;
const glTextureUnit = textureUnit + gl.TEXTURE0;
if (glTextureUnit < gl.TEXTURE0 || glTextureUnit > maxTextureUnit) {
const textureUnitRange = `[gl.TEXTURE0, gl.TEXTURE${maxTextureUnit}]`;
throw new Error(`textureUnit must be in ${textureUnitRange}.`);
}
}
function getBatchDim(shape, dimsToSkip = 2) {
return dist["util"].sizeFromShape(shape.slice(0, shape.length - dimsToSkip));
}
function getRowsCols(shape) {
if (shape.length === 0) {
throw Error("Cannot get rows and columns of an empty shape array.");
}
return [shape.length > 1 ? shape[shape.length - 2] : 1, shape[shape.length - 1]];
}
function getShapeAs3D(shape) {
let shapeAs3D = [1, 1, 1];
const isScalar = shape.length === 0 || (shape.length === 1 && shape[0] === 1);
if (!isScalar) {
shapeAs3D = [getBatchDim(shape), ...getRowsCols(shape)];
}
return shapeAs3D;
}
function getTextureShapeFromLogicalShape(logShape, isPacked = false) {
let maxTexSize = Object(dist["env"])().getNumber("WEBGL_MAX_TEXTURE_SIZE");
if (isPacked) {
maxTexSize = maxTexSize * 2;
// This logic ensures we accurately count the number of packed texels needed
// to accommodate the tensor. We can only pack values in the same texel if
// they are from adjacent pairs of rows/cols within the same batch. So if a
// tensor has 3 rows, we pretend it has 4 rows in order to account for the
// fact that the texels containing the third row are half empty.
logShape = logShape.map((d, i) =>
i >= logShape.length - 2 ? dist["util"].nearestLargerEven(logShape[i]) : logShape[i]
);
// Packed texture height is at least 2 (the channel height of a single
// texel).
if (logShape.length === 1) {
logShape = [2, logShape[0]];
}
}
// If logical shape is 2, we don't squeeze, since we want to match physical.
if (logShape.length !== 2) {
const squeezeResult = dist["util"].squeezeShape(logShape);
logShape = squeezeResult.newShape;
}
let size = dist["util"].sizeFromShape(logShape);
if (logShape.length <= 1 && size <= maxTexSize) {
return [1, size];
} else if (
logShape.length === 2 &&
logShape[0] <= maxTexSize &&
logShape[1] <= maxTexSize
) {
return logShape;
} else if (
logShape.length === 3 &&
logShape[0] * logShape[1] <= maxTexSize &&
logShape[2] <= maxTexSize
) {
return [logShape[0] * logShape[1], logShape[2]];
} else if (
logShape.length === 3 &&
logShape[0] <= maxTexSize &&
logShape[1] * logShape[2] <= maxTexSize
) {
return [logShape[0], logShape[1] * logShape[2]];
} else if (
logShape.length === 4 &&
logShape[0] * logShape[1] * logShape[2] <= maxTexSize &&
logShape[3] <= maxTexSize
) {
return [logShape[0] * logShape[1] * logShape[2], logShape[3]];
} else if (
logShape.length === 4 &&
logShape[0] <= maxTexSize &&
logShape[1] * logShape[2] * logShape[3] <= maxTexSize
) {
return [logShape[0], logShape[1] * logShape[2] * logShape[3]];
} else {
if (isPacked) {
// For packed textures size equals the number of channels required to
// accommodate the texture data. However in order to squarify such that
// inner dimensions stay even, we rewrite size to equal the number of
// texels. Then in the return statement we rehydrate the squarified
// dimensions to channel units.
const batchDim = getBatchDim(logShape);
let rows = 2,
cols = 2;
if (logShape.length) {
[rows, cols] = getRowsCols(logShape);
}
size = batchDim * (rows / 2) * (cols / 2);
return dist["util"].sizeToSquarishShape(size).map((d) => d * 2);
}
return dist["util"].sizeToSquarishShape(size);
}
}
function isEven(n) {
return n % 2 === 0;
}
/**
* This determines whether reshaping a packed texture requires rearranging
* the data within the texture, assuming 2x2 packing.
*/
function isReshapeFree(shape1, shape2) {
shape1 = shape1.slice(-2);
shape2 = shape2.slice(-2);
if (dist["util"].arraysEqual(shape1, shape2)) {
return true;
}
if (!shape1.length || !shape2.length) {
// One of the shapes is a scalar.
return true;
}
if (shape1[0] === 0 || shape1[1] === 0 || shape2[0] === 0 || shape2[1] === 0) {
return true;
}
if (shape1.length !== shape2.length) {
// One of the shapes is a vector.
const shape1Cols = shape1.slice(-1)[0];
const shape2Cols = shape2.slice(-1)[0];
if (shape1Cols === shape2Cols) {
return true;
}
if (isEven(shape1Cols) && isEven(shape2Cols) && (shape1[0] === 1 || shape2[0] === 1)) {
return true;
}
}
return shape1[1] === shape2[1] && isEven(shape1[0]) && isEven(shape2[0]);
}
// We cache webgl params because the environment gets reset between
// unit tests and we don't want to constantly query the WebGLContext for
// MAX_TEXTURE_SIZE.
let MAX_TEXTURE_SIZE;
let MAX_TEXTURES_IN_SHADER;
function getWebGLMaxTextureSize(webGLVersion) {
if (MAX_TEXTURE_SIZE == null) {
const gl = getWebGLContext(webGLVersion);
MAX_TEXTURE_SIZE = gl.getParameter(gl.MAX_TEXTURE_SIZE);
}
return MAX_TEXTURE_SIZE;
}
function resetMaxTextureSize() {
MAX_TEXTURE_SIZE = null;
}
function resetMaxTexturesInShader() {
MAX_TEXTURES_IN_SHADER = null;
}
function getMaxTexturesInShader(webGLVersion) {
if (MAX_TEXTURES_IN_SHADER == null) {
const gl = getWebGLContext(webGLVersion);
MAX_TEXTURES_IN_SHADER = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
}
// We cap at 16 to avoid spurious runtime "memory exhausted" error.
return Math.min(16, MAX_TEXTURES_IN_SHADER);
}
function getWebGLDisjointQueryTimerVersion(webGLVersion) {
if (webGLVersion === 0) {
return 0;
}
let queryTimerVersion;
const gl = getWebGLContext(webGLVersion);
if (hasExtension(gl, "EXT_disjoint_timer_query_webgl2") && webGLVersion === 2) {
queryTimerVersion = 2;
} else if (hasExtension(gl, "EXT_disjoint_timer_query")) {
queryTimerVersion = 1;
} else {
queryTimerVersion = 0;
}
return queryTimerVersion;
}
function hasExtension(gl, extensionName) {
const ext = gl.getExtension(extensionName);
return ext != null;
}
function isWebGLVersionEnabled(webGLVersion) {
try {
const gl = getWebGLContext(webGLVersion);
if (gl != null) {
return true;
}
} catch (e) {
return false;
}
return false;
}
function isCapableOfRenderingToFloatTexture(webGLVersion) {
if (webGLVersion === 0) {
return false;
}
const gl = getWebGLContext(webGLVersion);
if (webGLVersion === 1) {
if (!hasExtension(gl, "OES_texture_float")) {
return false;
}
} else {
if (!hasExtension(gl, "EXT_color_buffer_float")) {
return false;
}
}
const isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);
return isFrameBufferComplete;
}
/**
* Check if we can download values from a float/half-float texture.
*
* Note that for performance reasons we use binding a texture to a framebuffer
* as a proxy for ability to download float values later using readPixels. The
* texture params of this texture will not match those in readPixels exactly
* but if we are unable to bind some kind of float texture to the frameBuffer
* then we definitely will not be able to read float values from it.
*/
function isDownloadFloatTextureEnabled(webGLVersion) {
if (webGLVersion === 0) {
return false;
}
const gl = getWebGLContext(webGLVersion);
if (webGLVersion === 1) {
if (!hasExtension(gl, "OES_texture_float")) {
return false;
}
if (!hasExtension(gl, "WEBGL_color_buffer_float")) {
return false;
}
} else {
if (hasExtension(gl, "EXT_color_buffer_float")) {
return createFloatTextureAndBindToFramebuffer(gl);
}
const COLOR_BUFFER_HALF_FLOAT = "EXT_color_buffer_half_float";
if (hasExtension(gl, COLOR_BUFFER_HALF_FLOAT)) {
const textureHalfFloatExtension = gl.getExtension(COLOR_BUFFER_HALF_FLOAT);
return createHalfFloatTextureAndBindToFramebuffer(gl, textureHalfFloatExtension);
}
return false;
}
const isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);
return isFrameBufferComplete;
}
function createFloatTextureAndBindToFramebuffer(gl) {
const texConfig = getTextureConfig(gl);
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
const width = 1;
const height = 1;
gl.texImage2D(
gl.TEXTURE_2D,
0,
texConfig.internalFormatFloat,
width,
height,
0,
texConfig.textureFormatFloat,
texConfig.textureTypeFloat,
null
);
const frameBuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
const isFrameBufferComplete =
gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.deleteTexture(texture);
gl.deleteFramebuffer(frameBuffer);
return isFrameBufferComplete;
}
function createHalfFloatTextureAndBindToFramebuffer(
// tslint:disable-next-line:no-any
gl,
textureHalfFloatExtension
) {
const texConfig = getTextureConfig(gl, textureHalfFloatExtension);
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
const width = 1;
const height = 1;
gl.texImage2D(
gl.TEXTURE_2D,
0,
texConfig.internalFormatHalfFloat,
width,
height,
0,
texConfig.textureFormatFloat,
texConfig.textureTypeHalfFloat,
null
);
const frameBuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
const isFrameBufferComplete =
gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.deleteTexture(texture);
gl.deleteFramebuffer(frameBuffer);
return isFrameBufferComplete;
}
function isWebGLFenceEnabled(webGLVersion) {
if (webGLVersion !== 2) {
return false;
}
const gl = getWebGLContext(webGLVersion);
// tslint:disable-next-line:no-any
const isEnabled = gl.fenceSync != null;
return isEnabled;
}
//# sourceMappingURL=webgl_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/flags_webgl.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ENV = Object(dist["env"])();
/**
* This file contains WebGL-specific flag registrations.
*/
/**
* True if WebGL is supported.
*/
ENV.registerFlag("HAS_WEBGL", () => ENV.getNumber("WEBGL_VERSION") > 0);
/** 0: No WebGL, 1: WebGL 1.0, 2: WebGL 2.0. */
ENV.registerFlag("WEBGL_VERSION", () => {
if (isWebGLVersionEnabled(2)) {
return 2;
} else if (isWebGLVersionEnabled(1)) {
return 1;
}
return 0;
});
ENV.registerFlag("WEBGL_BUFFER_SUPPORTED", () => ENV.get("WEBGL_VERSION") === 2);
/** Whether the WebGL backend will sometimes forward ops to the CPU. */
ENV.registerFlag("WEBGL_CPU_FORWARD", () => true);
/** Whether the WebGL backend will always use f16 textures for rendering. */
ENV.registerFlag("WEBGL_FORCE_F16_TEXTURES", () => false);
/** Whether to turn all packing related flags on. */
ENV.registerFlag("WEBGL_PACK", () => ENV.getBool("HAS_WEBGL"));
/** Whether we will pack the batchnormalization op. */
ENV.registerFlag("WEBGL_PACK_NORMALIZATION", () => ENV.getBool("WEBGL_PACK"));
/** Whether we will pack the clip op. */
ENV.registerFlag("WEBGL_PACK_CLIP", () => ENV.getBool("WEBGL_PACK"));
/** Whether we will pack the depthwise conv op. */
// TODO: https://github.com/tensorflow/tfjs/issues/1679
ENV.registerFlag("WEBGL_PACK_DEPTHWISECONV", () => false);
/** Whether we will pack binary ops. */
ENV.registerFlag("WEBGL_PACK_BINARY_OPERATIONS", () => ENV.getBool("WEBGL_PACK"));
/** Whether we will pack unary ops. */
ENV.registerFlag("WEBGL_PACK_UNARY_OPERATIONS", () => ENV.getBool("WEBGL_PACK"));
/** Whether we will pack array ops. */
ENV.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS", () => ENV.getBool("WEBGL_PACK"));
/** Whether we will pack image ops. */
ENV.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS", () => ENV.getBool("WEBGL_PACK"));
/** Whether we will pack reduce ops. */
ENV.registerFlag("WEBGL_PACK_REDUCE", () => ENV.getBool("WEBGL_PACK"));
/** Whether packed WebGL kernels lazily unpack their outputs. */
ENV.registerFlag("WEBGL_LAZILY_UNPACK", () => ENV.getBool("WEBGL_PACK"));
/** Whether we will use the im2col algorithm to speed up convolutions. */
ENV.registerFlag("WEBGL_CONV_IM2COL", () => ENV.getBool("WEBGL_PACK"));
/** The maximum texture dimension. */
ENV.registerFlag("WEBGL_MAX_TEXTURE_SIZE", () =>
getWebGLMaxTextureSize(ENV.getNumber("WEBGL_VERSION"))
);
/** The maximum texture dimension. */
ENV.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER", () =>
getMaxTexturesInShader(ENV.getNumber("WEBGL_VERSION"))
);
/**
* The disjoint_query_timer extension version.
* 0: disabled, 1: EXT_disjoint_timer_query, 2:
* EXT_disjoint_timer_query_webgl2.
* In Firefox with WebGL 2.0,
* EXT_disjoint_timer_query_webgl2 is not available, so we must use the
* WebGL 1.0 extension.
*/
ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION", () => {
const webGLVersion = ENV.getNumber("WEBGL_VERSION");
if (webGLVersion === 0) {
return 0;
}
return getWebGLDisjointQueryTimerVersion(webGLVersion);
});
/**
* Whether the timer object from the disjoint_query_timer extension gives
* timing information that is reliable.
*/
ENV.registerFlag(
"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",
() =>
ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 &&
!dist["device_util"].isMobile()
);
/**
* Whether the device is physically capable of rendering to float32 textures.
*/
ENV.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE", () =>
isCapableOfRenderingToFloatTexture(ENV.getNumber("WEBGL_VERSION"))
);
/**
* Whether rendering to float32 textures is enabled. If disabled, renders to
* float16 textures.
*/
ENV.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED", () => {
return ENV.getBool("WEBGL_FORCE_F16_TEXTURES")
? false
: ENV.getBool("WEBGL_RENDER_FLOAT32_CAPABLE");
});
/**
* Whether downloading float textures is enabled (16 or 32 bit). If disabled,
* uses IEEE 754 encoding of the float32 values to 4 uint8 when downloading.
*/
ENV.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED", () =>
isDownloadFloatTextureEnabled(ENV.getNumber("WEBGL_VERSION"))
);
/** Whether the fence API is available. */
ENV.registerFlag("WEBGL_FENCE_API_ENABLED", () =>
isWebGLFenceEnabled(ENV.getNumber("WEBGL_VERSION"))
);
/**
* Tensors with size <= than this will be uploaded as uniforms, not textures.
*/
ENV.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM", () => {
// Use uniform uploads only when 32bit floats are supported. In
// 16bit
// environments there are problems with comparing a 16bit texture value
// with a 32bit uniform value.
const useUniforms = ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED");
return useUniforms ? 4 : 0;
});
//# sourceMappingURL=flags_webgl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/addn_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class AddNProgram {
constructor(outputShape, shapes) {
this.outputShape = [];
this.outputShape = outputShape;
this.variableNames = shapes.map((_, i) => `T${i}`);
const snippets = [];
// Get target elements from every input tensor.
this.variableNames.forEach((variable) => {
snippets.push(`float v${variable} = get${variable}AtOutCoords();`);
});
// Calculate the sum of all elements.
const operation = this.variableNames
.map((variable) => {
return `v${variable}`;
})
.join(" + ");
this.userCode = `
void main() {
${snippets.join("\n ")}
float result = ${operation};
setOutput(result);
}
`;
}
}
//# sourceMappingURL=addn_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/addn_packed_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class AddNPackedProgram {
constructor(outputShape, shapes) {
this.outputShape = [];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = outputShape;
this.variableNames = shapes.map((_, i) => `T${i}`);
const snippets = [];
// Get target elements from every input tensor.
this.variableNames.forEach((variable) => {
snippets.push(`vec4 v${variable} = get${variable}AtOutCoords();`);
});
// Calculate the sum of all elements.
const operation = this.variableNames
.map((variable) => {
return `v${variable}`;
})
.join(" + ");
this.userCode = `
void main() {
${snippets.join("\n ")}
vec4 result = ${operation};
setOutput(result);
}
`;
}
}
//# sourceMappingURL=addn_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/argminmax_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ArgMinMaxProgram {
constructor(reduceInfo, op, firstPass) {
this.variableNames = ["A"];
const windowSize = reduceInfo.windowSize;
const batchSize = reduceInfo.batchSize;
const inSize = reduceInfo.inSize;
const outSize = Math.ceil(inSize / windowSize);
if (!firstPass) {
this.variableNames.push("bestIndicesA");
}
this.outputShape = [batchSize, outSize];
const compOp = op === "max" ? ">" : "<";
const indexSnippet = firstPass
? "inOffset + i;"
: "round(getBestIndicesA(batch, inOffset + i));";
this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${windowSize};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${windowSize}; i++) {
int inIdx = ${indexSnippet};
float candidate = getA(batch, inIdx);
if (candidate ${compOp} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`;
}
}
//# sourceMappingURL=argminmax_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/packing_util.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function getVecChannels(name, rank) {
return ["x", "y", "z", "w", "u", "v"].slice(0, rank).map((d) => `${name}.${d}`);
}
function getChannels(name, rank) {
if (rank === 1) {
return [name];
}
return getVecChannels(name, rank);
}
function getSourceCoords(rank, dims) {
if (rank === 1) {
return "rc";
}
let coords = "";
for (let i = 0; i < rank; i++) {
coords += dims[i];
if (i < rank - 1) {
coords += ",";
}
}
return coords;
}
//# sourceMappingURL=packing_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/glsl_version.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function getGlslDifferences() {
let version;
let attribute;
let varyingVs;
let varyingFs;
let texture2D;
let output;
let defineOutput;
let defineSpecialNaN;
let defineSpecialInf;
let defineRound;
if (Object(dist["env"])().getNumber("WEBGL_VERSION") === 2) {
version = "#version 300 es";
attribute = "in";
varyingVs = "out";
varyingFs = "in";
texture2D = "texture";
output = "outputColor";
defineOutput = "out vec4 outputColor;";
// Use custom isnan definition to work across differences between
// implementations on various platforms. While this should happen in ANGLE
// we still see differences between android and windows (on chrome) when
// using isnan directly.
defineSpecialNaN = `
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`;
// In webgl 2 we do not need to specify a custom isinf so there is no
// need for a special INFINITY constant.
defineSpecialInf = ``;
defineRound = `
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`;
} else {
version = "";
attribute = "attribute";
varyingVs = "varying";
varyingFs = "varying";
texture2D = "texture2D";
output = "gl_FragColor";
defineOutput = "";
// WebGL1 has no built in isnan so we define one here.
defineSpecialNaN = `
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`;
defineSpecialInf = `
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`;
defineRound = `
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`;
}
return {
version,
attribute,
varyingVs,
varyingFs,
texture2D,
output,
defineOutput,
defineSpecialNaN,
defineSpecialInf,
defineRound,
};
}
//# sourceMappingURL=glsl_version.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/shader_compiler_util.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Produces GLSL code that derives logical coordinates from a flat
* index. The code performs integer division with each stride and decrements
* the index until the index equals the final dimension coordinate.
*/
function getLogicalCoordinatesFromFlatIndex(coords, shape, index = "index") {
const strides = dist["util"].computeStrides(shape);
return strides
.map((stride, i) => {
const line1 = `int ${coords[i]} = ${index} / ${stride}`;
const line2 =
i === strides.length - 1
? `int ${coords[i + 1]} = ${index} - ${coords[i]} * ${stride}`
: `index -= ${coords[i]} * ${stride}`;
return `${line1}; ${line2};`;
})
.join("");
}
function buildVec(x) {
if (x.length === 1) {
return `${x[0]}`;
}
return `vec${x.length}(${x.join(",")})`;
}
/**
* Produces GLSL code that computes the dot product of the input x and y
* vectors. Handles splitting inputs into increments of vec4s when necessary.
*/
function dotify(x, y) {
if (x.length !== y.length) {
throw new Error(
`Vectors to be dotted must be of the same length -` + `got ${x.length} and ${y.length}`
);
}
const slices = [];
const nearestVec4 = Math.floor(x.length / 4);
const nearestVec4Remainder = x.length % 4;
for (let i = 0; i < nearestVec4; i++) {
const xSlice = x.slice(i * 4, i * 4 + 4);
const ySlice = y.slice(i * 4, i * 4 + 4);
slices.push(`${buildVec(xSlice)}, ${buildVec(ySlice)}`);
}
if (nearestVec4Remainder !== 0) {
let xSlice = x.slice(nearestVec4 * 4);
let ySlice = y.slice(nearestVec4 * 4);
if (xSlice.length === 1) {
xSlice = xSlice.map((d) => `float(${d})`);
ySlice = ySlice.map((d) => `float(${d})`);
}
slices.push(`${buildVec(xSlice)}, ${buildVec(ySlice)}`);
}
return slices.map((d, i) => `dot(${d})`).join("+");
}
/**
* Produces GLSL that computes the flat index from 3D coordinates.
*/
function getFlatIndexFrom3D(shape) {
const strides = dist["util"].computeStrides(shape).map((d) => d.toString());
return `
int getFlatIndex(ivec3 coords) {
return coords.x * ${strides[0]} + coords.y * ${strides[1]} + coords.z;
}
`;
}
const ENCODE_FLOAT_SNIPPET = `
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
`;
//# sourceMappingURL=shader_compiler_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/shader_compiler.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const { getBroadcastDims } = dist["backend_util"];
function makeShader(inputsInfo, outputShape, userCode, usesPackedTextures) {
const prefixSnippets = [];
inputsInfo.forEach((x) => {
const size = dist["util"].sizeFromShape(x.shapeInfo.logicalShape);
// Snippet when we decided to upload the values as uniform.
if (x.shapeInfo.isUniform) {
prefixSnippets.push(`uniform float ${x.name}${size > 1 ? `[${size}]` : ""};`);
} else {
prefixSnippets.push(`uniform sampler2D ${x.name};`);
prefixSnippets.push(`uniform int offset${x.name};`);
}
});
const inputPrefixSnippet = prefixSnippets.join("\n");
const inputSamplingSnippet = inputsInfo
.map((x) => getInputSamplingSnippet(x, outputShape, usesPackedTextures))
.join("\n");
const outTexShape = outputShape.texShape;
const glsl = getGlslDifferences();
const floatTextureSampleSnippet = getFloatTextureSampleSnippet(glsl);
let outputSamplingSnippet;
let floatTextureSetOutputSnippet;
let shaderPrefix = getShaderPrefix(glsl);
if (outputShape.isPacked) {
outputSamplingSnippet = getPackedOutputSamplingSnippet(
outputShape.logicalShape,
outTexShape
);
floatTextureSetOutputSnippet = getFloatTextureSetRGBASnippet(glsl);
} else {
outputSamplingSnippet = getOutputSamplingSnippet(outputShape.logicalShape, outTexShape);
floatTextureSetOutputSnippet = getFloatTextureSetRSnippet(glsl);
}
if (usesPackedTextures) {
shaderPrefix += SHADER_PACKED_PREFIX;
}
const source = [
shaderPrefix,
floatTextureSampleSnippet,
floatTextureSetOutputSnippet,
inputPrefixSnippet,
outputSamplingSnippet,
inputSamplingSnippet,
userCode,
].join("\n");
return source;
}
function getSamplerFromInInfo(inInfo) {
const shape = inInfo.shapeInfo.logicalShape;
switch (shape.length) {
case 0:
return getSamplerScalar(inInfo);
case 1:
return getSampler1D(inInfo);
case 2:
return getSampler2D(inInfo);
case 3:
return getSampler3D(inInfo);
case 4:
return getSampler4D(inInfo);
case 5:
return getSampler5D(inInfo);
case 6:
return getSampler6D(inInfo);
default:
throw new Error(`${shape.length}-D input sampling` + ` is not yet supported`);
}
}
function getPackedSamplerFromInInfo(inInfo) {
const shape = inInfo.shapeInfo.logicalShape;
switch (shape.length) {
case 0:
return getPackedSamplerScalar(inInfo);
case 1:
return getPackedSampler1D(inInfo);
case 2:
return getPackedSampler2D(inInfo);
case 3:
return getPackedSampler3D(inInfo);
default:
return getPackedSamplerND(inInfo);
}
}
function getInputSamplingSnippet(inInfo, outShapeInfo, usesPackedTextures = false) {
let res = "";
if (usesPackedTextures) {
res += getPackedSamplerFromInInfo(inInfo);
} else {
res += getSamplerFromInInfo(inInfo);
}
const inShape = inInfo.shapeInfo.logicalShape;
const outShape = outShapeInfo.logicalShape;
if (inShape.length <= outShape.length) {
if (usesPackedTextures) {
res += getPackedSamplerAtOutputCoords(inInfo, outShapeInfo);
} else {
res += getSamplerAtOutputCoords(inInfo, outShapeInfo);
}
}
return res;
}
function getPackedOutputSamplingSnippet(outShape, outTexShape) {
switch (outShape.length) {
case 0:
return getOutputScalarCoords();
case 1:
return getOutputPacked1DCoords(outShape, outTexShape);
case 2:
return getOutputPacked2DCoords(outShape, outTexShape);
case 3:
return getOutputPacked3DCoords(outShape, outTexShape);
default:
return getOutputPackedNDCoords(outShape, outTexShape);
}
}
function getOutputSamplingSnippet(outShape, outTexShape) {
switch (outShape.length) {
case 0:
return getOutputScalarCoords();
case 1:
return getOutput1DCoords(outShape, outTexShape);
case 2:
return getOutput2DCoords(outShape, outTexShape);
case 3:
return getOutput3DCoords(outShape, outTexShape);
case 4:
return getOutput4DCoords(outShape, outTexShape);
case 5:
return getOutput5DCoords(outShape, outTexShape);
case 6:
return getOutput6DCoords(outShape, outTexShape);
default:
throw new Error(`${outShape.length}-D output sampling is not yet supported`);
}
}
function getFloatTextureSampleSnippet(glsl) {
return `
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${glsl.texture2D}(textureSampler, uv).r;
}
`;
}
function getFloatTextureSetRSnippet(glsl) {
return `
void setOutput(float val) {
${glsl.output} = vec4(val, 0, 0, 0);
}
`;
}
function getFloatTextureSetRGBASnippet(glsl) {
return `
void setOutput(vec4 val) {
${glsl.output} = val;
}
`;
}
function getShaderPrefix(glsl) {
const SHADER_PREFIX = `${glsl.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${glsl.varyingFs} vec2 resultUV;
${glsl.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${glsl.defineSpecialNaN}
${glsl.defineSpecialInf}
${glsl.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
${SAMPLE_1D_SNIPPET}
${SAMPLE_2D_SNIPPET}
${SAMPLE_3D_SNIPPET}
`;
return SHADER_PREFIX;
}
const SAMPLE_1D_SNIPPET = `
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
const SAMPLE_2D_SNIPPET = `
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
const SAMPLE_3D_SNIPPET = `
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
const SHADER_PACKED_PREFIX = `
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
`;
function getOutputScalarCoords() {
return `
int getOutputCoords() {
return 0;
}
`;
}
function getOutputPacked1DCoords(shape, texShape) {
const packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
if (packedTexShape[0] === 1) {
return `
int getOutputCoords() {
return 2 * int(resultUV.x * ${packedTexShape[1]}.0);
}
`;
}
if (packedTexShape[1] === 1) {
return `
int getOutputCoords() {
return 2 * int(resultUV.y * ${packedTexShape[0]}.0);
}
`;
}
return `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
return 2 * (resTexRC.x * ${packedTexShape[1]} + resTexRC.y);
}
`;
}
function getOutput1DCoords(shape, texShape) {
if (texShape[0] === 1) {
return `
int getOutputCoords() {
return int(resultUV.x * ${texShape[1]}.0);
}
`;
}
if (texShape[1] === 1) {
return `
int getOutputCoords() {
return int(resultUV.y * ${texShape[0]}.0);
}
`;
}
return `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
return resTexRC.x * ${texShape[1]} + resTexRC.y;
}
`;
}
function getOutputPacked3DCoords(shape, texShape) {
const packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
const texelsInLogicalRow = Math.ceil(shape[2] / 2);
const texelsInBatch = texelsInLogicalRow * Math.ceil(shape[1] / 2);
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;
int b = index / ${texelsInBatch};
index -= b * ${texelsInBatch};
int r = 2 * (index / ${texelsInLogicalRow});
int c = imod(index, ${texelsInLogicalRow}) * 2;
return ivec3(b, r, c);
}
`;
}
function getOutput3DCoords(shape, texShape) {
const coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(["r", "c", "d"], shape);
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
${coordsFromIndexSnippet}
return ivec3(r, c, d);
}
`;
}
function getOutputPackedNDCoords(shape, texShape) {
const packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
const texelsInLogicalRow = Math.ceil(shape[shape.length - 1] / 2);
const texelsInBatch = texelsInLogicalRow * Math.ceil(shape[shape.length - 2] / 2);
let texelsInBatchN = texelsInBatch;
let batches = ``;
let coords = "b, r, c";
for (let b = 2; b < shape.length - 1; b++) {
texelsInBatchN *= shape[shape.length - b - 1];
batches =
`
int b${b} = index / ${texelsInBatchN};
index -= b${b} * ${texelsInBatchN};
` + batches;
coords = `b${b}, ` + coords;
}
return `
ivec${shape.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;
${batches}
int b = index / ${texelsInBatch};
index -= b * ${texelsInBatch};
int r = 2 * (index / ${texelsInLogicalRow});
int c = imod(index, ${texelsInLogicalRow}) * 2;
return ivec${shape.length}(${coords});
}
`;
}
function getOutput4DCoords(shape, texShape) {
const coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(
["r", "c", "d", "d2"],
shape
);
return `
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
${coordsFromIndexSnippet}
return ivec4(r, c, d, d2);
}
`;
}
function getOutput5DCoords(shape, texShape) {
const coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(
["r", "c", "d", "d2", "d3"],
shape
);
return `
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${texShape[0]},
${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
${coordsFromIndexSnippet}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`;
}
function getOutput6DCoords(shape, texShape) {
const coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(
["r", "c", "d", "d2", "d3", "d4"],
shape
);
return `
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
${coordsFromIndexSnippet}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`;
}
function getOutputPacked2DCoords(shape, texShape) {
const packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
if (dist["util"].arraysEqual(shape, texShape)) {
return `
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
}
`;
}
// texels needed to accommodate a logical row
const texelsInLogicalRow = Math.ceil(shape[1] / 2);
/**
* getOutputCoords
*
* resTexRC: The rows and columns of the texels. If you move over one
* texel to the right in the packed texture, you are moving over one column
* (not two).
*
* index: The texel index
*/
return `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;
int r = 2 * (index / ${texelsInLogicalRow});
int c = imod(index, ${texelsInLogicalRow}) * 2;
return ivec2(r, c);
}
`;
}
function getOutput2DCoords(shape, texShape) {
if (dist["util"].arraysEqual(shape, texShape)) {
return `
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${texShape[0]}, ${texShape[1]}));
}
`;
}
if (shape[1] === 1) {
return `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
return ivec2(index, 0);
}
`;
}
if (shape[0] === 1) {
return `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
return ivec2(0, index);
}
`;
}
return `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
int r = index / ${shape[1]};
int c = index - r * ${shape[1]};
return ivec2(r, c);
}
`;
}
function getFlatOffsetUniformName(texName) {
return `offset${texName}`;
}
function getPackedSamplerScalar(inputInfo) {
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const glsl = getGlslDifferences();
return `
vec4 ${funcName}() {
return ${glsl.texture2D}(${texName}, halfCR);
}
`;
}
function getSamplerScalar(inputInfo) {
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
if (inputInfo.shapeInfo.isUniform) {
return `float ${funcName}() {return ${texName};}`;
}
const [texNumR, texNumC] = inputInfo.shapeInfo.texShape;
if (texNumR === 1 && texNumC === 1) {
return `
float ${funcName}() {
return sampleTexture(${texName}, halfCR);
}
`;
}
const [tNumR, tNumC] = inputInfo.shapeInfo.texShape;
const offset = getFlatOffsetUniformName(texName);
return `
float ${funcName}() {
vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, ${offset});
return sampleTexture(${texName}, uv);
}
`;
}
function getPackedSampler1D(inputInfo) {
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const texShape = inputInfo.shapeInfo.texShape;
const packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
const glsl = getGlslDifferences();
return `
vec4 ${funcName}(int index) {
vec2 uv = packedUVfrom1D(
${packedTexShape[0]}, ${packedTexShape[1]}, index);
return ${glsl.texture2D}(${texName}, uv);
}
`;
}
function getSampler1D(inputInfo) {
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
if (inputInfo.shapeInfo.isUniform) {
// Uniform arrays will be less than 65505 (no risk of float16 overflow).
return `
float ${funcName}(int index) {
${getUniformSampler(inputInfo)}
}
`;
}
const texShape = inputInfo.shapeInfo.texShape;
const tNumR = texShape[0];
const tNumC = texShape[1];
if (tNumC === 1 && tNumR === 1) {
return `
float ${funcName}(int index) {
return sampleTexture(${texName}, halfCR);
}
`;
}
const offset = getFlatOffsetUniformName(texName);
if (tNumC === 1) {
return `
float ${funcName}(int index) {
vec2 uv = vec2(0.5, (float(index + ${offset}) + 0.5) / ${tNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
if (tNumR === 1) {
return `
float ${funcName}(int index) {
vec2 uv = vec2((float(index + ${offset}) + 0.5) / ${tNumC}.0, 0.5);
return sampleTexture(${texName}, uv);
}
`;
}
return `
float ${funcName}(int index) {
vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, index + ${offset});
return sampleTexture(${texName}, uv);
}
`;
}
function getPackedSampler2D(inputInfo) {
const shape = inputInfo.shapeInfo.logicalShape;
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const texShape = inputInfo.shapeInfo.texShape;
const texNumR = texShape[0];
const texNumC = texShape[1];
const glsl = getGlslDifferences();
if (texShape != null && dist["util"].arraysEqual(shape, texShape)) {
return `
vec4 ${funcName}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
return ${glsl.texture2D}(${texName}, uv);
}
`;
}
const packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
const valuesPerRow = Math.ceil(shape[1] / 2);
return `
vec4 ${funcName}(int row, int col) {
vec2 uv = packedUVfrom2D(${valuesPerRow}, ${packedTexShape[0]}, ${packedTexShape[1]}, row, col);
return ${glsl.texture2D}(${texName}, uv);
}
`;
}
function getSampler2D(inputInfo) {
const shape = inputInfo.shapeInfo.logicalShape;
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const texShape = inputInfo.shapeInfo.texShape;
if (texShape != null && dist["util"].arraysEqual(shape, texShape)) {
const texNumR = texShape[0];
const texNumC = texShape[1];
return `
float ${funcName}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
const { newShape, keptDims } = dist["util"].squeezeShape(shape);
const squeezedShape = newShape;
if (squeezedShape.length < shape.length) {
const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
const params = ["row", "col"];
return `
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col) {
return ${funcName}(${getSqueezedParams(params, keptDims)});
}
`;
}
if (inputInfo.shapeInfo.isUniform) {
// Uniform arrays will be less than 65505 (no risk of float16 overflow).
return `
float ${funcName}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${shape[1]}, 1)));
${getUniformSampler(inputInfo)}
}
`;
}
const texNumR = texShape[0];
const texNumC = texShape[1];
const offset = getFlatOffsetUniformName(texName);
if (texNumC === 1) {
// index is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col) {
float index = dot(vec3(row, col, ${offset}), vec3(${shape[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
if (texNumR === 1) {
// index is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col) {
float index = dot(vec3(row, col, ${offset}), vec3(${shape[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${texNumC}.0, 0.5);
return sampleTexture(${texName}, uv);
}
`;
}
return `
float ${funcName}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${shape[1]} + col + ${offset};
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
return sampleTexture(${texName}, uv);
}
`;
}
function getPackedSampler3D(inputInfo) {
const shape = inputInfo.shapeInfo.logicalShape;
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const texShape = inputInfo.shapeInfo.texShape;
const packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
if (shape[0] === 1) {
const squeezedShape = shape.slice(1);
const keptDims = [1, 2];
const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
const params = ["b", "row", "col"];
return `
${getPackedSamplerFromInInfo(newInputInfo)}
vec4 ${funcName}(int b, int row, int col) {
return ${funcName}(${getSqueezedParams(params, keptDims)});
}
`;
}
const texNumR = packedTexShape[0];
const texNumC = packedTexShape[1];
const valuesPerRow = Math.ceil(shape[2] / 2);
const texelsInBatch = valuesPerRow * Math.ceil(shape[1] / 2);
const glsl = getGlslDifferences();
return `
vec4 ${funcName}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${texNumR}, ${texNumC}, ${texelsInBatch}, ${valuesPerRow}, b, row, col);
return ${glsl.texture2D}(${texName}, uv);
}
`;
}
function getSampler3D(inputInfo) {
const shape = inputInfo.shapeInfo.logicalShape;
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const stride0 = shape[1] * shape[2];
const stride1 = shape[2];
const { newShape, keptDims } = dist["util"].squeezeShape(shape);
const squeezedShape = newShape;
if (squeezedShape.length < shape.length) {
const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
const params = ["row", "col", "depth"];
return `
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col, int depth) {
return ${funcName}(${getSqueezedParams(params, keptDims)});
}
`;
}
if (inputInfo.shapeInfo.isUniform) {
// Uniform arrays will be less than 65505 (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${stride0}, ${stride1}, 1)));
${getUniformSampler(inputInfo)}
}
`;
}
const texShape = inputInfo.shapeInfo.texShape;
const texNumR = texShape[0];
const texNumC = texShape[1];
const flatOffset = inputInfo.shapeInfo.flatOffset;
if (texNumC === stride0 && flatOffset == null) {
// texC is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${stride1}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
if (texNumC === stride1 && flatOffset == null) {
// texR is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${shape[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
const offset = getFlatOffsetUniformName(texName);
return `
float ${funcName}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${stride0} + col * ${stride1} + depth + ${offset};
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
return sampleTexture(${texName}, uv);
}
`;
}
function getPackedSamplerND(inputInfo) {
const shape = inputInfo.shapeInfo.logicalShape;
const rank = shape.length;
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const texShape = inputInfo.shapeInfo.texShape;
const packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
const texNumR = packedTexShape[0];
const texNumC = packedTexShape[1];
const valuesPerRow = Math.ceil(shape[rank - 1] / 2);
let texelsInBatch = valuesPerRow * Math.ceil(shape[rank - 2] / 2);
let params = `int b, int row, int col`;
let index = `b * ${texelsInBatch} + (row / 2) * ${valuesPerRow} + (col / 2)`;
for (let b = 2; b < rank - 1; b++) {
params = `int b${b}, ` + params;
texelsInBatch *= shape[rank - b - 1];
index = `b${b} * ${texelsInBatch} + ` + index;
}
const glsl = getGlslDifferences();
return `
vec4 ${funcName}(${params}) {
int index = ${index};
int texR = index / ${texNumC};
int texC = index - texR * ${texNumC};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}, ${texNumR});
return ${glsl.texture2D}(${texName}, uv);
}
`;
}
function getSampler4D(inputInfo) {
const shape = inputInfo.shapeInfo.logicalShape;
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const stride2 = shape[3];
const stride1 = shape[2] * stride2;
const stride0 = shape[1] * stride1;
const { newShape, keptDims } = dist["util"].squeezeShape(shape);
if (newShape.length < shape.length) {
const newInputInfo = squeezeInputInfo(inputInfo, newShape);
const params = ["row", "col", "depth", "depth2"];
return `
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col, int depth, int depth2) {
return ${funcName}(${getSqueezedParams(params, keptDims)});
}
`;
}
if (inputInfo.shapeInfo.isUniform) {
// Uniform arrays will be less than 65505 (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${stride0}, ${stride1}, ${stride2}, 1)));
${getUniformSampler(inputInfo)}
}
`;
}
const flatOffset = inputInfo.shapeInfo.flatOffset;
const texShape = inputInfo.shapeInfo.texShape;
const texNumR = texShape[0];
const texNumC = texShape[1];
if (texNumC === stride0 && flatOffset == null) {
// texC is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${stride1}, ${stride2}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
if (texNumC === stride2 && flatOffset == null) {
// texR is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${shape[1] * shape[2]}, ${shape[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
const offset = getFlatOffsetUniformName(texName);
return `
float ${funcName}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${stride0} + col * ${stride1} +
depth * ${stride2} + depth2;
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index + ${offset});
return sampleTexture(${texName}, uv);
}
`;
}
function getSampler5D(inputInfo) {
const shape = inputInfo.shapeInfo.logicalShape;
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const stride3 = shape[4];
const stride2 = shape[3] * stride3;
const stride1 = shape[2] * stride2;
const stride0 = shape[1] * stride1;
const { newShape, keptDims } = dist["util"].squeezeShape(shape);
if (newShape.length < shape.length) {
const newInputInfo = squeezeInputInfo(inputInfo, newShape);
const params = ["row", "col", "depth", "depth2", "depth3"];
return `
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
return ${funcName}(${getSqueezedParams(params, keptDims)});
}
`;
}
if (inputInfo.shapeInfo.isUniform) {
// Uniform arrays will be less than 65505 (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${stride0}, ${stride1}, ${stride2}, ${stride3})) +
depth3;
${getUniformSampler(inputInfo)}
}
`;
}
const flatOffset = inputInfo.shapeInfo.flatOffset;
const texShape = inputInfo.shapeInfo.texShape;
const texNumR = texShape[0];
const texNumC = texShape[1];
if (texNumC === stride0 && flatOffset == null) {
// texC is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${stride1}, ${stride2}, ${stride3}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
if (texNumC === stride3 && flatOffset == null) {
// texR is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${shape[1] * shape[2] * shape[3]},
${shape[2] * shape[3]}, ${shape[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
const offset = getFlatOffsetUniformName(texName);
return `
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +
depth2 * ${stride3} + depth3 + ${offset};
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
return sampleTexture(${texName}, uv);
}
`;
}
function getSampler6D(inputInfo) {
const shape = inputInfo.shapeInfo.logicalShape;
const texName = inputInfo.name;
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
const { newShape, keptDims } = dist["util"].squeezeShape(shape);
if (newShape.length < shape.length) {
const newInputInfo = squeezeInputInfo(inputInfo, newShape);
const params = ["row", "col", "depth", "depth2", "depth3", "depth4"];
return `
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${funcName}(${getSqueezedParams(params, keptDims)});
}
`;
}
const stride4 = shape[5];
const stride3 = shape[4] * stride4;
const stride2 = shape[3] * stride3;
const stride1 = shape[2] * stride2;
const stride0 = shape[1] * stride1;
if (inputInfo.shapeInfo.isUniform) {
// Uniform arrays will be less than 65505 (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${stride0}, ${stride1}, ${stride2}, ${stride3})) +
dot(
vec2(depth3, depth4),
vec2(${stride4}, 1)));
${getUniformSampler(inputInfo)}
}
`;
}
const flatOffset = inputInfo.shapeInfo.flatOffset;
const texShape = inputInfo.shapeInfo.texShape;
const texNumR = texShape[0];
const texNumC = texShape[1];
if (texNumC === stride0 && flatOffset == null) {
// texC is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${stride1}, ${stride2}, ${stride3}, ${stride4})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
if (texNumC === stride4 && flatOffset == null) {
// texR is used directly as physical (no risk of float16 overflow).
return `
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${shape[1] * shape[2] * shape[3] * shape[4]},
${shape[2] * shape[3] * shape[4]},
${shape[3] * shape[4]},
${shape[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;
}
const offset = getFlatOffsetUniformName(texName);
return `
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +
depth2 * ${stride3} + depth3 * ${stride4} + depth4 + ${offset};
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
return sampleTexture(${texName}, uv);
}
`;
}
function getUniformSampler(inputInfo) {
const texName = inputInfo.name;
const inSize = dist["util"].sizeFromShape(inputInfo.shapeInfo.logicalShape);
if (inSize < 2) {
return `return ${texName};`;
}
return `
for (int i = 0; i < ${inSize}; i++) {
if (i == index) {
return ${texName}[i];
}
}
`;
}
function getPackedSamplerAtOutputCoords(inputInfo, outShapeInfo) {
const texName = inputInfo.name;
const texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);
const funcName = "get" + texFuncSnippet + "AtOutCoords";
const inRank = inputInfo.shapeInfo.logicalShape.length;
const outRank = outShapeInfo.logicalShape.length;
const broadcastDims = getBroadcastDims(
inputInfo.shapeInfo.logicalShape,
outShapeInfo.logicalShape
);
const type = getCoordsDataType(outRank);
const rankDiff = outRank - inRank;
let coordsSnippet;
const fields = ["x", "y", "z", "w", "u", "v"];
if (inRank === 0) {
coordsSnippet = "";
} else if (outRank < 2 && broadcastDims.length >= 1) {
coordsSnippet = "coords = 0;";
} else {
coordsSnippet = broadcastDims
.map((d) => `coords.${fields[d + rankDiff]} = 0;`)
.join("\n");
}
let unpackedCoordsSnippet = "";
if (outRank < 2 && inRank > 0) {
unpackedCoordsSnippet = "coords";
} else {
unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape
.map((s, i) => `coords.${fields[i + rankDiff]}`)
.join(", ");
}
let output = `return outputValue;`;
const inSize = dist["util"].sizeFromShape(inputInfo.shapeInfo.logicalShape);
const isInputScalar = inSize === 1;
const outSize = dist["util"].sizeFromShape(outShapeInfo.logicalShape);
const isOutputScalar = outSize === 1;
if (inRank === 1 && !isInputScalar && !isOutputScalar) {
output = `
return vec4(outputValue.xy, outputValue.xy);
`;
} else if (isInputScalar && !isOutputScalar) {
if (outRank === 1) {
output = `
return vec4(outputValue.x, outputValue.x, 0., 0.);
`;
} else {
output = `
return vec4(outputValue.x);
`;
}
} else if (broadcastDims.length) {
const rows = inRank - 2;
const cols = inRank - 1;
if (broadcastDims.indexOf(rows) > -1 && broadcastDims.indexOf(cols) > -1) {
output = `return vec4(outputValue.x);`;
} else if (broadcastDims.indexOf(rows) > -1) {
output =
`return vec4(outputValue.x, outputValue.y, ` + `outputValue.x, outputValue.y);`;
} else if (broadcastDims.indexOf(cols) > -1) {
output = `return vec4(outputValue.xx, outputValue.zz);`;
}
}
return `
vec4 ${funcName}() {
${type} coords = getOutputCoords();
${coordsSnippet}
vec4 outputValue = get${texFuncSnippet}(${unpackedCoordsSnippet});
${output}
}
`;
}
function getSamplerAtOutputCoords(inputInfo, outShapeInfo) {
const texName = inputInfo.name;
const texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);
const funcName = "get" + texFuncSnippet + "AtOutCoords";
const outTexShape = outShapeInfo.texShape;
const inTexShape = inputInfo.shapeInfo.texShape;
const inRank = inputInfo.shapeInfo.logicalShape.length;
const outRank = outShapeInfo.logicalShape.length;
if (
!inputInfo.shapeInfo.isUniform &&
inRank === outRank &&
inputInfo.shapeInfo.flatOffset == null &&
dist["util"].arraysEqual(inTexShape, outTexShape)
) {
return `
float ${funcName}() {
return sampleTexture(${texName}, resultUV);
}
`;
}
const type = getCoordsDataType(outRank);
const broadcastDims = getBroadcastDims(
inputInfo.shapeInfo.logicalShape,
outShapeInfo.logicalShape
);
const rankDiff = outRank - inRank;
let coordsSnippet;
const fields = ["x", "y", "z", "w", "u", "v"];
if (inRank === 0) {
coordsSnippet = "";
} else if (outRank < 2 && broadcastDims.length >= 1) {
coordsSnippet = "coords = 0;";
} else {
coordsSnippet = broadcastDims
.map((d) => `coords.${fields[d + rankDiff]} = 0;`)
.join("\n");
}
let unpackedCoordsSnippet = "";
if (outRank < 2 && inRank > 0) {
unpackedCoordsSnippet = "coords";
} else {
unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape
.map((s, i) => `coords.${fields[i + rankDiff]}`)
.join(", ");
}
return `
float ${funcName}() {
${type} coords = getOutputCoords();
${coordsSnippet}
return get${texFuncSnippet}(${unpackedCoordsSnippet});
}
`;
}
function getCoordsDataType(rank) {
if (rank <= 1) {
return "int";
} else if (rank === 2) {
return "ivec2";
} else if (rank === 3) {
return "ivec3";
} else if (rank === 4) {
return "ivec4";
} else if (rank === 5) {
return "ivec5";
} else if (rank === 6) {
return "ivec6";
} else {
throw Error(`GPU for rank ${rank} is not yet supported`);
}
}
/** Returns a new input info (a copy) that has a squeezed logical shape. */
function squeezeInputInfo(inInfo, squeezedShape) {
// Deep copy.
const newInputInfo = JSON.parse(JSON.stringify(inInfo));
newInputInfo.shapeInfo.logicalShape = squeezedShape;
return newInputInfo;
}
function getSqueezedParams(params, keptDims) {
return keptDims.map((d) => params[d]).join(", ");
}
//# sourceMappingURL=shader_compiler.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/argminmax_packed_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class argminmax_packed_gpu_ArgMinMaxPackedProgram {
constructor(shape, windowSize, op, firstPass) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = true;
dist["util"].assert(
shape.length > 2,
() =>
`Packed arg${
op.charAt(0).toUpperCase() + op.slice(1)
} supports only inputs with rank above 2.`
);
const inSize = shape[shape.length - 1];
const outSize = Math.ceil(inSize / windowSize);
this.outputShape = shape.slice(0, -1);
if (outSize > 1) {
this.outputShape.push(outSize);
}
if (!firstPass) {
this.variableNames.push("bestIndicesA");
}
const outShape = this.outputShape;
const rank = outShape.length;
const dtype = getCoordsDataType(rank);
const coords = getChannels("coords", rank);
let sourceLocSetup;
let sourceRank;
if (outSize === 1) {
sourceRank = rank + 1;
const sourceLocDType = getCoordsDataType(sourceRank);
sourceLocSetup = `
${sourceLocDType} sourceLocR = ${sourceLocDType}(${coords.join()}, 0);
++${coords[rank - 1]};
${sourceLocDType} sourceLocG = ${sourceLocDType}(${coords.join()}, 0);
++${coords[rank - 2]};
${sourceLocDType} sourceLocA = ${sourceLocDType}(${coords.join()}, 0);
--${coords[rank - 1]};
${sourceLocDType} sourceLocB = ${sourceLocDType}(${coords.join()}, 0);
--${coords[rank - 2]};`;
} else {
sourceRank = rank;
sourceLocSetup = `
${dtype} sourceLocR = coords;
++${coords[rank - 1]};
${dtype} sourceLocG = coords;
++${coords[rank - 2]};
${dtype} sourceLocA = coords;
--${coords[rank - 1]};
${dtype} sourceLocB = coords;
--${coords[rank - 2]};`;
}
const channels = ["x", "y", "z", "w", "u", "v"].slice(0, sourceRank);
const inChannel = "." + channels[sourceRank - 1]; // e.g. ".b" for rank 3.
const intChannels = channels.map((x) => "int " + x);
const srcRCoords = getChannels("sourceLocR", sourceRank - 1).concat("inIdx.r");
const srcGCoords = getChannels("sourceLocG", sourceRank - 1).concat("inIdx.g");
const srcBCoords = getChannels("sourceLocB", sourceRank - 1).concat("inIdx.b");
const srcACoords = getChannels("sourceLocA", sourceRank - 1).concat("inIdx.a");
const compOp = op === "max" ? "greaterThan" : "lessThan";
const fetchCandidateIdx = firstPass
? ""
: `
inIdx = round(vec4(getBestIndicesAChannel(${srcRCoords.join()}),
getBestIndicesAChannel(${srcGCoords.join()}),
getBestIndicesAChannel(${srcBCoords.join()}),
getBestIndicesAChannel(${srcACoords.join()})));`;
const fetchValue = `vec4(
getAChannel(${srcRCoords.join()}),
hasNextCol ? getAChannel(${srcGCoords.join()}) : 0.,
hasNextRow ? getAChannel(${srcBCoords.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${srcACoords.join()}) : 0.)`;
const getBestIndicesAChannelSnippet = firstPass
? ""
: `
float getBestIndicesAChannel(${intChannels.join()}) {
return getChannel(getBestIndicesA(${channels.join()}),
vec2(${channels.slice(-2).join()}));
}`;
this.userCode = `
float getAChannel(${intChannels.join()}) {
return getChannel(getA(${channels.join()}),
vec2(${channels.slice(-2).join()}));
}
${getBestIndicesAChannelSnippet}
void main() {
${dtype} coords = getOutputCoords();
bool hasNextCol = ${coords[rank - 1]} < ${outShape[rank - 1] - 1};
bool hasNextRow = ${coords[rank - 2]} < ${outShape[rank - 2] - 1};
${sourceLocSetup}
ivec4 srcIdx = ivec4(sourceLocR${inChannel}, sourceLocG${inChannel},
sourceLocB${inChannel}, sourceLocA${inChannel}) * ${windowSize};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${fetchValue};
for (int i = 0; i < ${windowSize}; i++) {
inIdx = srcIdx;
${fetchCandidateIdx}
vec4 candidate = ${fetchValue};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${compOp}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`;
}
}
//# sourceMappingURL=argminmax_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/avg_pool_backprop_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class AvgPool2DBackpropProgram {
constructor(convInfo) {
this.variableNames = ["dy"];
this.outputShape = convInfo.inShape;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const avgMultiplier = 1 / (filterHeight * filterWidth);
this.userCode = `
const ivec2 pads = ivec2(${padTop}, ${padLeft});
const float avgMultiplier = float(${avgMultiplier});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${effectiveFilterWidth};
wC+= ${dilationWidth}) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`;
}
}
class AvgPool3DBackpropProgram {
constructor(convInfo) {
this.variableNames = ["dy"];
this.outputShape = convInfo.inShape;
const filterDepth = convInfo.filterDepth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterDepth = convInfo.effectiveFilterDepth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);
this.userCode = `
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
const float avgMultiplier = float(${avgMultiplier});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${effectiveFilterDepth};
wD += ${dilationDepth}) {
float dyD = float(dyDCorner + wD) / ${strideDepth}.0;
if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${effectiveFilterWidth};
wC += ${dilationWidth}) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`;
}
}
//# sourceMappingURL=avg_pool_backprop_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/batchnorm_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class batchnorm_gpu_BatchNormProgram {
constructor(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon) {
this.outputShape = [];
this.variableNames = ["x", "mean", "variance"];
dist["backend_util"].assertAndGetBroadcastShape(xShape, meanShape);
dist["backend_util"].assertAndGetBroadcastShape(xShape, varianceShape);
let offsetSnippet = "0.0";
if (offsetShape != null) {
dist["backend_util"].assertAndGetBroadcastShape(xShape, offsetShape);
this.variableNames.push("offset");
offsetSnippet = "getOffsetAtOutCoords()";
}
let scaleSnippet = "1.0";
if (scaleShape != null) {
dist["backend_util"].assertAndGetBroadcastShape(xShape, scaleShape);
this.variableNames.push("scale");
scaleSnippet = "getScaleAtOutCoords()";
}
this.outputShape = xShape;
this.userCode = `
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${offsetSnippet};
float scale = ${scaleSnippet};
float inv = scale * inversesqrt(variance + float(${varianceEpsilon}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`;
}
}
//# sourceMappingURL=batchnorm_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/batchnorm_packed_gpu.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class batchnorm_packed_gpu_BatchNormPackedProgram {
constructor(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon) {
this.packedInputs = true;
this.packedOutput = true;
this.variableNames = ["x", "mean", "variance"];
dist["backend_util"].assertAndGetBroadcastShape(xShape, meanShape);
dist["backend_util"].assertAndGetBroadcastShape(xShape, varianceShape);
let offsetSnippet = "vec4(0.0)";
if (offsetShape != null) {
dist["backend_util"].assertAndGetBroadcastShape(xShape, offsetShape);
this.variableNames.push("offset");
offsetSnippet = "getOffsetAtOutCoords()";
}
let scaleSnippet = "vec4(1.0)";
if (scaleShape != null) {
dist["backend_util"].assertAndGetBroadcastShape(xShape, scaleShape);
this.variableNames.push("scale");
scaleSnippet = "getScaleAtOutCoords()";
}
this.outputShape = xShape;
this.userCode = `
void main() {
vec4 offset = ${offsetSnippet};
vec4 scale = ${scaleSnippet};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${varianceEpsilon}));
setOutput((x - mean) * inv + offset);
}
`;
}
}
//# sourceMappingURL=batchnorm_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/binaryop_complex_gpu.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// (Ar + Ai)(Br + Bi) =
// ArBr + ArBi + AiBr + AiBi = ArBr - AB + ArBi + AiBr
// Yr = ArBr - AB
// Yi = ArBi + AiBr
const COMPLEX_MULTIPLY = {
REAL: "return areal * breal - aimag * bimag;",
IMAG: "return areal * bimag + aimag * breal;",
};
class binaryop_complex_gpu_BinaryOpComplexProgram {
constructor(op, aShape, bShape) {
this.variableNames = ["AReal", "AImag", "BReal", "BImag"];
this.outputShape = dist["backend_util"].assertAndGetBroadcastShape(aShape, bShape);
this.userCode = `
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${op}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`;
}
}
//# sourceMappingURL=binaryop_complex_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/binaryop_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const CHECK_NAN_SNIPPET = `
if (isnan(a)) return a;
if (isnan(b)) return b;
`;
const ADD = "return a + b;";
const SUB = "return a - b;";
const MUL = "return a * b;";
// Without the equality check div produces 0.9999 for a = b, which when
// floored can cause errors.
const DIV = `
if (a == b) {
return 1.0;
};
return a / b;`;
// We use native integer division to deal with floating point imprecision. Since
// we implement floor division and glsl implements truncated division, we
// correct for this by subtracting 1 from result when the result is negative and
// there is a remainder.
const INT_DIV = `
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
`;
const POW = `
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
`;
const binaryop_gpu_SQUARED_DIFFERENCE = "return (a - b) * (a - b);";
const EQUAL = `return float(a == b);`;
const NOT_EQUAL = `return float(a != b);`;
const LESS = `return float(a < b);`;
const LESS_EQUAL = `return float(a <= b);`;
const GREATER = `return float(a > b);`;
const GREATER_EQUAL = `return float(a >= b);`;
const LOGICAL_AND = `return float(a >= 1.0 && b >= 1.0);`;
const LOGICAL_OR = `return float(a >= 1.0 || b >= 1.0);`;
const MAX =
CHECK_NAN_SNIPPET +
`
return max(a, b);
`;
const MIN =
CHECK_NAN_SNIPPET +
`
return min(a, b);
`;
const MOD = `if (b == 0.0) return NAN;
return mod(a, b);`;
const ATAN2 =
CHECK_NAN_SNIPPET +
`
return atan(a, b);
`;
const ELU_DER = `return (b >= 1.0) ? a : a * (b + 1.0);`;
const PRELU = `return (a < 0.) ? b * a : a;`;
class binaryop_gpu_BinaryOpProgram {
constructor(op, aShape, bShape) {
this.variableNames = ["A", "B"];
this.outputShape = dist["backend_util"].assertAndGetBroadcastShape(aShape, bShape);
this.userCode = `
float binaryOperation(float a, float b) {
${op}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`;
}
}
//# sourceMappingURL=binaryop_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/binaryop_packed_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const binaryop_packed_gpu_CHECK_NAN_SNIPPET = `
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;
// We do the same as in ./binaryop_gpu, with vec4 and ivec4.
// On Linux, the vectorized implementation produces NaNs when a and b are 0.
const binaryop_packed_gpu_DIV = `
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
`;
const binaryop_packed_gpu_INT_DIV = `
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
`;
const binaryop_packed_gpu_POW =
`
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
` +
binaryop_packed_gpu_CHECK_NAN_SNIPPET +
`
return result;
`;
const binaryop_packed_gpu_PRELU = `
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
const binaryop_packed_gpu_ELU_DER = `
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`;
const binaryop_packed_gpu_ATAN2 =
`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` +
binaryop_packed_gpu_CHECK_NAN_SNIPPET +
`
return result;
`;
const binaryop_packed_gpu_EQUAL = `
return vec4(equal(a, b));
`;
const binaryop_packed_gpu_NOT_EQUAL = `
return vec4(notEqual(a, b));
`;
const binaryop_packed_gpu_LESS = `
return vec4(lessThan(a, b));
`;
const binaryop_packed_gpu_LESS_EQUAL = `
return vec4(lessThanEqual(a, b));
`;
const binaryop_packed_gpu_GREATER = `
return vec4(greaterThan(a, b));
`;
const binaryop_packed_gpu_GREATER_EQUAL = `
return vec4(greaterThanEqual(a, b));
`;
const binaryop_packed_gpu_LOGICAL_AND = `
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`;
const binaryop_packed_gpu_LOGICAL_OR = `
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`;
const binaryop_packed_gpu_MAX =
`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` +
binaryop_packed_gpu_CHECK_NAN_SNIPPET +
`
return result;
`;
const binaryop_packed_gpu_MIN =
`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` +
binaryop_packed_gpu_CHECK_NAN_SNIPPET +
`
return result;
`;
const binaryop_packed_gpu_MOD =
`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
` +
binaryop_packed_gpu_CHECK_NAN_SNIPPET +
`
return result;
`;
class binaryop_packed_gpu_BinaryOpPackedProgram {
constructor(op, aShape, bShape, checkOutOfBounds = false) {
this.variableNames = ["A", "B"];
this.supportsBroadcasting = true;
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = dist["backend_util"].assertAndGetBroadcastShape(aShape, bShape);
const rank = this.outputShape.length;
let checkOutOfBoundsString = "";
if (checkOutOfBounds) {
if (rank === 0 || dist["util"].sizeFromShape(this.outputShape) === 1) {
checkOutOfBoundsString = `
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;
} else {
const dtype = getCoordsDataType(rank);
checkOutOfBoundsString = `
${dtype} coords = getOutputCoords();
`;
if (rank === 1) {
checkOutOfBoundsString += `
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;
} else {
const channels = getChannels("coords", rank);
checkOutOfBoundsString += `
bool nextRowOutOfBounds =
(${channels[rank - 2]} + 1) >= ${this.outputShape[rank - 2]};
bool nextColOutOfBounds =
(${channels[rank - 1]} + 1) >= ${this.outputShape[rank - 1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`;
}
}
}
this.userCode = `
vec4 binaryOperation(vec4 a, vec4 b) {
${op}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${checkOutOfBoundsString}
setOutput(result);
}
`;
}
}
//# sourceMappingURL=binaryop_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/clip_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ClipProgram {
constructor(aShape) {
this.variableNames = ["A"];
this.outputShape = aShape;
this.userCode = `
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`;
}
getCustomSetupFunc(min, max) {
return (gpgpu, webGLProgram) => {
if (this.minLoc == null) {
this.minLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, "minVal");
this.maxLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, "maxVal");
}
gpgpu.gl.uniform1f(this.minLoc, min);
gpgpu.gl.uniform1f(this.maxLoc, max);
};
}
}
//# sourceMappingURL=clip_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/clip_packed_gpu.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ClipPackedProgram {
constructor(aShape) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = aShape;
this.userCode = `
uniform float minVal;
uniform float maxVal;
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`;
}
getCustomSetupFunc(min, max) {
return (gpgpu, webGLProgram) => {
if (this.minLoc == null) {
this.minLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, "minVal");
this.maxLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, "maxVal");
}
gpgpu.gl.uniform1f(this.minLoc, min);
gpgpu.gl.uniform1f(this.maxLoc, max);
};
}
}
//# sourceMappingURL=clip_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/complex_abs_gpu.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ComplexAbsProgram {
constructor(shape) {
this.variableNames = ["real", "imag"];
this.outputShape = shape;
this.userCode = `
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
`;
}
}
//# sourceMappingURL=complex_abs_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/concat_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class concat_gpu_ConcatProgram {
// Concats 2d tensors along axis=1. See comments in MathBackendWebGL.concat().
constructor(shapes) {
this.outputShape = [];
this.outputShape = dist["backend_util"].computeOutShape(shapes, 1 /* axis */);
this.variableNames = shapes.map((_, i) => `T${i}`);
const offsets = new Array(shapes.length - 1);
offsets[0] = shapes[0][1];
for (let i = 1; i < offsets.length; i++) {
offsets[i] = offsets[i - 1] + shapes[i][1];
}
const snippets = [`if (yC < ${offsets[0]}) setOutput(getT0(yR, yC));`];
for (let i = 1; i < offsets.length; i++) {
const shift = offsets[i - 1];
snippets.push(
`else if (yC < ${offsets[i]}) ` + `setOutput(getT${i}(yR, yC-${shift}));`
);
}
const lastIndex = offsets.length;
const lastShift = offsets[offsets.length - 1];
snippets.push(`else setOutput(getT${lastIndex}(yR, yC-${lastShift}));`);
this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${snippets.join("\n ")}
}
`;
}
}
//# sourceMappingURL=concat_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/concat_packed_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class concat_packed_gpu_ConcatPackedProgram {
constructor(shapes, axis) {
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = [];
this.outputShape = dist["backend_util"].computeOutShape(shapes, axis);
const shape = this.outputShape;
const rank = shape.length;
const dtype = getCoordsDataType(rank);
const coords = getChannels("coords", rank);
const channels = ["x", "y", "z", "w", "u", "v"].slice(0, rank);
this.variableNames = shapes.map((_, i) => `T${i}`);
const offsets = new Array(shapes.length - 1);
offsets[0] = shapes[0][axis];
for (let i = 1; i < offsets.length; i++) {
offsets[i] = offsets[i - 1] + shapes[i][axis];
}
const channel = channels[axis];
const lastChannels = channels.slice(-2);
const allChannels = channels.join();
let getValueSnippet = `if (${channel} < ${offsets[0]}) {
return getChannel(
getT0(${allChannels}), vec2(${lastChannels.join()}));
}`;
for (let i = 1; i < offsets.length; i++) {
const shift = offsets[i - 1];
// Note: the >= comparison below may seem unnecessary given the check
// above but is needed to workaround branch execution issues on some
// devices. It makes all the conditions exclusive without relying on
// execution order.
getValueSnippet += `
if (${channel} < ${offsets[i]} && ${channel} >= ${offsets[i - 1]}) {
return getChannel(
getT${i}(${shiftedChannels(channels, channel, shift)}),
vec2(${shiftedChannels(lastChannels, channel, shift)}));
}`;
}
const lastIndex = offsets.length;
const shift = offsets[offsets.length - 1];
getValueSnippet += `
return getChannel(
getT${lastIndex}(${shiftedChannels(channels, channel, shift)}),
vec2(${shiftedChannels(lastChannels, channel, shift)}));`;
this.userCode = `
float getValue(${channels.map((x) => "int " + x)}) {
${getValueSnippet}
}
void main() {
${dtype} coords = getOutputCoords();
vec4 result = vec4(getValue(${coords}), 0., 0., 0.);
${coords[rank - 1]} = ${coords[rank - 1]} + 1;
if (${coords[rank - 1]} < ${shape[rank - 1]}) {
result.g = getValue(${coords});
}
${coords[rank - 2]} = ${coords[rank - 2]} + 1;
if (${coords[rank - 2]} < ${shape[rank - 2]}) {
result.a = getValue(${coords});
}
${coords[rank - 1]} = ${coords[rank - 1]} - 1;
if (${coords[rank - 2]} < ${shape[rank - 2]} &&
${coords[rank - 1]} < ${shape[rank - 1]}) {
result.b = getValue(${coords});
}
setOutput(result);
}
`;
}
}
/**
* Return an expression for coordinates into a vector where a given channel
* will be offset by [shift].
*
* @param channels the channels to consider
* @param channel the channel we want shifted
* @param shift the amount to subtract from the channel.
*
* @returns a string of the form 'x, y-[shift], z' where any one channel can
* have the shift applied.
*/
function shiftedChannels(channels, channel, shift) {
const channelIdx = channels.indexOf(channel);
const res = channels.map((c, idx) => {
if (idx === channelIdx) {
return `${c} - ${shift}`;
} else {
return c;
}
});
return res.join();
}
//# sourceMappingURL=concat_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/conv_backprop_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Conv2DDerFilterProgram {
constructor(convInfo) {
this.variableNames = ["x", "dy"];
this.outputShape = convInfo.filterShape;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const isChannelsLast = convInfo.dataFormat === "channelsLast";
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${convInfo.batchSize}; b++) {
for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {
int xR = wR + yR * ${strideHeight} - ${padTop};
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {
int xC = wC + yC * ${strideWidth} - ${padLeft};
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
if (${isChannelsLast}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`;
}
}
class Conv2DDerInputProgram {
constructor(convInfo) {
this.variableNames = ["dy", "W"];
this.outputShape = convInfo.inShape;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const isChannelsLast = convInfo.dataFormat === "channelsLast";
const padTop = filterHeight - 1 - convInfo.padInfo.top;
const padLeft = filterWidth - 1 - convInfo.padInfo.left;
const rowDim = isChannelsLast ? 1 : 2;
const colDim = isChannelsLast ? 2 : 3;
const channelDim = isChannelsLast ? 3 : 1;
this.userCode = `
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${channelDim}];
ivec2 dyCorner = ivec2(coords[${rowDim}], coords[${colDim}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${filterHeight}; wR++) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${filterHeight} - 1 - wR;
for (int wC = 0; wC < ${filterWidth}; wC++) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${filterWidth} - 1 - wC;
for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {
if (${isChannelsLast}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`;
}
}
class Conv3DDerFilterProgram {
constructor(convInfo) {
this.variableNames = ["x", "dy"];
this.outputShape = convInfo.filterShape;
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const padFront = convInfo.padInfo.front;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
this.userCode = `
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${convInfo.batchSize}; b++) {
for (int yF = 0; yF < ${convInfo.outDepth}; yF++) {
int xF = wF + yF * ${strideDepth} - ${padFront};
if (xF < 0 || xF >= ${convInfo.inDepth}) {
continue;
}
for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {
int xR = wR + yR * ${strideHeight} - ${padTop};
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {
int xC = wC + yC * ${strideWidth} - ${padLeft};
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`;
}
}
class Conv3DDerInputProgram {
constructor(convInfo) {
this.variableNames = ["dy", "W"];
this.outputShape = convInfo.inShape;
const filterDepth = convInfo.filterDepth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const padFront = filterDepth - 1 - convInfo.padInfo.front;
const padTop = filterHeight - 1 - convInfo.padInfo.top;
const padLeft = filterWidth - 1 - convInfo.padInfo.left;
this.userCode = `
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${filterDepth}; wF++) {
float dyF = float(dyFCorner + wF) / ${strideDepth}.0;
if (dyF < 0.0 || dyF >= ${convInfo.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${filterDepth} - 1 - wF;
for (int wR = 0; wR < ${filterHeight}; wR++) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${filterHeight} - 1 - wR;
for (int wC = 0; wC < ${filterWidth}; wC++) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${filterWidth} - 1 - wC;
for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`;
}
}
//# sourceMappingURL=conv_backprop_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/conv_backprop_gpu_depthwise.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class DepthwiseConv2DDerFilterProgram {
constructor(convInfo) {
this.variableNames = ["x", "dy"];
this.outputShape = convInfo.filterShape;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const channelMul = convInfo.outChannels / convInfo.inChannels;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${channelMul} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${convInfo.batchSize}; b++) {
for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {
int xR = wR + yR * ${strideHeight} - ${padTop};
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {
int xC = wC + yC * ${strideWidth} - ${padLeft};
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`;
}
}
class DepthwiseConv2DDerInputProgram {
constructor(convInfo) {
this.variableNames = ["dy", "W"];
this.outputShape = convInfo.inShape;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const padTop = filterHeight - 1 - convInfo.padInfo.top;
const padLeft = filterWidth - 1 - convInfo.padInfo.left;
const channelMul = convInfo.outChannels / convInfo.inChannels;
this.userCode = `
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${filterHeight}; wR++) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${filterHeight} - 1 - wR;
for (int wC = 0; wC < ${filterWidth}; wC++) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${filterWidth} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${channelMul}; dm++) {
int d2 = d1 * ${channelMul} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`;
}
}
//# sourceMappingURL=conv_backprop_gpu_depthwise.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/conv_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Conv2DProgram {
constructor(
convInfo,
addBias = false,
activation = null,
hasPreluActivationWeights = false
) {
this.variableNames = ["x", "W"];
this.outputShape = convInfo.outShape;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;
const inputDepthVec4Remainder = convInfo.inChannels % 4;
const isChannelsLast = convInfo.dataFormat === "channelsLast";
const rowDim = isChannelsLast ? 1 : 2;
const colDim = isChannelsLast ? 2 : 3;
const channelDim = isChannelsLast ? 3 : 1;
let activationSnippet = "",
applyActivationSnippet = "";
if (activation) {
if (hasPreluActivationWeights) {
activationSnippet = `float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${activation}
}`;
} else {
activationSnippet = `
float activation(float x) {
${activation}
}
`;
}
applyActivationSnippet = `result = activation(result);`;
}
const addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
if (addBias) {
this.variableNames.push("bias");
}
if (hasPreluActivationWeights) {
this.variableNames.push("preluActivationWeights");
}
this.userCode = `
${activationSnippet}
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${channelDim}];
ivec2 xRCCorner =
ivec2(coords[${rowDim}], coords[${colDim}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${filterHeight}; wR++) {
int xR = xRCorner + wR * ${dilationHeight};
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int wC = 0; wC < ${filterWidth}; wC++) {
int xC = xCCorner + wC * ${dilationWidth};
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${inputDepthNearestVec4}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${isChannelsLast}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${inputDepthVec4Remainder === 1}) {
if (${isChannelsLast}) {
dotProd +=
getX(batch, xR, xC, ${inputDepthNearestVec4}) *
getW(wR, wC, ${inputDepthNearestVec4}, d2);
} else {
dotProd +=
getX(batch, ${inputDepthNearestVec4}, xR, xC) *
getW(wR, wC, ${inputDepthNearestVec4}, d2);
}
} else if (${inputDepthVec4Remainder === 2}) {
vec2 wValues = vec2(
getW(wR, wC, ${inputDepthNearestVec4}, d2),
getW(wR, wC, ${inputDepthNearestVec4} + 1, d2)
);
if (${isChannelsLast}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${inputDepthNearestVec4}),
getX(batch, xR, xC, ${inputDepthNearestVec4} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${inputDepthNearestVec4}, xR, xC),
getX(batch, ${inputDepthNearestVec4} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${inputDepthVec4Remainder === 3}) {
vec3 wValues = vec3(
getW(wR, wC, ${inputDepthNearestVec4}, d2),
getW(wR, wC, ${inputDepthNearestVec4} + 1, d2),
getW(wR, wC, ${inputDepthNearestVec4} + 2, d2)
);
if (${isChannelsLast}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${inputDepthNearestVec4}),
getX(batch, xR, xC, ${inputDepthNearestVec4} + 1),
getX(batch, xR, xC, ${inputDepthNearestVec4} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${inputDepthNearestVec4}, xR, xC),
getX(batch, ${inputDepthNearestVec4} + 1, xR, xC),
getX(batch, ${inputDepthNearestVec4} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${addBiasSnippet}
${applyActivationSnippet}
setOutput(result);
}
`;
}
}
class Conv3DProgram {
constructor(convInfo) {
this.variableNames = ["x", "W"];
this.outputShape = convInfo.outShape;
const padFront = convInfo.padInfo.front;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const filterDepth = convInfo.filterDepth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;
const inputDepthVec4Remainder = convInfo.inChannels % 4;
this.userCode = `
const ivec3 strides = ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${filterDepth}; wF++) {
int xF = xFCorner + wF * ${dilationDepth};
if (xF < 0 || xF >= ${convInfo.inDepth}) {
continue;
}
for (int wR = 0; wR < ${filterHeight}; wR++) {
int xR = xRCorner + wR * ${dilationHeight};
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int wC = 0; wC < ${filterWidth}; wC++) {
int xC = xCCorner + wC * ${dilationWidth};
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${inputDepthNearestVec4}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${inputDepthVec4Remainder === 1}) {
dotProd +=
getX(batch, xF, xR, xC, ${inputDepthNearestVec4}) *
getW(wF, wR, wC, ${inputDepthNearestVec4}, d2);
} else if (${inputDepthVec4Remainder === 2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),
getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),
getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${inputDepthVec4Remainder === 3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),
getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1),
getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),
getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2),
getW(wF, wR, wC, ${inputDepthNearestVec4} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`;
}
}
//# sourceMappingURL=conv_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/conv_gpu_depthwise.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class DepthwiseConv2DProgram {
constructor(convInfo, addBias = false, activation = null, hasPreluActivation = false) {
this.variableNames = ["x", "W"];
this.outputShape = convInfo.outShape;
const xNumRows = convInfo.inHeight;
const xNumCols = convInfo.inWidth;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const channelMul = convInfo.outChannels / convInfo.inChannels;
let activationSnippet = "",
applyActivationSnippet = "";
if (activation) {
if (hasPreluActivation) {
activationSnippet = `float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${activation}
}`;
} else {
activationSnippet = `
float activation(float x) {
${activation}
}
`;
}
applyActivationSnippet = `result = activation(result);`;
}
const addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
if (addBias) {
this.variableNames.push("bias");
}
if (hasPreluActivation) {
this.variableNames.push("preluActivationWeights");
}
this.userCode = `
${activationSnippet}
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${channelMul};
int q = d2 - d1 * ${channelMul};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${filterHeight}; wR++) {
int xR = xRCorner + wR * ${dilationHeight};
if (xR < 0 || xR >= ${xNumRows}) {
continue;
}
for (int wC = 0; wC < ${filterWidth}; wC++) {
int xC = xCCorner + wC * ${dilationWidth};
if (xC < 0 || xC >= ${xNumCols}) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${addBiasSnippet}
${applyActivationSnippet}
setOutput(result);
}
`;
}
}
//# sourceMappingURL=conv_gpu_depthwise.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/conv_packed_gpu_depthwise.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class conv_packed_gpu_depthwise_DepthwiseConvPacked2DProgram {
constructor(convInfo, addBias = false, activation = null, hasPreluActivation = false) {
this.variableNames = ["x", "W"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = convInfo.outShape;
const xNumRows = convInfo.inHeight;
const xNumCols = convInfo.inWidth;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const texelsAcross = filterWidth;
let mainLoop = `int xR; int xC; int xCOffset;`;
for (let r = 0; r < filterHeight; r++) {
for (let c = 0; c < filterWidth; c++) {
mainLoop += `
vec4 xTexelR${r}C${c * 2} = vec4(0.);
vec4 wR${r}C${c} = vec4(0.);
vec4 xR${r}C${c} = vec4(0.);`;
}
}
/**
* This vectorized implementation works by gathering the values needed for
* each output channel's dot product into vec4's and then multiplying them
* all together (this happens in the final double for-loop below). Most of
* the main loop consists of constructing these vec4's with the minimum
* number of texture2D calls, which means making use of all four returned
* values from a texture2D call at once.
*/
for (let r = 0; r < filterHeight; r++) {
for (let texelC = 0; texelC < texelsAcross; texelC++) {
const c = texelC * 2;
mainLoop += `
xR = xRCorner + ${r * dilationHeight};
xC = xCCorner + ${c * dilationWidth};
`;
if (strideWidth === 1) {
if (c < filterWidth) {
// If padding is odd, the outer texels have to be composed.
if (padLeft % 2 === 1) {
// TODO: Ensure vec4 previous does not result in redundant sample,
// and avoid setting xTexelRC's that exceed the boundary in the
// first place rather than resetting them to vec4(0)).
// To compute xCOffset:
// - If padding is odd, we must add 1 to ensure we ask for an
// even-numbered row.
// - We subtract 2 to access the previous texel.
mainLoop += `
xCOffset = xC + 1;
if(xR >= 0 && xR < ${xNumRows} && xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${xNumCols}) {
xTexelR${r}C${c}.zw = vec2(0.);
}
} else {
xTexelR${r}C${c} = vec4(0.);
}
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < ${xNumRows} && xCOffset >= 0 && xCOffset < ${xNumCols}) {
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${xNumCols}) {
previous.zw = vec2(0.);
}
xR${r}C${c} = vec4(previous.zw, xTexelR${r}C${c}.xy);
} else {
xR${r}C${c} = vec4(0, 0, xTexelR${r}C${c}.xy);
}
`;
} else {
// Padding is even, so xRC corresponds to a single texel.
mainLoop += `
if(xR >= 0 && xR < ${xNumRows} && xC >= 0 && xC < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xC, d1);
} else {
xTexelR${r}C${c} = vec4(0.);
}
xR${r}C${c} = xTexelR${r}C${c};
`;
}
if (c + 1 < filterWidth) {
// If dilation is even, the second entry should match the first
// (either both are composed or both are single samples). But if
// dilation is odd, then the second entry should be the opposite
// of the first (if the first is composed, the second is a single
// sample, and vice versa.)
const nextTexelOffset =
padLeft % 2 === 0
? dist["util"].nearestLargerEven(dilationWidth)
: dilationWidth;
if (
(dilationWidth % 2 === 0 && padLeft % 2 === 1) ||
(dilationWidth % 2 !== 0 && padLeft % 2 !== 1)
) {
mainLoop += `
xCOffset = xC + ${padLeft % 2} + ${nextTexelOffset};
if(xR >= 0 && xR < ${xNumRows} &&
xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c + 2} = getX(batch, xR, xCOffset, d1);
}
`;
// If dilation > 1 then the xRC's will not be able to share any
// values, so each xRC will require two unique calls to getX.
if (dilationWidth > 1) {
mainLoop += `
xCOffset -= 2;
if(xR >= 0 && xR < ${xNumRows} &&
xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${r}C${c} = vec4(0.);
}
`;
}
mainLoop += `
xR${r}C${c + 1} = vec4(
xTexelR${r}C${c}.zw, xTexelR${r}C${c + 2}.xy);
`;
} else {
mainLoop += `
xCOffset = xC + ${nextTexelOffset};
if(xR >= 0 && xR < ${xNumRows} &&
xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c + 2} = getX(batch, xR, xCOffset, d1);
}
xR${r}C${c + 1} = xTexelR${r}C${c + 2};
`;
}
}
}
} else {
// stride > 1
if (c < filterWidth) {
mainLoop += `
if(xR >= 0 && xR < ${xNumRows}) {
`;
// Depending on whether padLeft is even or odd, we want either the
// xy or zw channels from X texels for xR${r}C${c}. If padLeft is
// even, xR${r}C${c + 1} is simply the zw channels of texels we've
// already sampled. But if padLeft is odd, xR${r}C{$c + 1}.zw will
// need to come from the xy channels of a new texel, hence the `vec4
// final` initialized below.
if (padLeft % 2 === 1) {
mainLoop += `
xCOffset = xC + 1 - ${strideWidth};
if(xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${r}C${c} = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < ${xNumCols}) {
xTexelR${r}C${c + 2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${r}C${c + 2} = vec4(0.);
}
xR${r}C${c} = vec4(
xTexelR${r}C${c}.zw, xTexelR${r}C${c + 2}.zw);
`;
if (c + 1 < filterWidth) {
mainLoop += `
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${strideWidth};
if(xCOffset >= 0 && xCOffset < ${xNumCols}) {
final = getX(batch, xR, xCOffset, d1);
}
xR${r}C${c + 1} = vec4(xTexelR${r}C${c + 2}.xy, final.xy);
`;
}
} else {
mainLoop += `
if(xC >= 0 && xC < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xC, d1);
} else {
xTexelR${r}C${c} = vec4(0.);
}
xCOffset = xC + ${strideWidth};
if(xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c + 2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${r}C${c + 2} = vec4(0.);
}
xR${r}C${c} = vec4(
xTexelR${r}C${c}.xy, xTexelR${r}C${c + 2}.xy);
`;
if (c + 1 < filterWidth) {
mainLoop += `
xR${r}C${c + 1} = vec4(
xTexelR${r}C${c}.zw, xTexelR${r}C${c + 2}.zw);
`;
}
}
mainLoop += `}`;
}
}
if (c < filterWidth) {
mainLoop += `
vec4 wTexelR${r}C${c} = getW(${r}, ${c}, d1, q);
wR${r}C${c} = vec4(wTexelR${r}C${c}.xz, wTexelR${r}C${c}.xz);
`;
if (c + 1 < filterWidth) {
mainLoop += `
vec4 wTexelR${r}C${c + 1} = getW(${r}, ${c + 1}, d1, q);
wR${r}C${c + 1} =
vec4(wTexelR${r}C${c + 1}.xz, wTexelR${r}C${c + 1}.xz);`;
}
}
}
}
for (let r = 0; r < filterHeight; r++) {
for (let c = 0; c < filterWidth; c++) {
mainLoop += `dotProd += xR${r}C${c} * wR${r}C${c};`;
}
}
let activationSnippet = "",
applyActivationSnippet = "";
if (activation) {
if (hasPreluActivation) {
activationSnippet = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${activation}
}`;
} else {
activationSnippet = `vec4 activation(vec4 x) {
${activation}
}`;
}
applyActivationSnippet = `result = activation(result);`;
}
const addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
if (addBias) {
this.variableNames.push("bias");
}
if (hasPreluActivation) {
this.variableNames.push("preluActivationWeights");
}
this.userCode = `
${activationSnippet}
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
${mainLoop}
vec4 result = dotProd;
${addBiasSnippet}
${applyActivationSnippet}
setOutput(result);
}
`;
}
}
//# sourceMappingURL=conv_packed_gpu_depthwise.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/crop_and_resize_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class CropAndResizeProgram {
constructor(imageShape, boxShape, cropSize, method, extrapolationValue) {
this.variableNames = ["Image", "Boxes", "BoxInd"];
this.outputShape = [];
const [batch, imageHeight, imageWidth, depth] = imageShape;
const [numBoxes] = boxShape;
const [cropHeight, cropWidth] = cropSize;
this.outputShape = [numBoxes, cropHeight, cropWidth, depth];
const methodId = method === "bilinear" ? 1 : 0;
const [inputHeightFloat, inputWidthFloat] = [
`${imageHeight - 1}.0`,
`${imageWidth - 1}.0`,
];
const [heightRatio, heightScale, inY] =
cropHeight > 1
? [
`${(imageHeight - 1) / (cropHeight - 1)}`,
"(y2-y1) * height_ratio",
`y1*${inputHeightFloat} + float(y)*(height_scale)`,
]
: ["0.0", "0.0", `0.5 * (y1+y2) * ${inputHeightFloat}`];
const [widthRatio, widthScale, inX] =
cropWidth > 1
? [
`${(imageWidth - 1) / (cropWidth - 1)}`,
"(x2-x1) * width_ratio",
`x1*${inputWidthFloat} + float(x)*(width_scale)`,
]
: ["0.0", "0.0", `0.5 * (x1+x2) * ${inputWidthFloat}`];
// Reference implementation
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/crop_and_resize_op_gpu.cu.cc
this.userCode = `
const float height_ratio = float(${heightRatio});
const float width_ratio = float(${widthRatio});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${batch}) {
return;
}
float height_scale = ${heightScale};
float width_scale = ${widthScale};
float in_y = ${inY};
if( in_y < 0.0 || in_y > ${inputHeightFloat} ) {
setOutput(float(${extrapolationValue}));
return;
}
float in_x = ${inX};
if( in_x < 0.0 || in_x > ${inputWidthFloat} ) {
setOutput(float(${extrapolationValue}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${methodId} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
`;
}
}
//# sourceMappingURL=crop_and_resize_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/cumsum_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class cumsum_gpu_CumSumProgram {
constructor(shape, exclusive, reverse) {
this.variableNames = ["x"];
this.outputShape = shape;
const rank = shape.length;
const finalDim = shape[shape.length - 1];
const comparator = reverse ? "<" : ">";
this.userCode = `
int getIndex(int i) {
${reverse ? `return ${finalDim} -i - 1;` : "return i;"}
}
void main() {
${getCoordsDataType(rank)} coords = getOutputCoords();
int end = ${getFinalCoord(rank, "coords")};
float val = 0.0;
for (int i = ${finalDim} - 1; i >= 0; i -= 1) {
int idx = getIndex(i);
if (idx ${comparator} end) {
continue;
}
if (idx == end && ${exclusive}) {
continue;
}
${getFinalCoord(rank, "coords")} = idx;
val += getX(${getCoords(rank, "coords")});
}
setOutput(val);
}
`;
}
}
function getCoords(rank, name) {
if (rank === 1) {
return `${name}`;
} else if (rank === 2) {
return `${name}.x, ${name}.y`;
} else if (rank === 3) {
return `${name}.x, ${name}.y, ${name}.z`;
} else if (rank === 4) {
return `${name}.x, ${name}.y, ${name}.z, ${name}.w`;
} else {
throw Error(`Cumulative sum for rank ${rank} is not yet supported`);
}
}
function getFinalCoord(rank, name) {
if (rank === 1) {
return `${name}`;
} else if (rank === 2) {
return `${name}.y`;
} else if (rank === 3) {
return `${name}.z`;
} else if (rank === 4) {
return `${name}.w`;
} else {
throw Error(`Cumulative sum for rank ${rank} is not yet supported`);
}
}
//# sourceMappingURL=cumsum_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/decode_matrix_gpu.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.
* =============================================================================
*/
class decode_matrix_gpu_DecodeMatrixProgram {
constructor(outputShape) {
this.variableNames = ["A"];
this.packedInputs = false;
this.packedOutput = true;
this.outPackingScheme = PackingScheme.DENSE;
const texShape = getDenseTexShape(outputShape);
const glsl = getGlslDifferences();
this.outputShape = outputShape;
this.userCode = `
ivec3 outCoordsFromFlatIndex(int index) {
${getLogicalCoordinatesFromFlatIndex(["r", "c", "d"], outputShape)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = 4 * (resTexRC.x * ${texShape[1]} + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
${glsl.output} = result;
}
`;
}
}
//# sourceMappingURL=decode_matrix_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/decode_matrix_packed_gpu.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.
* =============================================================================
*/
class decode_matrix_packed_gpu_DecodeMatrixPackedProgram {
constructor(outputShape) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = true;
this.outPackingScheme = PackingScheme.DENSE;
const texShape = getDenseTexShape(outputShape);
const glsl = getGlslDifferences();
this.outputShape = outputShape;
this.userCode = `
ivec3 outCoordsFromFlatIndex(int index) {
${getLogicalCoordinatesFromFlatIndex(["r", "c", "d"], outputShape)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = 4 * (resTexRC.x * ${texShape[1]} + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
${glsl.output} = result;
}
`;
}
}
//# sourceMappingURL=decode_matrix_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/depth_to_space_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class DepthToSpaceProgram {
constructor(outputShape, blockSize, dataFormat) {
this.variableNames = ["x"];
this.outputShape = [];
this.outputShape = outputShape;
this.blockSize = blockSize;
this.dataFormat = dataFormat;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${blockSize};
int offset_h = imod(h, ${blockSize});
int in_w = w / ${blockSize};
int offset_w = imod(w, ${blockSize});
int offset_d = (offset_h * ${blockSize} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`;
}
getHeightCoordString() {
if (this.dataFormat === "NHWC") {
return `coords[1]`;
} else {
return `coords[2]`;
}
}
getWidthCoordString() {
if (this.dataFormat === "NHWC") {
return `coords[2]`;
} else {
return `coords[3]`;
}
}
getDepthCoordString() {
if (this.dataFormat === "NHWC") {
return `coords[3]`;
} else {
return `coords[1]`;
}
}
getOutputDepthSize() {
if (this.dataFormat === "NHWC") {
return this.outputShape[3];
} else {
return this.outputShape[1];
}
}
getInputSamplingString() {
if (this.dataFormat === "NHWC") {
return `getX(b, in_h, in_w, in_d)`;
} else {
return `getX(b, in_d, in_h, in_w)`;
}
}
}
//# sourceMappingURL=depth_to_space_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/diag_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class DiagProgram {
constructor(size) {
this.variableNames = ["X"];
this.outputShape = [size, size];
this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`;
}
}
//# sourceMappingURL=diag_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/encode_float_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class encode_float_gpu_EncodeFloatProgram {
constructor(outputShape) {
this.variableNames = ["A"];
this.outTexUsage = TextureUsage.DOWNLOAD;
const glsl = getGlslDifferences();
this.outputShape = outputShape;
this.userCode = `
${ENCODE_FLOAT_SNIPPET}
void main() {
float x = getAAtOutCoords();
${glsl.output} = encode_float(x);
}
`;
}
}
//# sourceMappingURL=encode_float_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/encode_float_packed_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class encode_float_packed_gpu_EncodeFloatPackedProgram {
constructor(outputShape) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = false;
this.outTexUsage = TextureUsage.DOWNLOAD;
const glsl = getGlslDifferences();
this.outputShape = outputShape;
this.userCode = `
${ENCODE_FLOAT_SNIPPET}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${glsl.output} = encode_float(x);
}
`;
}
}
//# sourceMappingURL=encode_float_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/encode_matrix_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class encode_matrix_gpu_EncodeMatrixProgram {
constructor(outputShape, texShape, inputIsUnsignedByte = false) {
this.variableNames = ["A"];
const glsl = getGlslDifferences();
const [height, width] = texShape;
this.outputShape = outputShape;
let output = `result`;
if (inputIsUnsignedByte) {
output = `floor(result * 255. + 0.5)`;
}
this.userCode = `
${getFlatIndexFrom3D(outputShape)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / ${width};
int c = imod(flatIndex, ${width});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${width}.0, ${height}.0);
vec4 values = ${glsl.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
${glsl.output} = vec4(${output}, 0., 0., 0.);
}
`;
}
}
//# sourceMappingURL=encode_matrix_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/encode_matrix_packed_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/*
This is how the shader encodes a tensor with shape = [2, 3, 5]
(indices are [batch, row, col]).
000|001 002|003 004|xxx 020|021 022|023 024|xxx
------- ------- ------- ------- ------- -------
010|011 012|013 014|xxx xxx|xxx xxx|xxx xxx|xxx
100|101 102|103 104|xxx 120|121 122|123 124|xxx
------- ------- ------- ------- ------- -------
110|111 112|113 114|xxx xxx|xxx xxx|xxx xxx|xxx
Single texels contain only values from the same batch, and from adjacent rows
and columns.
*/
class encode_matrix_packed_gpu_EncodeMatrixPackedProgram {
constructor(outputShape, texShape, inputIsUnsignedByte = false) {
this.variableNames = ["A"];
this.packedInputs = false;
this.packedOutput = true;
const glsl = getGlslDifferences();
const [height, width] = texShape;
this.outputShape = outputShape;
let mainLoop = "";
let output = "result";
if (inputIsUnsignedByte) {
output = "floor(result * 255. + 0.5)";
}
for (let row = 0; row <= 1; row++) {
for (let col = 0; col <= 1; col++) {
const channel = row * 2 + col;
mainLoop += `
localCoords = coords;
if(localCoords[2] + ${col} < ${outputShape[2]}) {
localCoords[2] += ${col};
if(localCoords[1] + ${row} < ${outputShape[1]}) {
localCoords[1] += ${row};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
r = flatIndex / ${width};
c = imod(flatIndex, ${width});
uv = (vec2(c, r) + halfCR) / vec2(${width}.0, ${height}.0);
values = ${glsl.texture2D}(A, uv);
if(offset == 0) {
result[${channel}] = values[0];
} else if(offset == 1) {
result[${channel}] = values[1];
} else if(offset == 2) {
result[${channel}] = values[2];
} else {
result[${channel}] = values[3];
}
}
}
`;
}
}
this.userCode = `
${getFlatIndexFrom3D(outputShape)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${mainLoop}
${glsl.output} = ${output};
}
`;
}
}
//# sourceMappingURL=encode_matrix_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/fft_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const COMPLEX_FFT = {
REAL: "return real * expR - imag * expI;",
IMAG: "return real * expI + imag * expR;",
};
class FFTProgram {
constructor(op, inputShape, inverse) {
this.variableNames = ["real", "imag"];
const innerDim = inputShape[1];
this.outputShape = inputShape;
const exponentMultiplierSnippet = inverse ? `2.0 * ${Math.PI}` : `-2.0 * ${Math.PI}`;
const resultDenominator = inverse ? `${innerDim}.0` : "1.0";
this.userCode = `
const float exponentMultiplier = ${exponentMultiplierSnippet};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${op}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${innerDim});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${innerDim}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${resultDenominator};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`;
}
}
//# sourceMappingURL=fft_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/fill_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class FillProgram {
constructor(shape, value) {
this.outputShape = [];
this.variableNames = ["x"];
this.outputShape = shape;
this.userCode = `
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`;
}
getCustomSetupFunc(value) {
return (gpgpu, webGLProgram) => {
if (this.valueLoc == null) {
this.valueLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, "value");
}
gpgpu.gl.uniform1f(this.valueLoc, value);
};
}
}
//# sourceMappingURL=fill_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/gather_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class gather_gpu_GatherProgram {
constructor(aShape, indicesLength, axis) {
this.variableNames = ["A", "indices"];
const outputShape = aShape.slice();
outputShape[axis] = indicesLength;
this.outputShape = outputShape;
this.rank = outputShape.length;
const dtype = getCoordsDataType(this.rank);
const sourceCoords = gather_gpu_getSourceCoords(aShape, axis);
this.userCode = `
void main() {
${dtype} resRC = getOutputCoords();
setOutput(getA(${sourceCoords}));
}
`;
}
}
function gather_gpu_getSourceCoords(aShape, axis) {
const rank = aShape.length;
if (rank > 4) {
throw Error(`Gather for rank ${rank} is not yet supported`);
}
if (rank === 1) {
return `int(getIndices(resRC))`;
}
const currentCoords = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"];
const sourceCoords = [];
for (let i = 0; i < aShape.length; i++) {
if (i === axis) {
sourceCoords.push(`int(getIndices(${currentCoords[i]}))`);
} else {
sourceCoords.push(`${currentCoords[i]}`);
}
}
return sourceCoords.join();
}
//# sourceMappingURL=gather_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/gather_nd_gpu.js
class gather_nd_gpu_GatherNDProgram {
constructor(sliceDim, strides, shape) {
this.sliceDim = sliceDim;
this.strides = strides;
this.variableNames = ["x", "indices"];
this.outputShape = shape;
const stridesType = getCoordsDataType(strides.length);
const dtype = getCoordsDataType(shape.length);
const strideString = this.sliceDim > 1 ? "strides[j]" : "strides";
this.userCode = `
${stridesType} strides = ${stridesType}(${this.strides});
void main() {
${dtype} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${strideString};
}
setOutput(getX(flattenIndex, coords[1]));
}
`;
}
}
//# sourceMappingURL=gather_nd_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/gpgpu_util.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function gpgpu_util_createVertexShader(gl, debug) {
const glsl = getGlslDifferences();
const vertexShaderSource = `${glsl.version}
precision highp float;
${glsl.attribute} vec3 clipSpacePos;
${glsl.attribute} vec2 uv;
${glsl.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;
return createVertexShader(gl, debug, vertexShaderSource);
}
function createVertexBuffer(gl, debug) {
// [x y z u v] * [upper-left, lower-left, upper-right, lower-right]
const vertexArray = new Float32Array([
-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0,
]);
return createStaticVertexBuffer(gl, debug, vertexArray);
}
function createIndexBuffer(gl, debug) {
// OpenGL (and WebGL) have "CCW == front" winding
const triangleVertexIndices = new Uint16Array([0, 1, 2, 2, 1, 3]);
return createStaticIndexBuffer(gl, debug, triangleVertexIndices);
}
function createAndConfigureTexture(
gl,
debug,
width,
height,
internalFormat,
textureFormat,
textureType
) {
validateTextureSize(width, height);
const texture = createTexture(gl, debug);
const tex2d = gl.TEXTURE_2D;
callAndCheck(gl, debug, () => gl.bindTexture(tex2d, texture));
callAndCheck(gl, debug, () => gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE));
callAndCheck(gl, debug, () => gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE));
callAndCheck(gl, debug, () => gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST));
callAndCheck(gl, debug, () => gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST));
callAndCheck(gl, debug, () =>
gl.texImage2D(
tex2d,
0,
internalFormat,
width,
height,
0,
textureFormat,
textureType,
null
)
);
callAndCheck(gl, debug, () => gl.bindTexture(gl.TEXTURE_2D, null));
return texture;
}
function createFloat32MatrixTexture(gl, debug, rows, columns, textureConfig) {
const [width, height] = getUnpackedMatrixTextureShapeWidthHeight(rows, columns);
return createAndConfigureTexture(
gl,
debug,
width,
height,
textureConfig.internalFormatFloat,
textureConfig.textureFormatFloat,
gl.FLOAT
);
}
function createFloat16MatrixTexture(gl, debug, rows, columns, textureConfig) {
const [width, height] = getUnpackedMatrixTextureShapeWidthHeight(rows, columns);
return createAndConfigureTexture(
gl,
debug,
width,
height,
textureConfig.internalFormatHalfFloat,
textureConfig.textureFormatFloat,
textureConfig.textureTypeHalfFloat
);
}
function createUnsignedBytesMatrixTexture(gl, debug, rows, columns, textureConfig) {
const [width, height] = getUnpackedMatrixTextureShapeWidthHeight(rows, columns);
return createAndConfigureTexture(
gl,
debug,
width,
height,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE
);
}
function createPackedMatrixTexture(gl, debug, rows, columns, textureConfig) {
const [width, height] = getPackedMatrixTextureShapeWidthHeight(rows, columns);
return createAndConfigureTexture(
gl,
debug,
width,
height,
textureConfig.internalFormatPackedFloat,
gl.RGBA,
gl.FLOAT
);
}
function createFloat16PackedMatrixTexture(gl, debug, rows, columns, textureConfig) {
const [width, height] = getPackedMatrixTextureShapeWidthHeight(rows, columns);
return createAndConfigureTexture(
gl,
debug,
width,
height,
textureConfig.internalFormatPackedHalfFloat,
gl.RGBA,
textureConfig.textureTypeHalfFloat
);
}
function bindVertexProgramAttributeStreams(gl, debug, program, vertexBuffer) {
const posOffset = 0; // x is the first buffer element
const uvOffset = 3 * 4; // uv comes after [x y z]
const stride = 3 * 4 + 2 * 4; // xyz + uv, each entry is 4-byte float.
callAndCheck(gl, debug, () => gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer));
const success = bindVertexBufferToProgramAttribute(
gl,
debug,
program,
"clipSpacePos",
vertexBuffer,
3,
stride,
posOffset
);
return (
success &&
bindVertexBufferToProgramAttribute(
gl,
debug,
program,
"uv",
vertexBuffer,
2,
stride,
uvOffset
)
);
}
function uploadDenseMatrixToTexture(gl, debug, texture, width, height, data, textureConfig) {
callAndCheck(gl, debug, () => gl.bindTexture(gl.TEXTURE_2D, texture));
let dataForUpload, texelDataType, internalFormat;
if (data instanceof Uint8Array) {
dataForUpload = new Uint8Array(width * height * 4);
texelDataType = gl.UNSIGNED_BYTE;
internalFormat = gl.RGBA;
} else {
dataForUpload = new Float32Array(width * height * 4);
texelDataType = gl.FLOAT;
internalFormat = textureConfig.internalFormatPackedFloat;
}
dataForUpload.set(data);
callAndCheck(gl, debug, () =>
gl.texImage2D(
gl.TEXTURE_2D,
0,
internalFormat,
width,
height,
0,
gl.RGBA,
texelDataType,
dataForUpload
)
);
callAndCheck(gl, debug, () => gl.bindTexture(gl.TEXTURE_2D, null));
}
function uploadPixelDataToTexture(gl, debug, texture, pixels) {
callAndCheck(gl, debug, () => gl.bindTexture(gl.TEXTURE_2D, texture));
if (pixels.data instanceof Uint8Array) {
callAndCheck(gl, debug, () =>
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
pixels.width,
pixels.height,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
pixels.data
)
);
} else {
callAndCheck(gl, debug, () =>
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, pixels)
);
}
callAndCheck(gl, debug, () => gl.bindTexture(gl.TEXTURE_2D, null));
}
function createBufferFromOutputTexture(gl2, debug, rows, columns, textureConfig) {
// Create and bind the buffer.
const buffer = gl2.createBuffer();
callAndCheck(gl2, debug, () => gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer));
// Initialize the buffer to the size of the texture in bytes.
const bytesPerFloat = 4;
const valuesPerTexel = 4;
const bufferSizeBytes = bytesPerFloat * valuesPerTexel * rows * columns;
callAndCheck(gl2, debug, () =>
gl2.bufferData(gl2.PIXEL_PACK_BUFFER, bufferSizeBytes, gl2.STREAM_READ)
);
// Enqueue a command on the GPU command queue to copy of texture into the
// buffer.
callAndCheck(gl2, debug, () => gl2.readPixels(0, 0, columns, rows, gl2.RGBA, gl2.FLOAT, 0));
callAndCheck(gl2, debug, () => gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null));
return buffer;
}
function downloadFloat32MatrixFromBuffer(gl, buffer, size) {
const gl2 = gl;
const downloadTarget = new Float32Array(size);
gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);
gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);
gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);
return downloadTarget;
}
function downloadByteEncodedFloatMatrixFromOutputTexture(
gl,
debug,
rows,
columns,
textureConfig
) {
const [w, h] = getUnpackedMatrixTextureShapeWidthHeight(rows, columns);
const numChannels = 4;
const downloadTarget = new Uint8Array(
getUnpackedArraySizeFromMatrixSize(rows * columns, numChannels)
);
callAndCheck(gl, debug, () =>
gl.readPixels(
0,
0,
w,
h,
textureConfig.downloadTextureFormat,
gl.UNSIGNED_BYTE,
downloadTarget
)
);
// By wrapping the buffer in a Float32Array, we use native browser IEEE 754
// decoding of the 4 bytes that back each 32 bit float.
return new Float32Array(downloadTarget.buffer);
}
function downloadPackedMatrixFromBuffer(
gl,
buffer,
batch,
rows,
cols,
physicalRows,
physicalCols,
textureConfig
) {
const gl2 = gl;
const downloadTarget = new Float32Array(
getPackedRGBAArraySizeFromMatrixShape(physicalRows, physicalCols)
);
gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);
gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);
gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);
return downloadTarget;
}
function downloadMatrixFromPackedOutputTexture(gl, debug, physicalRows, physicalCols) {
const packedRGBA = new Float32Array(physicalRows * physicalCols * 4);
callAndCheck(gl, debug, () =>
gl.readPixels(0, 0, physicalCols, physicalRows, gl.RGBA, gl.FLOAT, packedRGBA)
);
return packedRGBA;
}
//# sourceMappingURL=gpgpu_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/gpgpu_context.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class gpgpu_context_GPGPUContext {
constructor(gl) {
this.outputTexture = null;
this.program = null;
this.disposed = false;
this.vertexAttrsAreBound = false;
this.itemsToPoll = [];
const glVersion = Object(dist["env"])().getNumber("WEBGL_VERSION");
if (gl != null) {
this.gl = gl;
setWebGLContext(glVersion, gl);
} else {
this.gl = getWebGLContext(glVersion);
}
// WebGL 2.0 enables texture floats without an extension.
let COLOR_BUFFER_FLOAT = "WEBGL_color_buffer_float";
const COLOR_BUFFER_HALF_FLOAT = "EXT_color_buffer_half_float";
if (Object(dist["env"])().getNumber("WEBGL_VERSION") === 1) {
const TEXTURE_FLOAT = "OES_texture_float";
const TEXTURE_HALF_FLOAT = "OES_texture_half_float";
this.textureFloatExtension = getExtensionOrThrow(this.gl, this.debug, TEXTURE_FLOAT);
if (hasExtension(this.gl, TEXTURE_HALF_FLOAT)) {
this.textureHalfFloatExtension = getExtensionOrThrow(
this.gl,
this.debug,
TEXTURE_HALF_FLOAT
);
} else if (Object(dist["env"])().get("WEBGL_FORCE_F16_TEXTURES")) {
throw new Error(
"GL context does not support half float textures, yet the " +
"environment flag WEBGL_FORCE_F16_TEXTURES is set to true."
);
}
this.colorBufferFloatExtension = this.gl.getExtension(COLOR_BUFFER_FLOAT);
if (hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {
this.colorBufferHalfFloatExtension = getExtensionOrThrow(
this.gl,
this.debug,
COLOR_BUFFER_HALF_FLOAT
);
} else if (Object(dist["env"])().get("WEBGL_FORCE_F16_TEXTURES")) {
throw new Error(
"GL context does not support color renderable half floats, yet " +
"the environment flag WEBGL_FORCE_F16_TEXTURES is set to true."
);
}
} else {
COLOR_BUFFER_FLOAT = "EXT_color_buffer_float";
if (hasExtension(this.gl, COLOR_BUFFER_FLOAT)) {
this.colorBufferFloatExtension = this.gl.getExtension(COLOR_BUFFER_FLOAT);
} else if (hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {
this.colorBufferHalfFloatExtension = this.gl.getExtension(COLOR_BUFFER_HALF_FLOAT);
} else {
throw new Error("GL context does not support color renderable floats");
}
}
this.vertexBuffer = createVertexBuffer(this.gl, this.debug);
this.indexBuffer = createIndexBuffer(this.gl, this.debug);
this.framebuffer = createFramebuffer(this.gl, this.debug);
this.textureConfig = getTextureConfig(this.gl, this.textureHalfFloatExtension);
}
get debug() {
return Object(dist["env"])().getBool("DEBUG");
}
dispose() {
if (this.disposed) {
return;
}
if (this.program != null) {
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."
);
}
if (this.outputTexture != null) {
console.warn(
"Disposing a GPGPUContext that still has a bound output matrix " +
"texture. This is probably a resource leak, delete the output " +
"matrix texture with GPGPUContext.deleteMatrixTexture before " +
"disposing."
);
}
const gl = this.gl;
callAndCheck(gl, this.debug, () => gl.finish());
callAndCheck(gl, this.debug, () => gl.bindFramebuffer(gl.FRAMEBUFFER, null));
callAndCheck(gl, this.debug, () => gl.deleteFramebuffer(this.framebuffer));
callAndCheck(gl, this.debug, () => gl.bindBuffer(gl.ARRAY_BUFFER, null));
callAndCheck(gl, this.debug, () => gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null));
callAndCheck(gl, this.debug, () => gl.deleteBuffer(this.indexBuffer));
this.disposed = true;
}
createFloat32MatrixTexture(rows, columns) {
this.throwIfDisposed();
return createFloat32MatrixTexture(this.gl, this.debug, rows, columns, this.textureConfig);
}
createFloat16MatrixTexture(rows, columns) {
this.throwIfDisposed();
return createFloat16MatrixTexture(this.gl, this.debug, rows, columns, this.textureConfig);
}
createUnsignedBytesMatrixTexture(rows, columns) {
this.throwIfDisposed();
return createUnsignedBytesMatrixTexture(
this.gl,
this.debug,
rows,
columns,
this.textureConfig
);
}
uploadPixelDataToTexture(texture, pixels) {
this.throwIfDisposed();
uploadPixelDataToTexture(this.gl, this.debug, texture, pixels);
}
uploadDenseMatrixToTexture(texture, width, height, data) {
this.throwIfDisposed();
uploadDenseMatrixToTexture(
this.gl,
this.debug,
texture,
width,
height,
data,
this.textureConfig
);
}
createFloat16PackedMatrixTexture(rows, columns) {
this.throwIfDisposed();
return createFloat16PackedMatrixTexture(
this.gl,
this.debug,
rows,
columns,
this.textureConfig
);
}
createPackedMatrixTexture(rows, columns) {
this.throwIfDisposed();
return createPackedMatrixTexture(this.gl, this.debug, rows, columns, this.textureConfig);
}
deleteMatrixTexture(texture) {
this.throwIfDisposed();
if (this.outputTexture === texture) {
unbindColorTextureFromFramebuffer(this.gl, this.debug, this.framebuffer);
this.outputTexture = null;
}
callAndCheck(this.gl, this.debug, () => this.gl.deleteTexture(texture));
}
downloadByteEncodedFloatMatrixFromOutputTexture(texture, rows, columns) {
return this.downloadMatrixDriver(texture, () =>
downloadByteEncodedFloatMatrixFromOutputTexture(
this.gl,
this.debug,
rows,
columns,
this.textureConfig
)
);
}
downloadPackedMatrixFromBuffer(buffer, batch, rows, columns, physicalRows, physicalCols) {
return downloadPackedMatrixFromBuffer(
this.gl,
buffer,
batch,
rows,
columns,
physicalRows,
physicalCols,
this.textureConfig
);
}
downloadFloat32MatrixFromBuffer(buffer, size) {
return downloadFloat32MatrixFromBuffer(this.gl, buffer, size);
}
createBufferFromTexture(texture, rows, columns) {
this.bindTextureToFrameBuffer(texture);
const result = createBufferFromOutputTexture(
this.gl,
this.debug,
rows,
columns,
this.textureConfig
);
this.unbindTextureToFrameBuffer();
return result;
}
createAndWaitForFence() {
const fenceContext = this.createFence(this.gl);
return this.pollFence(fenceContext);
}
createFence(gl) {
let query;
let isFencePassed;
if (Object(dist["env"])().getBool("WEBGL_FENCE_API_ENABLED")) {
const gl2 = gl;
const sync = gl2.fenceSync(gl2.SYNC_GPU_COMMANDS_COMPLETE, 0);
gl.flush();
isFencePassed = () => {
const status = gl2.clientWaitSync(sync, 0, 0);
return status === gl2.ALREADY_SIGNALED || status === gl2.CONDITION_SATISFIED;
};
query = sync;
} else if (
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0
) {
query = this.beginQuery();
this.endQuery();
isFencePassed = () =>
this.isQueryAvailable(
query,
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")
);
} else {
// If we have no way to fence, return true immediately. This will fire in
// WebGL 1.0 when there is no disjoint query timer. In this case, because
// the fence passes immediately, we'll immediately ask for a download of
// the texture, which will cause the UI thread to hang.
isFencePassed = () => true;
}
return { query, isFencePassed };
}
downloadMatrixFromPackedTexture(texture, physicalRows, physicalCols) {
return this.downloadMatrixDriver(texture, () =>
downloadMatrixFromPackedOutputTexture(this.gl, this.debug, physicalRows, physicalCols)
);
}
createProgram(fragmentShaderSource) {
this.throwIfDisposed();
const gl = this.gl;
const fragmentShader = createFragmentShader(gl, this.debug, fragmentShaderSource);
const vertexShader = gpgpu_util_createVertexShader(gl, this.debug);
const program = createProgram(gl, this.debug);
callAndCheck(gl, this.debug, () => gl.attachShader(program, vertexShader));
callAndCheck(gl, this.debug, () => gl.attachShader(program, fragmentShader));
linkProgram(gl, this.debug, program);
if (this.debug) {
validateProgram(gl, this.debug, program);
}
if (!this.vertexAttrsAreBound) {
this.setProgram(program);
this.vertexAttrsAreBound = bindVertexProgramAttributeStreams(
gl,
this.debug,
this.program,
this.vertexBuffer
);
}
return program;
}
deleteProgram(program) {
this.throwIfDisposed();
if (program === this.program) {
this.program = null;
}
if (program != null) {
callAndCheck(this.gl, this.debug, () => this.gl.deleteProgram(program));
}
}
setProgram(program) {
this.throwIfDisposed();
this.program = program;
if (this.program != null && this.debug) {
validateProgram(this.gl, this.debug, this.program);
}
callAndCheck(this.gl, this.debug, () => this.gl.useProgram(program));
}
getUniformLocation(program, uniformName, shouldThrow = true) {
this.throwIfDisposed();
if (shouldThrow) {
return getProgramUniformLocationOrThrow(this.gl, this.debug, program, uniformName);
} else {
return getProgramUniformLocation(this.gl, program, uniformName);
}
}
getAttributeLocation(program, attribute) {
this.throwIfDisposed();
return callAndCheck(this.gl, this.debug, () =>
this.gl.getAttribLocation(program, attribute)
);
}
getUniformLocationNoThrow(program, uniformName) {
this.throwIfDisposed();
return this.gl.getUniformLocation(program, uniformName);
}
setInputMatrixTexture(inputMatrixTexture, uniformLocation, textureUnit) {
this.throwIfDisposed();
this.throwIfNoProgram();
bindTextureToProgramUniformSampler(
this.gl,
this.debug,
this.program,
inputMatrixTexture,
uniformLocation,
textureUnit
);
}
setOutputMatrixTexture(outputMatrixTexture, rows, columns) {
this.setOutputMatrixTextureDriver(outputMatrixTexture, columns, rows);
}
setOutputPackedMatrixTexture(outputPackedMatrixTexture, rows, columns) {
this.throwIfDisposed();
const [width, height] = getPackedMatrixTextureShapeWidthHeight(rows, columns);
this.setOutputMatrixTextureDriver(outputPackedMatrixTexture, width, height);
}
setOutputMatrixWriteRegion(startRow, numRows, startColumn, numColumns) {
this.setOutputMatrixWriteRegionDriver(startColumn, startRow, numColumns, numRows);
}
setOutputPackedMatrixWriteRegion(startRow, numRows, startColumn, numColumns) {
throw new Error("setOutputPackedMatrixWriteRegion not implemented.");
}
debugValidate() {
if (this.program != null) {
validateProgram(this.gl, this.debug, this.program);
}
validateFramebuffer(this.gl);
}
executeProgram() {
this.throwIfDisposed();
this.throwIfNoProgram();
const gl = this.gl;
if (this.debug) {
this.debugValidate();
}
callAndCheck(gl, this.debug, () =>
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0)
);
}
blockUntilAllProgramsCompleted() {
this.throwIfDisposed();
callAndCheck(this.gl, this.debug, () => this.gl.finish());
}
getQueryTimerExtension() {
if (this.disjointQueryTimerExtension == null) {
this.disjointQueryTimerExtension = getExtensionOrThrow(
this.gl,
this.debug,
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2
? "EXT_disjoint_timer_query_webgl2"
: "EXT_disjoint_timer_query"
);
}
return this.disjointQueryTimerExtension;
}
getQueryTimerExtensionWebGL2() {
return this.getQueryTimerExtension();
}
getQueryTimerExtensionWebGL1() {
return this.getQueryTimerExtension();
}
beginQuery() {
if (
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2
) {
const gl2 = this.gl;
const ext = this.getQueryTimerExtensionWebGL2();
const query = gl2.createQuery();
gl2.beginQuery(ext.TIME_ELAPSED_EXT, query);
return query;
}
const ext = this.getQueryTimerExtensionWebGL1();
const query = ext.createQueryEXT();
ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, query);
return query;
}
endQuery() {
if (
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2
) {
const gl2 = this.gl;
const ext = this.getQueryTimerExtensionWebGL2();
gl2.endQuery(ext.TIME_ELAPSED_EXT);
return;
}
const ext = this.getQueryTimerExtensionWebGL1();
ext.endQueryEXT(ext.TIME_ELAPSED_EXT);
}
async waitForQueryAndGetTime(query) {
await dist["util"].repeatedTry(
() =>
this.disposed || // while testing contexts are created / disposed
// in rapid succession, so without this check we
// may poll for the query timer indefinitely
this.isQueryAvailable(
query,
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")
)
);
return this.getQueryTime(
query,
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")
);
}
getQueryTime(query, queryTimerVersion) {
if (queryTimerVersion === 0) {
return null;
}
if (queryTimerVersion === 2) {
const gl2 = this.gl;
const timeElapsedNanos = gl2.getQueryParameter(query, gl2.QUERY_RESULT);
// Return milliseconds.
return timeElapsedNanos / 1000000;
} else {
const ext = this.getQueryTimerExtensionWebGL1();
const timeElapsedNanos = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);
// Return milliseconds.
return timeElapsedNanos / 1000000;
}
}
isQueryAvailable(query, queryTimerVersion) {
if (queryTimerVersion === 0) {
return true;
}
if (queryTimerVersion === 2) {
const gl2 = this.gl;
const ext = this.getQueryTimerExtensionWebGL2();
const available = gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE);
if (this.disjoint == null) {
this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);
}
return available && !this.disjoint;
} else {
const ext = this.getQueryTimerExtensionWebGL1();
const available = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);
if (this.disjoint == null) {
this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);
}
return available && !this.disjoint;
}
}
pollFence(fenceContext) {
return new Promise((resolve) => {
this.addItemToPoll(
() => fenceContext.isFencePassed(),
() => resolve()
);
});
}
pollItems() {
// Find the last query that has finished.
const index = linearSearchLastTrue(this.itemsToPoll.map((x) => x.isDoneFn));
for (let i = 0; i <= index; ++i) {
const { resolveFn } = this.itemsToPoll[i];
resolveFn();
}
this.itemsToPoll = this.itemsToPoll.slice(index + 1);
}
addItemToPoll(isDoneFn, resolveFn) {
this.itemsToPoll.push({ isDoneFn, resolveFn });
if (this.itemsToPoll.length > 1) {
// We already have a running loop that polls.
return;
}
// Start a new loop that polls.
dist["util"].repeatedTry(() => {
this.pollItems();
// End the loop if no more items to poll.
return this.itemsToPoll.length === 0;
});
}
bindTextureToFrameBuffer(texture) {
this.throwIfDisposed();
bindColorTextureToFramebuffer(this.gl, this.debug, texture, this.framebuffer);
if (this.debug) {
validateFramebuffer(this.gl);
}
}
unbindTextureToFrameBuffer() {
if (this.outputTexture != null) {
bindColorTextureToFramebuffer(
this.gl,
this.debug,
this.outputTexture,
this.framebuffer
);
if (this.debug) {
validateFramebuffer(this.gl);
}
} else {
unbindColorTextureFromFramebuffer(this.gl, this.debug, this.framebuffer);
}
}
downloadMatrixDriver(texture, downloadAndDecode) {
this.bindTextureToFrameBuffer(texture);
const result = downloadAndDecode();
this.unbindTextureToFrameBuffer();
return result;
}
setOutputMatrixTextureDriver(outputMatrixTextureMaybePacked, width, height) {
this.throwIfDisposed();
const gl = this.gl;
bindColorTextureToFramebuffer(
gl,
this.debug,
outputMatrixTextureMaybePacked,
this.framebuffer
);
if (this.debug) {
validateFramebuffer(gl);
}
this.outputTexture = outputMatrixTextureMaybePacked;
callAndCheck(gl, this.debug, () => gl.viewport(0, 0, width, height));
callAndCheck(gl, this.debug, () => gl.scissor(0, 0, width, height));
}
setOutputMatrixWriteRegionDriver(x, y, width, height) {
this.throwIfDisposed();
callAndCheck(this.gl, this.debug, () => this.gl.scissor(x, y, width, height));
}
throwIfDisposed() {
if (this.disposed) {
throw new Error("Attempted to use disposed GPGPUContext.");
}
}
throwIfNoProgram() {
if (this.program == null) {
throw new Error("No GPU program is currently set.");
}
}
}
/**
* Finds the index of the last true element using linear search.
* Note: We can't do binary search because Chrome expects us to explicitly
* test all fences before download:
* https://github.com/tensorflow/tfjs/issues/1145
*/
function linearSearchLastTrue(arr) {
let i = 0;
for (; i < arr.length; ++i) {
const isDone = arr[i]();
if (!isDone) {
break;
}
}
return i - 1;
}
//# sourceMappingURL=gpgpu_context.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/gpgpu_math.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function compileProgram(gpgpu, program, inputs, output) {
const userCode = program.userCode;
const inputInfos = inputs.map((input, i) => {
const shapeInfo = {
logicalShape: input.shape,
texShape: input.isUniform ? null : input.texData.texShape,
isUniform: input.isUniform,
isPacked: input.isUniform ? false : input.texData.isPacked,
flatOffset: null,
};
if (
input.texData != null &&
input.texData.slice != null &&
input.texData.slice.flatOffset > 0
) {
shapeInfo.flatOffset = input.texData.slice.flatOffset;
}
return { name: program.variableNames[i], shapeInfo };
});
const inShapeInfos = inputInfos.map((x) => x.shapeInfo);
const outShapeInfo = {
logicalShape: output.shape,
texShape: output.texData.texShape,
isUniform: false,
isPacked: output.texData.isPacked,
flatOffset: null,
};
const source = makeShader(inputInfos, outShapeInfo, userCode, program.packedInputs);
const webGLProgram = gpgpu.createProgram(source);
// Add special uniforms (NAN, INFINITY)
let infLoc = null;
const nanLoc = gpgpu.getUniformLocation(webGLProgram, "NAN", false);
if (Object(dist["env"])().getNumber("WEBGL_VERSION") === 1) {
infLoc = gpgpu.getUniformLocation(webGLProgram, "INFINITY", false);
}
// Add user-defined uniforms
const uniformLocations = {};
for (let i = 0; i < program.variableNames.length; i++) {
const varName = program.variableNames[i];
const shouldThrow = false;
uniformLocations[varName] = gpgpu.getUniformLocation(webGLProgram, varName, shouldThrow);
uniformLocations[`offset${varName}`] = gpgpu.getUniformLocation(
webGLProgram,
`offset${varName}`,
shouldThrow
);
}
return {
program,
source,
webGLProgram,
uniformLocations,
inShapeInfos,
outShapeInfo,
infLoc,
nanLoc,
};
}
function validateBinaryAndProgram(shapeInfos, inputs) {
if (shapeInfos.length !== inputs.length) {
throw Error(
`Binary was compiled with ${shapeInfos.length} inputs, but ` +
`was executed with ${inputs.length} inputs`
);
}
shapeInfos.forEach((s, i) => {
const shapeA = s.logicalShape;
const input = inputs[i];
const shapeB = input.shape;
if (!dist["util"].arraysEqual(shapeA, shapeB)) {
throw Error(
`Binary was compiled with different shapes than ` +
`the current args. Shapes ${shapeA} and ${shapeB} must match`
);
}
// The input is uploaded as uniform.
if (s.isUniform && input.isUniform) {
return;
}
const texShapeA = s.texShape;
const texShapeB = input.isUniform ? null : input.texData.texShape;
if (!dist["util"].arraysEqual(texShapeA, texShapeB)) {
throw Error(
`Binary was compiled with different texture shapes than the` +
` current args. Shape ${texShapeA} and ${texShapeB} must match`
);
}
});
}
function runProgram(gpgpu, binary, inputs, output, customSetup) {
validateBinaryAndProgram(binary.inShapeInfos, inputs);
validateBinaryAndProgram([binary.outShapeInfo], [output]);
const outTex = output.texData.texture;
const outTexShape = output.texData.texShape;
if (output.texData.isPacked) {
gpgpu.setOutputPackedMatrixTexture(outTex, outTexShape[0], outTexShape[1]);
} else {
gpgpu.setOutputMatrixTexture(outTex, outTexShape[0], outTexShape[1]);
}
gpgpu.setProgram(binary.webGLProgram);
// Set special uniforms (NAN, INFINITY)
if (Object(dist["env"])().getNumber("WEBGL_VERSION") === 1) {
if (binary.infLoc !== null) {
gpgpu.gl.uniform1f(binary.infLoc, Infinity);
}
}
if (binary.nanLoc !== null) {
gpgpu.gl.uniform1f(binary.nanLoc, NaN);
}
// Set user-defined inputs
inputs.forEach((input, i) => {
const varName = binary.program.variableNames[i];
const varLoc = binary.uniformLocations[varName];
const varOffsetLoc = binary.uniformLocations[`offset${varName}`];
if (varLoc == null) {
// The compiler inferred that this variable is not used in this shader.
return;
}
if (input.isUniform) {
// Upload the values of the tensor as uniform.
if (dist["util"].sizeFromShape(input.shape) < 2) {
gpgpu.gl.uniform1f(varLoc, input.uniformValues[0]);
} else {
let vals = input.uniformValues;
if (!(vals instanceof Float32Array)) {
vals = new Float32Array(vals);
}
gpgpu.gl.uniform1fv(varLoc, vals);
}
return;
}
// If the input was sliced, upload the flat offset index.
if (input.texData.slice != null && varOffsetLoc != null) {
gpgpu.gl.uniform1i(varOffsetLoc, input.texData.slice.flatOffset);
}
gpgpu.setInputMatrixTexture(input.texData.texture, varLoc, i);
});
if (customSetup != null) {
customSetup(gpgpu, binary.webGLProgram);
}
gpgpu.executeProgram();
}
function makeShaderKey(program, inputs, output) {
let keyInputs = "";
inputs.concat(output).forEach((x) => {
const hasOffset =
x.texData != null && x.texData.slice != null && x.texData.slice.flatOffset > 0;
const texShape = x.isUniform ? "uniform" : x.texData.texShape;
keyInputs += `${x.shape}_${texShape}_${hasOffset}`;
});
const keyUserCode = program.userCode;
let key = program.constructor.name;
// Fast string concat. See https://jsperf.com/string-concatenation/14.
key += "_" + keyInputs + "_" + keyUserCode;
return key;
}
//# sourceMappingURL=gpgpu_math.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/im2col_packed_gpu.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.
* =============================================================================
*/
class im2col_packed_gpu_Im2ColPackedProgram {
constructor(outputShape, inputShape, convInfo) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = outputShape;
const {
filterWidth,
inChannels,
strideWidth,
strideHeight,
padInfo,
outWidth,
dilationWidth,
dilationHeight,
dataFormat,
} = convInfo;
const { left, top } = padInfo;
const itemsPerBlockRow = inChannels * filterWidth;
const glsl = getGlslDifferences();
const isChannelsLast = dataFormat === "channelsLast";
const rowDim = isChannelsLast ? 0 : 1;
const colDim = isChannelsLast ? 1 : 2;
let unrolled = ``;
for (let row = 0; row <= 1; row++) {
for (let col = 0; col <= 1; col++) {
unrolled += `
blockIndex = rc.y + ${col};
pos = rc.x + ${row};
if(blockIndex < ${outputShape[1]} && pos < ${outputShape[0]}) {
offsetY = int(blockIndex / (${outWidth})) * ${strideHeight} - ${top};
d0 = offsetY + ${dilationHeight} * (pos / ${itemsPerBlockRow});
if(d0 < ${inputShape[rowDim]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${outWidth}.) * ${strideWidth}. - ${left}.);
d1 = offsetX + ${dilationWidth} * (int(mod(float(pos), ${itemsPerBlockRow}.) / ${inChannels}.));
if(d1 < ${inputShape[colDim]} && d1 >= 0) {
ch = int(mod(float(pos), ${inChannels}.));
if (${isChannelsLast}) {
innerDims = vec2(d1, ch);
result[${row * 2 + col}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${row * 2 + col}] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;
}
}
this.userCode = `
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${unrolled}
${glsl.output} = result;
}
`;
}
}
//# sourceMappingURL=im2col_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/lrn_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class LRNProgram {
constructor(xShape, radius, bias, alpha, beta) {
this.variableNames = ["x"];
this.outputShape = [];
const rad = radius;
const maxD = xShape[3] - 1;
this.outputShape = xShape;
// optimize pow(bias + alpha * sum, -beta)
// src: https://github.com/tensorflow/tensorflow/..
// blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..
// tensorflow/core/kernels/mkl_lrn_op.cc#L320
let powOperator;
const basis = `float(${bias}) + float(${alpha}) * sum`;
if (beta === 0.5) {
powOperator = `inversesqrt(${basis})`;
} else if (beta === 1.0) {
powOperator = `1.0/(${basis})`;
} else {
powOperator = `exp(log(${basis}) * float(-${beta}));`;
}
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${rad}; j <= ${rad}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${maxD}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${powOperator};
setOutput(val);
}
`;
}
}
//# sourceMappingURL=lrn_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/lrn_grad_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class LRNGradProgram {
constructor(inputShape, depthRadius, bias, alpha, beta) {
this.variableNames = ["inputImage", "outputImage", "dy"];
this.outputShape = [];
this.outputShape = inputShape;
this.depth = inputShape[3];
this.depthRadius = depthRadius;
this.bias = bias;
this.alpha = alpha;
this.beta = beta;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${depthRadius})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${depthRadius} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${alpha}) * norm + float(${bias});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${alpha})
* float(${beta})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${beta});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`;
}
}
//# sourceMappingURL=lrn_grad_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/lrn_packed_gpu.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.
* =============================================================================
*/
class LRNPackedProgram {
constructor(xShape, radius, bias, alpha, beta) {
this.variableNames = ["x"];
this.outputShape = [];
this.packedInputs = true;
this.packedOutput = true;
const rad = radius;
const maxD = xShape[3] - 1;
this.outputShape = xShape;
// optimize pow(bias + alpha * sum, -beta)
// src: https://github.com/tensorflow/tensorflow/..
// blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..
// tensorflow/core/kernels/mkl_lrn_op.cc#L320
let powOperator;
const basis = `float(${bias}) + float(${alpha}) * sum`;
if (beta === 0.5) {
powOperator = `inversesqrt(${basis})`;
} else if (beta === 1.0) {
powOperator = `1.0/(${basis})`;
} else {
powOperator = `exp(log(${basis}) * float(-${beta}));`;
}
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${rad};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${rad}; j <= ${rad}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${maxD}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${powOperator};
setOutput(result);
}
`;
}
}
//# sourceMappingURL=lrn_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/max_pool_backprop_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class MaxPool2DBackpropProgram {
constructor(convInfo) {
this.variableNames = ["dy", "maxPos"];
this.outputShape = convInfo.inShape;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const lastIndex = effectiveFilterHeight * effectiveFilterWidth - 1;
this.userCode = `
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${effectiveFilterWidth}; wC++) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${lastIndex} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${effectiveFilterWidth} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`;
}
}
class MaxPool3DBackpropProgram {
constructor(convInfo) {
this.variableNames = ["dy", "maxPos"];
this.outputShape = convInfo.inShape;
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterDepth = convInfo.effectiveFilterDepth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const lastIndex = effectiveFilterDepth * effectiveFilterHeight * effectiveFilterWidth - 1;
this.userCode = `
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${effectiveFilterDepth};
wD += ${dilationDepth}) {
float dyD = float(dyDCorner + wD) / ${strideDepth}.0;
if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${effectiveFilterWidth};
wC += ${dilationWidth}) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${lastIndex} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${effectiveFilterHeight} * ${effectiveFilterWidth} +
wR * ${effectiveFilterWidth} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`;
}
}
//# sourceMappingURL=max_pool_backprop_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/mulmat_packed_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class MatMulPackedProgram {
constructor(
aShape,
outputShape,
transposeA = false,
transposeB = false,
addBias = false,
activation = null,
hasPreluActivation = false
) {
this.variableNames = ["matrixA", "matrixB"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = outputShape;
const sharedDim = transposeA ? aShape[1] : aShape[2];
const sharedDimensionPacked = Math.ceil(sharedDim / 2);
const aSample = transposeA ? "i * 2, rc.y" : "rc.y, i * 2";
const bSample = transposeB ? "rc.z, i * 2" : "i * 2, rc.z";
const aSwizzle = transposeA ? ["a.xxyy", "a.zzww"] : ["a.xxzz", "a.yyww"];
const bSwizzle = transposeB ? ["b.xzxz", "b.ywyw"] : ["b.xyxy", "b.zwzw"];
let activationSnippet = "",
applyActivationSnippet = "";
if (activation) {
if (hasPreluActivation) {
activationSnippet = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${activation}
}`;
} else {
activationSnippet = `vec4 activation(vec4 x) {
${activation}
}`;
}
applyActivationSnippet = `result = activation(result);`;
}
const addBiasSnippet = addBias ? "result += getBiasAtOutCoords();" : "";
if (addBias) {
this.variableNames.push("bias");
}
if (hasPreluActivation) {
this.variableNames.push("preluActivationWeights");
}
this.userCode = `
${activationSnippet}
const float sharedDimension = ${sharedDimensionPacked}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${sharedDimensionPacked}; i++) {
vec4 a = getMatrixA(rc.x, ${aSample});
vec4 b = getMatrixB(rc.x, ${bSample});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${aSwizzle[0]} * ${bSwizzle[0]});
result += (${aSwizzle[1]} * ${bSwizzle[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${addBiasSnippet}
${applyActivationSnippet}
setOutput(result);
}
`;
}
}
//# sourceMappingURL=mulmat_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/multinomial_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class MultinomialProgram {
constructor(batchSize, numOutcomes, numSamples) {
this.variableNames = ["probs"];
this.outputShape = [batchSize, numSamples];
this.userCode = `
uniform float seed;
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${numOutcomes - 1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${numOutcomes - 1}));
}
`;
}
getCustomSetupFunc(seed) {
return (gpgpu, webGLProgram) => {
if (this.seedLoc == null) {
this.seedLoc = gpgpu.getUniformLocation(webGLProgram, "seed");
}
gpgpu.gl.uniform1f(this.seedLoc, seed);
};
}
}
//# sourceMappingURL=multinomial_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/onehot_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class OneHotProgram {
constructor(numIndices, depth, onValue, offValue) {
this.variableNames = ["indices"];
this.outputShape = [numIndices, depth];
this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${offValue}), float(${onValue}),
float(index == coords.y)));
}
`;
}
}
//# sourceMappingURL=onehot_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/pack_gpu.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class pack_gpu_PackProgram {
constructor(outputShape) {
this.variableNames = ["A"];
this.packedInputs = false;
this.packedOutput = true;
// Only input / output 3D tensors.
this.outputShape = outputShape;
const rank = outputShape.length;
if (rank === 0) {
this.userCode = `
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;
} else {
const channels = getChannels("rc", rank);
const dtype = getCoordsDataType(rank);
const outOfBoundsCondition = getOutOfBoundsCondition(rank, outputShape, channels);
const setup = getSetup(
rank,
outputShape[outputShape.length - 1],
outputShape[outputShape.length - 2],
channels
);
const output = getOutput(outputShape, channels);
this.userCode = `
void main() {
${dtype} rc = getOutputCoords();
if(${outOfBoundsCondition}) {
setOutput(vec4(0));
} else {
${setup}
setOutput(vec4(${output}));
}
}
`;
}
}
}
function getSourceCoordsArr(rank, dims) {
const coords = [];
for (let row = 0; row <= 1; row++) {
for (let col = 0; col <= 1; col++) {
let coord = `${row === 0 ? "r" : "rp1"}, ${col === 0 ? "c" : "cp1"}`;
for (let d = 2; d < rank; d++) {
coord = `${dims[dims.length - 1 - d]},` + coord;
}
coords.push(coord);
}
}
return coords;
}
function getOutOfBoundsCondition(rank, shape, dims) {
if (rank === 1) {
return `rc > ${shape[0]}`;
}
let cond = "";
for (let i = rank - 2; i < rank; i++) {
cond += `${dims[i]} >= ${shape[i]}`;
if (i < rank - 1) {
cond += "||";
}
}
return cond;
}
function getSetup(rank, cols, rows, dims) {
if (rank === 1) {
return "";
}
const innerDims = dims.slice(-2);
return `
int r = ${innerDims[0]};
int c = ${innerDims[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${cols};
bool rEdge = rp1 >= ${rows};
`;
}
function getOutput(shape, dims) {
const rank = shape.length;
const sourceCoords = getSourceCoordsArr(rank, dims);
if (rank === 1) {
return `getA(rc),
rc + 1 >= ${shape[0]} ? 0. : getA(rc + 1),
0, 0`;
}
return `getA(${sourceCoords[0]}),
cEdge ? 0. : getA(${sourceCoords[1]}),
rEdge ? 0. : getA(${sourceCoords[2]}),
rEdge || cEdge ? 0. : getA(${sourceCoords[3]})`;
}
//# sourceMappingURL=pack_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/pad_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class pad_gpu_PadProgram {
constructor(xShape, paddings, constantValue) {
this.variableNames = ["x"];
this.outputShape = paddings.map(
(p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */
);
const rank = xShape.length;
const type = getCoordsDataType(rank);
const start = paddings.map((p) => p[0]).join(",");
const end = paddings.map((p, i) => p[0] + xShape[i]).join(",");
const unpackedCoords = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(
0,
rank
);
if (rank === 1) {
this.userCode = `
int start = ${start};
int end = ${end};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(${constantValue}));
} else {
setOutput(getX(outC - start));
}
}
`;
return;
}
this.userCode = `
${type} start = ${type}(${start});
${type} end = ${type}(${end});
void main() {
${type} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(${constantValue}));
} else {
${type} coords = outC - start;
setOutput(getX(${unpackedCoords}));
}
}
`;
}
}
//# sourceMappingURL=pad_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/pad_packed_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class pad_packed_gpu_PadPackedProgram {
constructor(xShape, paddings, constantValue) {
this.variableNames = ["x"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = paddings.map(
(p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */
);
const rank = xShape.length;
const dtype = getCoordsDataType(rank);
const start = paddings.map((p) => p[0]).join(",");
const end = paddings.map((p, i) => p[0] + xShape[i]).join(",");
const coords = getChannels("rc", rank);
const source = getChannels("source", rank);
const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;
const innerDims = rank === 1 ? "source" : `vec2(${source.slice(-2).join()})`;
const componentSetup = [
`${dtype} rc = outputLoc;`,
`${coords[rank - 1]} += 1;
if(${cLimit}) {
`,
rank === 1
? ""
: `}
rc = outputLoc;
${coords[rank - 2]} += 1;
if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {`,
rank === 1
? ""
: ` ${coords[rank - 1]} += 1;
if(${cLimit}) {`,
];
const paddingArea =
rank === 1
? "rc < start || rc >= end"
: "any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";
let mainLoop = "";
for (let i = 0, j = rank === 1 ? 2 : 4; i < j; i++) {
mainLoop += `
${componentSetup[i]}
if (${paddingArea}) {
result[${i}] = float(${constantValue});
} else {
${dtype} source = rc - start;
result[${i}] = getChannel(getX(${source.join()}), ${innerDims});
}
`;
}
mainLoop += rank === 1 ? `} ` : `}}`;
this.userCode = `
const ${dtype} start = ${dtype}(${start});
const ${dtype} end = ${dtype}(${end});
void main() {
${dtype} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${mainLoop}
setOutput(result);
}
`;
}
}
//# sourceMappingURL=pad_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/pool_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Pool2DProgram {
constructor(
convInfo,
poolType,
computePositions,
flattenPositions = false,
includeBatchInIndex = false
) {
this.variableNames = ["x"];
if (poolType === "avg" && computePositions) {
throw new Error("Cannot compute positions for average pool.");
}
const filterWidth = convInfo.filterWidth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
this.outputShape = convInfo.outShape;
const isAvgPool = poolType === "avg";
const batchFlattenPositionStr = `((batch * ${convInfo.inHeight} + xR) * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`;
const flattenPositionStr = `(xR * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`;
let initializationValue = "0.0";
if (!isAvgPool) {
// WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.
initializationValue = "-1.0 / 1e-20";
}
if (computePositions) {
const compareOp = ">=";
this.userCode = `
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int wC = 0; wC < ${effectiveFilterWidth};
wC += ${dilationWidth}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${compareOp} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${
flattenPositions
? includeBatchInIndex
? batchFlattenPositionStr
: flattenPositionStr
: `wR * ${effectiveFilterWidth} + wC`
};
}
}
}
setOutput(float(minMaxPosition));
}
`;
return;
}
const compareOp = "max";
let returnValue =
`${poolType}(${poolType}(${poolType}(` +
"minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";
if (poolType === "avg") {
returnValue = `avgValue / count`;
}
const filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;
const filterWidthVec4Remainder = filterWidth % 4;
const updateSnippet = `
if (${isAvgPool}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${compareOp}(values, minMaxValue);
}
`;
this.userCode = `
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
const float initializationValue = ${initializationValue};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${convInfo.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${initializationValue});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int wC = 0; wC < ${filterWidthNearestVec4}; wC += 4) {
int xC = xCCorner + wC * ${dilationWidth};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${dilationWidth}, d),
getValue(batch, xR, xC + 2 * ${dilationWidth}, d),
getValue(batch, xR, xC + 3 * ${dilationWidth}, d)
);
${updateSnippet}
}
int xC = xCCorner + ${filterWidthNearestVec4};
if (${filterWidthVec4Remainder === 1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${filterWidthVec4Remainder === 2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${dilationWidth}, d),
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${filterWidthVec4Remainder === 3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${dilationWidth}, d),
getValue(batch, xR, xC + 2 * ${dilationWidth}, d),
initializationValue
);
${updateSnippet}
}
}
setOutput(${returnValue});
}
`;
}
}
class Pool3DProgram {
constructor(
convInfo,
poolType,
computePositions,
flattenPositions = false,
includeBatchInIndex = false
) {
this.variableNames = ["x"];
if (poolType === "avg" && computePositions) {
throw new Error("Cannot compute positions for average pool.");
}
const filterWidth = convInfo.filterWidth;
const strideDepth = convInfo.strideDepth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dilationDepth = convInfo.dilationDepth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterDepth = convInfo.effectiveFilterDepth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padFront = convInfo.padInfo.front;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
this.outputShape = convInfo.outShape;
const isAvgPool = poolType === "avg";
let initializationValue = "0.0";
if (!isAvgPool) {
// WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.
initializationValue = "-1.0 / 1e-20";
}
if (computePositions) {
const compareOp = ">=";
this.userCode = `
const ivec3 strides =
ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < ${effectiveFilterDepth};
wD += ${dilationDepth}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${convInfo.inDepth}) {
continue;
}
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int wC = 0; wC < ${effectiveFilterWidth};
wC += ${dilationWidth}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${compareOp} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${
flattenPositions
? includeBatchInIndex
? `(((batch * ${convInfo.inDepth} + xD) * ${convInfo.inHeight} + xR) * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + ch`
: `((xD * ${convInfo.inHeight} + xR) * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + ch`
: `wD * ${effectiveFilterHeight} * ${effectiveFilterWidth} +
wR * ${effectiveFilterWidth} + wC`
};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;
return;
}
const compareOp = "max";
let returnValue =
`${poolType}(${poolType}(${poolType}(` +
"minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";
if (poolType === "avg") {
returnValue = `avgValue / count`;
}
const filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;
const filterWidthVec4Remainder = filterWidth % 4;
const updateSnippet = `
if (${isAvgPool}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${compareOp}(values, minMaxValue);
}
`;
this.userCode = `
const ivec3 strides =
ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
const float initializationValue = ${initializationValue};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${convInfo.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${initializationValue});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${effectiveFilterDepth};
wD += ${dilationDepth}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${convInfo.inDepth}) {
continue;
}
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int wC = 0; wC < ${filterWidthNearestVec4}; wC += 4) {
int xC = xCCorner + wC * ${dilationWidth};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${dilationWidth}, ch),
getValue(batch, xD, xR, xC + 2 * ${dilationWidth}, ch),
getValue(batch, xD, xR, xC + 3 * ${dilationWidth}, ch)
);
${updateSnippet}
}
int xC = xCCorner + ${filterWidthNearestVec4};
if (${filterWidthVec4Remainder === 1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${filterWidthVec4Remainder === 2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${dilationWidth}, ch),
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${filterWidthVec4Remainder === 3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${dilationWidth}, ch),
getValue(batch, xD, xR, xC + 2 * ${dilationWidth}, ch),
initializationValue
);
${updateSnippet}
}
}
setOutput(${returnValue});
}
}
`;
}
}
//# sourceMappingURL=pool_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/reduce_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ReduceProgram {
constructor(reduceInfo, reduceType) {
this.variableNames = ["x"];
const windowSize = reduceInfo.windowSize;
const batchSize = reduceInfo.batchSize;
const inSize = reduceInfo.inSize;
const outSize = Math.ceil(inSize / windowSize);
this.outputShape = [batchSize, outSize];
let initializationValue = "0.0";
let compareOp = ``;
if (reduceType === "prod") {
initializationValue = "1.0";
} else if (reduceType === "min") {
// WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.
initializationValue = "1.0 / 1e-20";
compareOp = `min`;
} else if (reduceType === "max") {
// WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.
initializationValue = "-1.0 / 1e-20";
compareOp = `max`;
}
let returnValue =
`${reduceType}(${reduceType}(${reduceType}(` +
"minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";
if (reduceType === "sum") {
returnValue = `sumValue`;
} else if (reduceType === "prod") {
returnValue = `prodValue`;
} else if (reduceType === "all") {
returnValue = `allValue`;
} else if (reduceType === "any") {
returnValue = `anyValue`;
}
const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
const windowSizeVec4Remainder = windowSize % 4;
let updateSnippet = `
if (${reduceType === "sum"}) {
sumValue += dot(values, ones);
} else if (${reduceType === "prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${compareOp}(values, minMaxValue);
}
`;
let vecType = `vec4`;
if (reduceType === "all") {
initializationValue = "1.0";
updateSnippet = `
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`;
vecType = `bvec4`;
} else if (reduceType === "any") {
initializationValue = "0.0";
updateSnippet = `
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`;
vecType = `bvec4`;
}
let checkOutOfBounds = "";
if (inSize % windowSize > 0) {
checkOutOfBounds = `
if (inIdx < 0 || inIdx >= ${inSize}) {
return initializationValue;
}
`;
}
this.userCode = `
const float initializationValue = ${initializationValue};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${checkOutOfBounds}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${windowSize};
vec4 minMaxValue = vec4(${initializationValue});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {
int inIdx = inOffset + i;
${vecType} values = ${vecType}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${updateSnippet}
}
int inIdx = inOffset + ${windowSizeNearestVec4};
if (${windowSizeVec4Remainder === 1}) {
${vecType} values = ${vecType}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${windowSizeVec4Remainder === 2}) {
${vecType} values = ${vecType}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${windowSizeVec4Remainder === 3}) {
${vecType} values = ${vecType}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${updateSnippet}
}
setOutput(${returnValue});
}
`;
}
}
//# sourceMappingURL=reduce_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/reshape_packed_gpu.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class reshape_packed_gpu_ReshapePackedProgram {
constructor(outputShape, inputShape) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = outputShape;
let mainLoop = ``;
for (let i = 0; i < 4; i++) {
let thisRC = `thisRC = rc;`;
if (i % 2 === 1) {
thisRC += `thisRC.z += 1;`;
}
if (i > 1) {
thisRC += `thisRC.y += 1;`;
}
mainLoop += `
${thisRC}
${i > 0 ? `if(thisRC.y < rows && thisRC.z < cols){` : ""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${i}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${i > 0 ? "}" : ""}
`;
}
this.userCode = `
${getReshapedInputCoords(inputShape)}
${getFlatIndexFrom3D(outputShape)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${outputShape[1]};
int cols = ${outputShape[2]};
${mainLoop}
setOutput(result);
}
`;
}
}
function getReshapedInputCoords(shape) {
const coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(["r", "c", "d"], shape);
return `
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${coordsFromIndexSnippet}
return ivec3(r, c, d);
}
`;
}
//# sourceMappingURL=reshape_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/resize_bilinear_backprop_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ResizeBilinearBackpropProgram {
constructor(dy, x, alignCorners) {
this.variableNames = ["dy"];
this.outputShape = [];
this.outputShape = x.shape;
const [, xHeight, xWidth] = x.shape;
const [, yHeight, yWidth] = dy.shape;
// In the backwards pass, we want to find the pixels that were generated for
// each pixel in the input image the forward pass and add the corresponding
// coefficient from dy to the gradient (with some interpolation).
const effectiveXSize = [
alignCorners && yHeight > 1 ? xHeight - 1 : xHeight,
alignCorners && yWidth > 1 ? xWidth - 1 : xWidth,
];
const effectiveYSize = [
alignCorners && yHeight > 1 ? yHeight - 1 : yHeight,
alignCorners && yWidth > 1 ? yWidth - 1 : yWidth,
];
const heightScale = effectiveXSize[0] / effectiveYSize[0];
const widthScale = effectiveXSize[1] / effectiveYSize[1];
const invHeightScale = 1 / heightScale;
const invWidthScale = 1 / widthScale;
// This defines the size of the window of values around a particular
// index in dy that we want to search for contributions to dx.
const winHeight = Math.ceil(invHeightScale) * 2 + 2;
const winWidth = Math.ceil(invWidthScale) * 2 + 2;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${heightScale});
const float widthScale = float(${widthScale});
const float invHeightScale = float(${invHeightScale});
const float invWidthScale = float(${invWidthScale});
const int winHeight = int(${winHeight});
const int winWidth = int(${winWidth});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${yHeight}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${yWidth}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${xHeight - 1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${xWidth - 1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
`;
}
}
//# sourceMappingURL=resize_bilinear_backprop_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/resize_bilinear_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ResizeBilinearProgram {
constructor(inputShape, newHeight, newWidth, alignCorners) {
this.variableNames = ["A"];
this.outputShape = [];
const [batch, oldHeight, oldWidth, depth] = inputShape;
this.outputShape = [batch, newHeight, newWidth, depth];
const effectiveInSize = [
alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth,
];
const effectiveOutSize = [
alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
alignCorners && newWidth > 1 ? newWidth - 1 : newWidth,
];
this.userCode = `
const vec2 effectiveInputOverOutputRatioRC = vec2(
${effectiveInSize[0] / effectiveOutSize[0]},
${effectiveInSize[1] / effectiveOutSize[1]});
const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
`;
}
}
//# sourceMappingURL=resize_bilinear_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/resize_bilinear_packed_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ResizeBilinearPackedProgram {
constructor(inputShape, newHeight, newWidth, alignCorners) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = [];
const [batch, oldHeight, oldWidth, depth] = inputShape;
this.outputShape = [batch, newHeight, newWidth, depth];
const effectiveInSize = [
alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth,
];
const effectiveOutSize = [
alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
alignCorners && newWidth > 1 ? newWidth - 1 : newWidth,
];
this.userCode = `
const vec3 effectiveInputOverOutputRatioRC = vec3(
${effectiveInSize[0] / effectiveOutSize[0]},
${effectiveInSize[1] / effectiveOutSize[1]},
${effectiveInSize[1] / effectiveOutSize[1]});
const vec3 inputShapeRC = vec3(${oldHeight}.0, ${oldWidth}.0,
${oldWidth}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${depth - 1};
bool hasNextRow = coords.z < ${newWidth - 1};
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
`;
}
}
//# sourceMappingURL=resize_bilinear_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/resize_nearest_neighbor_backprop_gpu.js
/**
* @license
* Copyright 2018 Google LLC All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ResizeNearestNeigborBackpropProgram {
constructor(dy, x, alignCorners) {
this.variableNames = ["dy"];
this.outputShape = [];
this.outputShape = x.shape;
const [, xHeight, xWidth] = x.shape;
const [, yHeight, yWidth] = dy.shape;
// In the backwards pass, we want to find the pixels that were generated for
// each pixel in the input image the forward pass and add the corresponding
// coefficient from dy to the gradient (with some interpolation).
const effectiveXSize = [
alignCorners && yHeight > 1 ? xHeight - 1 : xHeight,
alignCorners && yWidth > 1 ? xWidth - 1 : xWidth,
];
const effectiveYSize = [
alignCorners && yHeight > 1 ? yHeight - 1 : yHeight,
alignCorners && yWidth > 1 ? yWidth - 1 : yWidth,
];
const heightScale = effectiveXSize[0] / effectiveYSize[0];
const widthScale = effectiveXSize[1] / effectiveYSize[1];
const invHeightScale = 1 / heightScale;
const invWidthScale = 1 / widthScale;
// This defines the size of the window of values around a particular
// index in dy that we want to search for contributions to dx.
const winHeight = Math.ceil(invHeightScale) * 2 + 2;
const winWidth = Math.ceil(invWidthScale) * 2 + 2;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${heightScale});
const float widthScale = float(${widthScale});
const float invHeightScale = float(${invHeightScale});
const float invWidthScale = float(${invWidthScale});
const int winHeight = int(${winHeight});
const int winWidth = int(${winWidth});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${yHeight}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${yWidth}) {
continue;
}
float sourceFracRow =
float(${effectiveXSize[0]}) *
(float(dyR) / float(${effectiveYSize[0]}));
float sourceFracCol =
float(${effectiveXSize[1]}) *
(float(dyC) / float(${effectiveYSize[1]}));
int sourceNearestRow = int(min(
float(int(${xHeight}) - 1),
${alignCorners} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${xWidth}) - 1),
${alignCorners} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`;
}
}
//# sourceMappingURL=resize_nearest_neighbor_backprop_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/resize_nearest_neighbor_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ResizeNearestNeighborProgram {
constructor(inputShape, newHeight, newWidth, alignCorners) {
this.variableNames = ["A"];
this.outputShape = [];
const [batch, oldHeight, oldWidth, depth] = inputShape;
this.outputShape = [batch, newHeight, newWidth, depth];
const effectiveInSize = [
alignCorners && newHeight > 1 ? oldHeight - 1 : oldHeight,
alignCorners && newWidth > 1 ? oldWidth - 1 : oldWidth,
];
const effectiveOutSize = [
alignCorners && newHeight > 1 ? newHeight - 1 : newHeight,
alignCorners && newWidth > 1 ? newWidth - 1 : newWidth,
];
// When align corners is false, we rounds the value with floor.
const roundBase = alignCorners ? "0.5" : "0.0";
this.userCode = `
const vec2 effectiveInputOverOutputRatioRC = vec2(
${effectiveInSize[0] / effectiveOutSize[0]},
${effectiveInSize[1] / effectiveOutSize[1]});
const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`;
}
}
//# sourceMappingURL=resize_nearest_neighbor_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/reverse_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class reverse_gpu_ReverseProgram {
constructor(xShape, axis) {
this.variableNames = ["x"];
const rank = xShape.length;
if (rank > 4) {
throw new Error(`WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);
}
this.outputShape = xShape;
if (rank === 1) {
this.userCode = `
void main() {
int coord = getOutputCoords();
setOutput(getX(${xShape[0]} - coord - 1));
}
`;
return;
}
const getInCoord = (i) => {
if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {
return `${xShape[i]} - coords[${i}] - 1`;
}
return `coords[${i}]`;
};
const inCoords = xShape.map((_, i) => getInCoord(i)).join(",");
const type = getCoordsDataType(rank);
this.userCode = `
void main() {
${type} coords = getOutputCoords();
setOutput(getX(${inCoords}));
}
`;
}
}
//# sourceMappingURL=reverse_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/reverse_packed_gpu.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.
* =============================================================================
*/
class reverse_packed_gpu_ReversePackedProgram {
constructor(xShape, axis) {
this.variableNames = ["x"];
this.packedInputs = true;
this.packedOutput = true;
const rank = xShape.length;
if (rank > 4) {
throw new Error(`WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);
}
this.outputShape = xShape;
const channels = getChannels("rc", rank);
const nextColumn = `${channels[rank - 1]} + 1 < ${this.outputShape[rank - 1]}`;
const nextRow = `${channels[rank - 2]} + 1 < ${this.outputShape[rank - 2]}`;
const type = getCoordsDataType(rank);
if (rank === 1) {
this.userCode = `
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${xShape[0]} - rc - 1),
${xShape[0]} - rc - 1);
if(${nextColumn}){
result.g = getChannel(getX(${xShape[0]} - (rc + 1) - 1),
${xShape[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`;
} else {
this.userCode = `
void main() {
${type} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${getR(channels.slice())};
if(${nextColumn}){
result.g = ${getG(channels.slice())};
}
if(${nextRow}) {
result.b = ${getB(channels.slice())};
if(${nextColumn}) {
result.a = ${getA(channels.slice())};
}
}
setOutput(result);
}
`;
}
function getR(channels) {
return getChannel(channels);
}
function getG(channels) {
channels[rank - 1] = "(" + channels[rank - 1] + ` + 1)`;
return getChannel(channels);
}
function getB(channels) {
channels[rank - 2] = "(" + channels[rank - 2] + ` + 1)`;
return getChannel(channels);
}
function getA(channels) {
channels[rank - 1] = "(" + channels[rank - 1] + ` + 1)`;
channels[rank - 2] = "(" + channels[rank - 2] + ` + 1)`;
return getChannel(channels);
}
function getChannel(channels) {
const inCoordsArray = xShape.map((_, i) => getInCoord(i, channels));
const inCoords = inCoordsArray.join(",");
const innerDims = inCoordsArray.slice(-2).join(",");
return `getChannel(getX(${inCoords}), vec2(${innerDims}))`;
}
function getInCoord(i, channels1) {
if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {
return `${xShape[i]} - ${channels1[i]} - 1`;
} else {
return `${channels1[i]}`;
}
}
}
}
//# sourceMappingURL=reverse_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/scatter_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class scatter_gpu_ScatterProgram {
constructor(
updateSize,
sliceDim,
indicesRank,
updatesRank,
strides,
shape,
summingDupeIndex = true
) {
this.variableNames = ["updates", "indices", "defaultValue"];
this.outputShape = shape;
const stridesType = getCoordsDataType(strides.length);
const dtype = getCoordsDataType(shape.length);
let indicesString = "";
if (indicesRank === 1) {
indicesString = "i";
} else if (indicesRank === 2) {
indicesString = "i, j";
}
const indicesSnippet = `getIndices(${indicesString})`;
let updatesString = "";
if (updatesRank === 1) {
updatesString = "i";
} else if (updatesRank === 2) {
updatesString = "i, coords[1]";
}
const updatesSnippet = `getUpdates(${updatesString})`;
const strideString = sliceDim > 1 ? "strides[j]" : "strides";
this.userCode = `
${stridesType} strides = ${stridesType}(${strides});
void main() {
${dtype} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${updateSize}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${sliceDim}; j++) {
int index = round(${indicesSnippet});
flattenedIndex += index * ${strideString};
}
if (flattenedIndex == coords[0]) {
sum += ${updatesSnippet};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`;
}
}
//# sourceMappingURL=scatter_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/segment_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class SegmentOpProgram {
constructor(segOpInfo, segOpType) {
this.variableNames = ["x", "segmentIds"];
const windowSize = segOpInfo.windowSize;
const batchSize = segOpInfo.batchSize;
const inSize = segOpInfo.inSize;
const numSegments = segOpInfo.numSegments;
const outSize = numSegments * Math.ceil(inSize / windowSize);
this.outputShape = [batchSize, outSize];
const initializationValue = "0.0";
const returnValue = `sumValue`;
const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
const windowSizeVec4Remainder = windowSize % 4;
const updateSnippet = `
sumValue += dot(values, segFilter);
`;
let checkValueOutOfBounds = "";
if (inSize % windowSize > 0) {
checkValueOutOfBounds = `
if (inIdx < 0 || inIdx >= ${inSize}) {
return initializationValue;
}
`;
}
let checkSegmentIdOutOfBounds = "";
if (inSize % windowSize > 0) {
checkSegmentIdOutOfBounds = `
if (inIdx < 0 || inIdx >= ${inSize}) {
return -1.0;
}
`;
}
this.userCode = `
const float initializationValue = ${initializationValue};
float getValue(int batch, int inIdx) {
${checkValueOutOfBounds}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${checkSegmentIdOutOfBounds}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${numSegments})) * float(${windowSize}));
int currentSeg = int(mod(float(outIdx), float(${numSegments})));
float sumValue = 0.0;
for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${updateSnippet}
}
int inIdx = inOffset + ${windowSizeNearestVec4};
if (${windowSizeVec4Remainder === 1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
${updateSnippet}
} else if (${windowSizeVec4Remainder === 2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
${updateSnippet}
} else if (${windowSizeVec4Remainder === 3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
${updateSnippet}
}
setOutput(${returnValue});
}
`;
}
}
//# sourceMappingURL=segment_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/select_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class select_gpu_SelectProgram {
constructor(cRank, shape, rank) {
this.variableNames = ["c", "a", "b"];
this.outputShape = shape;
let cCoords;
let abCoords;
if (rank > 4) {
throw Error(`Where for rank ${rank} is not yet supported`);
}
if (rank === 1) {
abCoords = `resRC`;
cCoords = `resRC`;
} else {
const currentCoords = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"];
const cCoordVars = [];
const abCoordVars = [];
for (let i = 0; i < shape.length; i++) {
abCoordVars.push(`${currentCoords[i]}`);
if (i < cRank) {
cCoordVars.push(`${currentCoords[i]}`);
}
}
cCoords = cCoordVars.join();
abCoords = abCoordVars.join();
}
const dtype = getCoordsDataType(rank);
this.userCode = `
void main() {
${dtype} resRC = getOutputCoords();
float cVal = getC(${cCoords});
if (cVal >= 1.0) {
setOutput(getA(${abCoords}));
} else {
setOutput(getB(${abCoords}));
}
}
`;
}
}
//# sourceMappingURL=select_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/slice_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class slice_gpu_SliceProgram {
constructor(destSize) {
this.variableNames = ["source"];
this.outputShape = destSize;
this.rank = destSize.length;
const dtype = getCoordsDataType(this.rank);
const uniformPart = `uniform int start[${this.rank}];`;
const sourceCoords = slice_gpu_getCoords(this.rank);
let body;
const coordSum = destSize.map((_, i) => {
return `sourceLoc.${slice_gpu_coords[i]} = start[${i}] + coords.${slice_gpu_coords[i]};`;
});
body = `
${dtype} sourceLoc;
${dtype} coords = getOutputCoords();
${coordSum.join("\n")}
`;
this.userCode = `
${uniformPart}
void main() {
${body}
setOutput(getSource(${sourceCoords}));
}
`;
}
getCustomSetupFunc(start) {
if (start.length !== this.rank) {
throw Error(
`The rank (${this.rank}) of the program must match the ` +
`length of start (${start.length})`
);
}
return (gpgpu, webGLProgram) => {
if (this.startLoc == null) {
this.startLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, "start");
if (this.startLoc == null) {
// This means the compiler has optimized and realized it doesn't need
// the uniform.
return;
}
}
gpgpu.gl.uniform1iv(this.startLoc, start);
};
}
}
const slice_gpu_coords = ["x", "y", "z", "w", "u", "v"];
function slice_gpu_getCoords(rank) {
if (rank === 1) {
return "sourceLoc";
} else if (rank <= 6) {
return slice_gpu_coords
.slice(0, rank)
.map((x) => "sourceLoc." + x)
.join(",");
} else {
throw Error(`Slicing for rank ${rank} is not yet supported`);
}
}
//# sourceMappingURL=slice_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/slice_packed_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class slice_packed_gpu_SlicePackedProgram {
constructor(destSize) {
this.variableNames = ["source"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = destSize;
this.rank = destSize.length;
const dtype = getCoordsDataType(this.rank);
const coords = getChannels("coords", this.rank);
const sourceLoc = getChannels("sourceLoc", this.rank);
const innerDims = this.rank === 1 ? "sourceLoc" : `vec2(${sourceLoc.slice(-2).join()})`;
const getChannel = `getChannel(getSource(${sourceLoc.join()}), ${innerDims})`;
const upperRow = `
result.x = ${getChannel};
if (++${coords[this.rank - 1]} < ${destSize[this.rank - 1]}) {
++${sourceLoc[this.rank - 1]};
result.y = ${getChannel};
--${sourceLoc[this.rank - 1]};
}
`;
const lowerRow =
this.rank === 1
? ""
: `
--${coords[this.rank - 1]};
if (++${coords[this.rank - 2]} < ${destSize[this.rank - 2]}) {
++${sourceLoc[this.rank - 2]};
result.z = ${getChannel};
if (++${coords[this.rank - 1]} < ${destSize[this.rank - 1]}) {
++${sourceLoc[this.rank - 1]};
result.w = ${getChannel};
}
}
`;
const sourceLocSetup =
this.rank <= 4
? `sourceLoc = coords +
${dtype}(${destSize.map((_, i) => `start[${i}]`).join()});`
: destSize.map((_, i) => `${sourceLoc[i]} = ${coords[i]} + start[${i}];`).join("\n");
this.userCode = `
uniform int start[${this.rank}];
void main() {
${dtype} coords = getOutputCoords();
${dtype} sourceLoc;
${sourceLocSetup}
vec4 result = vec4(0.);
${upperRow}
${lowerRow}
setOutput(result);
}
`;
}
getCustomSetupFunc(start) {
if (start.length !== this.rank) {
throw Error(
`The rank (${this.rank}) of the program must match the ` +
`length of start (${start.length})`
);
}
return (gpgpu, webGLProgram) => {
if (this.startLoc == null) {
this.startLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, "start");
if (this.startLoc == null) {
// This means the compiler has optimized and realized it doesn't need
// the uniform.
return;
}
}
gpgpu.gl.uniform1iv(this.startLoc, start);
};
}
}
//# sourceMappingURL=slice_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/strided_slice_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class strided_slice_gpu_StridedSliceProgram {
constructor(begin, strides, size) {
this.variableNames = ["x"];
this.outputShape = size;
const rank = size.length;
const inputDtype = getCoordsDataType(size.length);
const dtype = getCoordsDataType(size.length);
let newCoords = "";
if (rank === 1) {
newCoords = "coords * strides + begin";
} else {
let outputAxis = 0;
newCoords = size
.map((_, i) => {
outputAxis++;
return size.length === 1
? `coords * strides[${i}] + begin[${i}]`
: `coords[${outputAxis - 1}] * strides[${i}] + begin[${i}]`;
})
.join(",");
}
this.userCode = `
${inputDtype} begin = ${inputDtype}(${begin});
${inputDtype} strides = ${inputDtype}(${strides});
void main() {
${dtype} coords = getOutputCoords();
setOutput(getX(${newCoords}));
}
`;
}
}
//# sourceMappingURL=strided_slice_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/texture_manager.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class texture_manager_TextureManager {
constructor(gpgpu) {
this.gpgpu = gpgpu;
this.numUsedTextures = 0;
this.numFreeTextures = 0;
this.freeTextures = {};
this.logEnabled = false;
this.usedTextures = {};
}
acquireTexture(shapeRC, usage, isPacked) {
const physicalTexType = getPhysicalFromLogicalTextureType(usage, isPacked);
const shapeKey = getKeyFromTextureShape(shapeRC, physicalTexType, isPacked);
if (!(shapeKey in this.freeTextures)) {
this.freeTextures[shapeKey] = [];
}
if (!(shapeKey in this.usedTextures)) {
this.usedTextures[shapeKey] = [];
}
if (this.freeTextures[shapeKey].length > 0) {
this.numFreeTextures--;
this.numUsedTextures++;
this.log();
const newTexture = this.freeTextures[shapeKey].shift();
this.usedTextures[shapeKey].push(newTexture);
return newTexture;
}
this.numUsedTextures++;
this.log();
let newTexture;
if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT32) {
newTexture = this.gpgpu.createPackedMatrixTexture(shapeRC[0], shapeRC[1]);
} else if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT16) {
newTexture = this.gpgpu.createFloat16PackedMatrixTexture(shapeRC[0], shapeRC[1]);
} else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT32) {
newTexture = this.gpgpu.createFloat32MatrixTexture(shapeRC[0], shapeRC[1]);
} else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT16) {
newTexture = this.gpgpu.createFloat16MatrixTexture(shapeRC[0], shapeRC[1]);
} else if (physicalTexType === PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE) {
newTexture = this.gpgpu.createUnsignedBytesMatrixTexture(shapeRC[0], shapeRC[1]);
}
this.usedTextures[shapeKey].push(newTexture);
return newTexture;
}
releaseTexture(texture, shape, logicalTexType, isPacked) {
if (this.freeTextures == null) {
// Already disposed.
return;
}
const physicalTexType = getPhysicalFromLogicalTextureType(logicalTexType, isPacked);
const shapeKey = getKeyFromTextureShape(shape, physicalTexType, isPacked);
if (!(shapeKey in this.freeTextures)) {
this.freeTextures[shapeKey] = [];
}
this.freeTextures[shapeKey].push(texture);
this.numFreeTextures++;
this.numUsedTextures--;
const texList = this.usedTextures[shapeKey];
const texIndex = texList.indexOf(texture);
if (texIndex < 0) {
throw new Error(
"Cannot release a texture that was never provided by this " + "texture manager"
);
}
texList.splice(texIndex, 1);
this.log();
}
log() {
if (!this.logEnabled) {
return;
}
const total = this.numFreeTextures + this.numUsedTextures;
console.log(
"Free/Used",
`${this.numFreeTextures} / ${this.numUsedTextures}`,
`(${total})`
);
}
getNumUsedTextures() {
return this.numUsedTextures;
}
getNumFreeTextures() {
return this.numFreeTextures;
}
dispose() {
if (this.freeTextures == null) {
// Already disposed.
return;
}
for (const texShape in this.freeTextures) {
this.freeTextures[texShape].forEach((tex) => {
this.gpgpu.deleteMatrixTexture(tex);
});
}
for (const texShape in this.usedTextures) {
this.usedTextures[texShape].forEach((tex) => {
this.gpgpu.deleteMatrixTexture(tex);
});
}
this.freeTextures = null;
this.usedTextures = null;
this.numUsedTextures = 0;
this.numFreeTextures = 0;
}
}
function getPhysicalTextureForRendering(isPacked) {
if (Object(dist["env"])().getBool("WEBGL_RENDER_FLOAT32_ENABLED")) {
if (isPacked) {
return PhysicalTextureType.PACKED_2X2_FLOAT32;
}
return PhysicalTextureType.UNPACKED_FLOAT32;
}
if (isPacked) {
return PhysicalTextureType.PACKED_2X2_FLOAT16;
}
return PhysicalTextureType.UNPACKED_FLOAT16;
}
function getPhysicalFromLogicalTextureType(logicalTexType, isPacked) {
if (logicalTexType === TextureUsage.UPLOAD) {
return PhysicalTextureType.PACKED_2X2_FLOAT32;
} else if (logicalTexType === TextureUsage.RENDER || logicalTexType == null) {
return getPhysicalTextureForRendering(isPacked);
} else if (
logicalTexType === TextureUsage.DOWNLOAD ||
logicalTexType === TextureUsage.PIXELS
) {
return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE;
}
throw new Error(`Unknown logical texture type ${logicalTexType}`);
}
function getKeyFromTextureShape(shapeRowsCol, physicalTexType, isPacked) {
return `${shapeRowsCol[0]}_${shapeRowsCol[1]}_${physicalTexType}_${isPacked}`;
}
//# sourceMappingURL=texture_manager.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/tile_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class tile_gpu_TileProgram {
constructor(aShape, reps) {
this.variableNames = ["A"];
const outputShape = new Array(aShape.length);
for (let i = 0; i < outputShape.length; i++) {
outputShape[i] = aShape[i] * reps[i];
}
this.outputShape = outputShape;
this.rank = outputShape.length;
const dtype = getCoordsDataType(this.rank);
const sourceCoords = tile_gpu_getSourceCoords(aShape);
this.userCode = `
void main() {
${dtype} resRC = getOutputCoords();
setOutput(getA(${sourceCoords}));
}
`;
}
}
function tile_gpu_getSourceCoords(aShape) {
const rank = aShape.length;
if (rank > 5) {
throw Error(`Tile for rank ${rank} is not yet supported`);
}
if (rank === 1) {
return `imod(resRC, ${aShape[0]})`;
}
const currentCoords = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u"];
const sourceCoords = [];
for (let i = 0; i < aShape.length; i++) {
sourceCoords.push(`imod(${currentCoords[i]}, ${aShape[i]})`);
}
return sourceCoords.join();
}
//# sourceMappingURL=tile_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/unaryop_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class UnaryOpProgram {
constructor(aShape, opSnippet) {
this.variableNames = ["A"];
this.outputShape = aShape;
this.userCode = `
float unaryOperation(float x) {
${opSnippet}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`;
}
}
const unaryop_gpu_CHECK_NAN_SNIPPET = `if (isnan(x)) return x;`;
const LINEAR = `return x;`;
const ABS = `return abs(x);`;
const RELU =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
return (x < 0.0) ? 0.0 : x;
`;
const RELU6 =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
return (x < 0.0) ? 0.0 : min(6.0, x);
`;
const ELU = `return (x >= 0.0) ? x : (exp(x) - 1.0);`;
const SELU = `
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${dist["backend_util"].SELU_SCALEALPHA};
float scale = ${dist["backend_util"].SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;
function STEP(alpha = 0.0) {
return (
unaryop_gpu_CHECK_NAN_SNIPPET +
`
return x > 0.0 ? 1.0 : float(${alpha});
`
);
}
const NEG = `return -x;`;
const CEIL = `return ceil(x);`;
const FLOOR = `return floor(x);`;
const SIGN = `
if (isnan(x)) { return 0.0; }
return sign(x);
`;
const IS_NAN = `return float(isnan(x));`;
const IS_INF = `return float(isinf(x));`;
const IS_FINITE = `return float(!isnan(x) && !isinf(x));`;
const ROUND = `
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
`;
const EXP = `return exp(x);`;
const EXPM1 = `return exp(x) - 1.0;`;
const LOG = `if (x < 0.0) return NAN;
return log(x);`;
const LOG1P = `return log(1.0 + x);`;
const SQRT = `return sqrt(x);`;
const RSQRT = `return inversesqrt(x);`;
const SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;
/**
* mirrors the implementation of tf.nn.softplus: https://goo.gl/vkcvwX
*
* epsilon is the difference between 1.0 and the next representable
* float. For a single precision 32 bit float this should be 2^-23, see:
* https://math.byu.edu/~schow/work/IEEEFloatingPoint.htm
*
* too_large = (x > -threshold) is value above which exp(x) may overflow
* but softplus(x) == x is within machine epsilon
*
* too_small = (x < threshold) is value below which exp(x) may underflow,
* but softplus(x) == exp(x) is within machine epsilon.
*/
const SOFTPLUS = `
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
`;
const SIN =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
return sin(x);
`;
const COS =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
return cos(x);
`;
const TAN = `return tan(x);`;
const ASIN =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`;
const ACOS =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`;
const ATAN =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
return atan(x);
`;
const SINH = `
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`;
const COSH = `
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`;
const TANH = `
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`;
const ASINH = unaryop_gpu_CHECK_NAN_SNIPPET + `return log(x + sqrt(x * x + 1.0));`;
const ACOSH =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`;
const ATANH =
unaryop_gpu_CHECK_NAN_SNIPPET +
`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`;
const ERF = `
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${dist["backend_util"].ERF_P};
float a1 = ${dist["backend_util"].ERF_A1};
float a2 = ${dist["backend_util"].ERF_A2};
float a3 = ${dist["backend_util"].ERF_A3};
float a4 = ${dist["backend_util"].ERF_A4};
float a5 = ${dist["backend_util"].ERF_A5};
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
`;
const SQUARE = `return x * x;`;
const RECIPROCAL = `return 1.0 / x;`;
const LOGICAL_NOT = `return float(!(x >= 1.0));`;
const TO_INT = `return float(int(x));`;
const CLONE = "return x;";
//# sourceMappingURL=unaryop_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/unaryop_packed_gpu.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const unaryop_packed_gpu_LINEAR = `return x;`;
const unaryop_packed_gpu_LOG = `
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
`;
const unaryop_packed_gpu_RELU = `
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
const unaryop_packed_gpu_RELU6 = `
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
const unaryop_packed_gpu_ELU = `
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`;
class UnaryOpPackedProgram {
constructor(aShape, opSnippet) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = true;
this.outputShape = aShape;
this.userCode = `
vec4 unaryOperation(vec4 x) {
${opSnippet}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`;
}
}
//# sourceMappingURL=unaryop_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/unpack_gpu.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class unpack_gpu_UnpackProgram {
constructor(outputShape) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = false;
this.outputShape = outputShape;
const rank = outputShape.length;
const channels = getChannels("rc", rank);
const dtype = getCoordsDataType(rank);
const sourceCoords = getSourceCoords(rank, channels);
const innerDims = channels.slice(-2);
const coords = rank <= 1 ? "rc" : `vec2(${innerDims.join(",")})`;
this.userCode = `
void main() {
${dtype} rc = getOutputCoords();
vec4 packedInput = getA(${sourceCoords});
setOutput(getChannel(packedInput, ${coords}));
}
`;
}
}
//# sourceMappingURL=unpack_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/backend_webgl.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Import webgl flags.
const { segment_util } = dist["backend_util"];
const split = dist["kernel_impls"].split;
const tile = dist["kernel_impls"].tile;
const topkImpl = dist["kernel_impls"].topkImpl;
const whereImpl = dist["kernel_impls"].whereImpl;
const EPSILON_FLOAT32 = 1e-7;
const EPSILON_FLOAT16 = 1e-4;
const binaryCaches = {};
function getBinaryCache(webGLVersion) {
if (webGLVersion in binaryCaches) {
return binaryCaches[webGLVersion];
}
binaryCaches[webGLVersion] = {};
return binaryCaches[webGLVersion];
}
function mapActivationToShaderProgram(activation, packed = false) {
if (activation === "linear") {
if (packed) {
return unaryop_packed_gpu_LINEAR;
}
return LINEAR;
} else if (activation === "relu") {
if (packed) {
return unaryop_packed_gpu_RELU;
}
return RELU;
} else if (activation === "elu") {
if (packed) {
return unaryop_packed_gpu_ELU;
}
return ELU;
} else if (activation === "relu6") {
if (packed) {
return unaryop_packed_gpu_RELU6;
}
return RELU6;
} else if (activation === "prelu") {
if (packed) {
return binaryop_packed_gpu_PRELU;
}
return PRELU;
}
throw new Error(`Activation ${activation} has not been implemented for the WebGL backend.`);
}
// Empirically determined constant used to determine size threshold for handing
// off execution to the CPU.
const CPU_HANDOFF_SIZE_THRESHOLD = 128;
// Empirically determined constant used to decide the number of MB on GPU
// before we warn about high memory use. The MB are this constant * screen area
// * dpi / 1024 / 1024.
const BEFORE_PAGING_CONSTANT = 600;
function numMBBeforeWarning() {
if (Object(dist["env"])().global.screen == null) {
return 1024; // 1 GB.
}
return (
(Object(dist["env"])().global.screen.height *
Object(dist["env"])().global.screen.width *
window.devicePixelRatio *
BEFORE_PAGING_CONSTANT) /
1024 /
1024
);
}
// Empirically determined minimal shared dimension in matmul before we forward
// to a.mul(b).sum() in order to take advantage of GPU parallelism. See
// https://github.com/tensorflow/tfjs-core/pull/1379 for benchmarks.
const MATMUL_SHARED_DIM_THRESHOLD = 1000;
class backend_webgl_MathBackendWebGL extends dist["KernelBackend"] {
constructor(gpgpu) {
super();
// Maps data ids that have a pending read operation, to list of subscribers.
this.pendingRead = new WeakMap();
// List of data ids that are scheduled for disposal, but are waiting on a
// pending read operation.
this.pendingDisposal = new WeakSet();
// Used to count the number of 'shallow' sliced tensors that point to the
// same data id.
this.dataRefCount = new WeakMap();
this.numBytesInGPU = 0;
// Accumulated time spent (including blocking) in uploading data to webgl.
this.uploadWaitMs = 0;
// Accumulated time spent (including blocking in downloading data from webgl.
this.downloadWaitMs = 0;
this.warnedAboutMemory = false;
this.pendingDeletes = 0;
this.disposed = false;
if (!Object(dist["env"])().getBool("HAS_WEBGL")) {
throw new Error("WebGL is not supported on this device");
}
if (gpgpu == null) {
const gl = getWebGLContext(Object(dist["env"])().getNumber("WEBGL_VERSION"));
this.binaryCache = getBinaryCache(Object(dist["env"])().getNumber("WEBGL_VERSION"));
this.gpgpu = new gpgpu_context_GPGPUContext(gl);
this.canvas = gl.canvas;
this.gpgpuCreatedLocally = true;
} else {
this.gpgpu = gpgpu;
this.binaryCache = {};
this.gpgpuCreatedLocally = false;
this.canvas = gpgpu.gl.canvas;
}
this.textureManager = new texture_manager_TextureManager(this.gpgpu);
this.numMBBeforeWarning = numMBBeforeWarning();
this.texData = new dist["DataStorage"](this, Object(dist["engine"])());
}
numDataIds() {
return (
this.texData.numDataIds() +
(this.cpuBackend ? this.cpuBackend.numDataIds() : 0) -
this.pendingDeletes
);
}
write(values, shape, dtype) {
if (Object(dist["env"])().getBool("DEBUG")) {
this.checkNumericalProblems(values);
}
if (dtype === "complex64" && values != null) {
throw new Error(
`Cannot write to a complex64 dtype. ` + `Please use tf.complex(real, imag).`
);
}
const dataId = {};
this.texData.set(dataId, { shape, dtype, values, usage: TextureUsage.UPLOAD });
return dataId;
}
move(dataId, values, shape, dtype) {
if (Object(dist["env"])().getBool("DEBUG")) {
this.checkNumericalProblems(values);
}
if (dtype === "complex64") {
throw new Error(
`Cannot write to a complex64 dtype. ` + `Please use tf.complex(real, imag).`
);
}
this.texData.set(dataId, { shape, dtype, values, usage: TextureUsage.UPLOAD });
}
readSync(dataId) {
const texData = this.texData.get(dataId);
const { values, dtype, complexTensors, slice, shape, isPacked } = texData;
if (slice != null) {
let program;
if (isPacked) {
program = new UnaryOpPackedProgram(shape, CLONE);
} else {
program = new UnaryOpProgram(shape, CLONE);
}
const res = this.runWebGLProgram(program, [{ dataId, shape, dtype }], dtype);
const data = this.readSync(res.dataId);
this.disposeData(res.dataId);
return data;
}
if (values != null) {
return this.convertAndCacheOnCPU(dataId);
}
if (dtype === "string") {
return values;
}
const shouldTimeProgram = this.activeTimers != null;
let start;
if (shouldTimeProgram) {
start = dist["util"].now();
}
let result;
if (dtype === "complex64") {
const realValues = complexTensors.real.dataSync();
const imagValues = complexTensors.imag.dataSync();
result = dist["backend_util"].mergeRealAndImagArrays(realValues, imagValues);
} else {
result = this.getValuesFromTexture(dataId);
}
if (shouldTimeProgram) {
this.downloadWaitMs += dist["util"].now() - start;
}
return this.convertAndCacheOnCPU(dataId, result);
}
async read(dataId) {
if (this.pendingRead.has(dataId)) {
const subscribers = this.pendingRead.get(dataId);
return new Promise((resolve) => subscribers.push(resolve));
}
const texData = this.texData.get(dataId);
const { values, shape, slice, dtype, complexTensors, isPacked } = texData;
if (slice != null) {
let program;
if (isPacked) {
program = new UnaryOpPackedProgram(shape, CLONE);
} else {
program = new UnaryOpProgram(shape, CLONE);
}
const res = this.runWebGLProgram(program, [{ dataId, shape, dtype }], dtype);
const data = this.read(res.dataId);
this.disposeData(res.dataId);
return data;
}
if (values != null) {
return this.convertAndCacheOnCPU(dataId);
}
if (
!Object(dist["env"])().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED") &&
Object(dist["env"])().getNumber("WEBGL_VERSION") === 2
) {
throw new Error(
`tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and ` +
`WEBGL_VERSION=2 not yet supported.`
);
}
let buffer = null;
let tmpDownloadTarget;
if (dtype !== "complex64" && Object(dist["env"])().get("WEBGL_BUFFER_SUPPORTED")) {
// Possibly copy the texture into a buffer before inserting a fence.
tmpDownloadTarget = this.decode(dataId);
const tmpData = this.texData.get(tmpDownloadTarget.dataId);
buffer = this.gpgpu.createBufferFromTexture(
tmpData.texture,
...getDenseTexShape(shape)
);
}
this.pendingRead.set(dataId, []);
if (dtype !== "complex64") {
// Create a fence and wait for it to resolve.
await this.gpgpu.createAndWaitForFence();
}
// Download the values from the GPU.
let vals;
if (dtype === "complex64") {
const ps = await Promise.all([complexTensors.real.data(), complexTensors.imag.data()]);
const realValues = ps[0];
const imagValues = ps[1];
vals = dist["backend_util"].mergeRealAndImagArrays(realValues, imagValues);
} else if (buffer == null) {
vals = this.getValuesFromTexture(dataId);
} else {
const size = dist["util"].sizeFromShape(shape);
vals = this.gpgpu.downloadFloat32MatrixFromBuffer(buffer, size);
}
if (tmpDownloadTarget != null) {
this.disposeData(tmpDownloadTarget.dataId);
}
const dTypeVals = this.convertAndCacheOnCPU(dataId, vals);
const subscribers = this.pendingRead.get(dataId);
this.pendingRead.delete(dataId);
// Notify all pending reads.
subscribers.forEach((resolve) => resolve(dTypeVals));
if (this.pendingDisposal.has(dataId)) {
this.pendingDisposal.delete(dataId);
this.disposeData(dataId);
this.pendingDeletes--;
}
return dTypeVals;
}
checkNumericalProblems(values) {
if (values == null) {
return;
}
for (let i = 0; i < values.length; i++) {
const num = values[i];
if (!canBeRepresented(num)) {
if (Object(dist["env"])().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")) {
throw Error(
`The value ${num} cannot be represented with your ` +
`current settings. Consider enabling float32 rendering: ` +
`'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`
);
}
throw Error(`The value ${num} cannot be represented on this device.`);
}
}
}
getValuesFromTexture(dataId) {
const { shape, dtype, isPacked } = this.texData.get(dataId);
const size = dist["util"].sizeFromShape(shape);
if (Object(dist["env"])().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")) {
const tmpTarget = this.decode(dataId);
const tmpData = this.texData.get(tmpTarget.dataId);
const vals = this.gpgpu
.downloadMatrixFromPackedTexture(tmpData.texture, ...getDenseTexShape(shape))
.subarray(0, size);
this.disposeData(tmpTarget.dataId);
return vals;
}
const shouldUsePackedProgram =
Object(dist["env"])().getBool("WEBGL_PACK") && isPacked === true;
const outputShape = shouldUsePackedProgram ? getShapeAs3D(shape) : shape;
const program = shouldUsePackedProgram
? new encode_float_packed_gpu_EncodeFloatPackedProgram(outputShape)
: new encode_float_gpu_EncodeFloatProgram(outputShape);
const output = this.runWebGLProgram(
program,
[{ shape: outputShape, dtype, dataId }],
"float32"
);
const tmpData = this.texData.get(output.dataId);
const vals = this.gpgpu
.downloadByteEncodedFloatMatrixFromOutputTexture(
tmpData.texture,
tmpData.texShape[0],
tmpData.texShape[1]
)
.subarray(0, size);
this.disposeData(output.dataId);
return vals;
}
async time(f) {
const oldActiveTimers = this.activeTimers;
const newActiveTimers = [];
let outerMostTime = false;
if (this.programTimersStack == null) {
this.programTimersStack = newActiveTimers;
outerMostTime = true;
} else {
this.activeTimers.push(newActiveTimers);
}
this.activeTimers = newActiveTimers;
f();
// needing to split these up because util.flatten only accepts certain types
const flattenedActiveTimerQueries = dist["util"]
.flatten(this.activeTimers.map((d) => d.query))
.filter((d) => d != null);
const flattenedActiveTimerNames = dist["util"]
.flatten(this.activeTimers.map((d) => d.name))
.filter((d) => d != null);
this.activeTimers = oldActiveTimers;
if (outerMostTime) {
this.programTimersStack = null;
}
const res = {
uploadWaitMs: this.uploadWaitMs,
downloadWaitMs: this.downloadWaitMs,
kernelMs: null,
wallMs: null, // will be filled by the engine
};
if (
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0
) {
const kernelMs = await Promise.all(flattenedActiveTimerQueries);
res["kernelMs"] = dist["util"].sum(kernelMs);
res["getExtraProfileInfo"] = () =>
kernelMs
.map((d, i) => ({ name: flattenedActiveTimerNames[i], ms: d }))
.map((d) => `${d.name}: ${d.ms}`)
.join(", ");
} else {
res["kernelMs"] = {
error: "WebGL query timers are not supported in this environment.",
};
}
this.uploadWaitMs = 0;
this.downloadWaitMs = 0;
return res;
}
memory() {
return { unreliable: false, numBytesInGPU: this.numBytesInGPU };
}
startTimer() {
if (
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0
) {
return this.gpgpu.beginQuery();
}
return { startMs: dist["util"].now(), endMs: null };
}
endTimer(query) {
if (
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0
) {
this.gpgpu.endQuery();
return query;
}
query.endMs = dist["util"].now();
return query;
}
async getQueryTime(query) {
if (
Object(dist["env"])().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0
) {
return this.gpgpu.waitForQueryAndGetTime(query);
}
const timerQuery = query;
return timerQuery.endMs - timerQuery.startMs;
}
disposeData(dataId) {
if (this.pendingDisposal.has(dataId)) {
return;
}
if (this.pendingRead.has(dataId)) {
this.pendingDisposal.add(dataId);
this.pendingDeletes++;
return;
}
// No-op if already disposed.
if (!this.texData.has(dataId)) {
return;
}
this.releaseGPUData(dataId);
const { complexTensors } = this.texData.get(dataId);
if (complexTensors != null) {
complexTensors.real.dispose();
complexTensors.imag.dispose();
}
this.texData.delete(dataId);
}
releaseGPUData(dataId) {
const { texture, dtype, texShape, usage, isPacked, slice } = this.texData.get(dataId);
const key = (slice && slice.origDataId) || dataId;
const refCount = this.dataRefCount.get(key);
if (refCount > 1) {
this.dataRefCount.set(key, refCount - 1);
} else {
this.dataRefCount.delete(key);
if (texture != null) {
this.numBytesInGPU -= this.computeBytes(texShape, dtype);
this.textureManager.releaseTexture(texture, texShape, usage, isPacked);
}
}
const texData = this.texData.get(dataId);
texData.texture = null;
texData.texShape = null;
texData.isPacked = false;
texData.slice = null;
}
getTexture(dataId) {
this.uploadToGPU(dataId);
return this.texData.get(dataId).texture;
}
/**
* Returns internal information for the specific data bucket. Used in unit
* tests.
*/
getDataInfo(dataId) {
return this.texData.get(dataId);
}
getCPUBackend() {
if (!Object(dist["env"])().getBool("WEBGL_CPU_FORWARD")) {
return null;
}
if (this.cpuBackend == null) {
this.cpuBackend = Object(dist["engine"])().findBackend("cpu");
}
return this.cpuBackend;
}
/*
Tests whether all the inputs to an op are small and on the CPU. This heuristic
determines when it would be faster to execute a kernel on the CPU. WebGL
kernels opt into running this check and forwarding when appropriate.
TODO(https://github.com/tensorflow/tfjs/issues/872): Develop a more
sustainable strategy for optimizing backend execution of ops.
*/
shouldExecuteOnCPU(inputs, sizeThreshold = CPU_HANDOFF_SIZE_THRESHOLD) {
return (
this.getCPUBackend() != null &&
inputs.every(
(input) =>
this.texData.get(input.dataId).texture == null &&
dist["util"].sizeFromShape(input.shape) < sizeThreshold
)
);
}
getGPGPUContext() {
return this.gpgpu;
}
complex(real, imag) {
const result = this.makeOutput(real.shape, "complex64");
const resultData = this.texData.get(result.dataId);
// The backend owns the reference to the underlying real and imaginary
// clones. These will explicitly get disposed when the complex tensor is
// disposed.
resultData.complexTensors = {
real: Object(dist["engine"])().keep(real.clone()),
imag: Object(dist["engine"])().keep(imag.clone()),
};
return result;
}
real(input) {
const resultData = this.texData.get(input.dataId);
return resultData.complexTensors.real.clone();
}
imag(input) {
const resultData = this.texData.get(input.dataId);
return resultData.complexTensors.imag.clone();
}
slice(x, begin, size) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.slice(x, begin, size);
}
// Short-circuit computation if the slice is zero-sized.
if (dist["util"].sizeFromShape(size) === 0) {
return Object(dist["tensor"])([], size, x.dtype);
}
const { isPacked } = this.texData.get(x.dataId);
const isContinous = dist["slice_util"].isSliceContinous(x.shape, begin, size);
if (isPacked || !isContinous) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_ARRAY_OPERATIONS")
? new slice_packed_gpu_SlicePackedProgram(size)
: new slice_gpu_SliceProgram(size);
const customSetup = program.getCustomSetupFunc(begin);
return this.compileAndRun(program, [x], null, customSetup);
}
this.uploadToGPU(x.dataId);
return this.shallowSlice(x, begin, size);
}
shallowSlice(x, begin, size) {
const xTexData = this.texData.get(x.dataId);
const t = this.makeOutput(size, x.dtype);
const newTexData = this.texData.get(t.dataId);
// Copy texture data from the original tensor.
Object.assign(newTexData, xTexData);
newTexData.shape = size;
newTexData.dtype = x.dtype;
let flatOffset = dist["slice_util"].computeFlatOffset(begin, x.strides);
if (xTexData.slice) {
// We are slicing an already sliced tensor, so we have to accumulate
// the offset.
flatOffset += xTexData.slice.flatOffset;
}
newTexData.slice = {
flatOffset,
// Point to the original dataId, which is used to do ref counting.
origDataId: (xTexData.slice && xTexData.slice.origDataId) || x.dataId,
};
// Increase the ref count for that data bucket.
const refCount = this.dataRefCount.get(newTexData.slice.origDataId) || 1;
this.dataRefCount.set(newTexData.slice.origDataId, refCount + 1);
return t;
}
stridedSlice(x, begin, end, strides) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.stridedSlice(x, begin, end, strides);
}
const outShape = dist["slice_util"].computeOutShape(begin, end, strides);
if (outShape.some((axis) => axis === 0)) {
return Object(dist["tensor"])([], outShape);
}
const program = new strided_slice_gpu_StridedSliceProgram(begin, strides, outShape);
return this.compileAndRun(program, [x]);
}
reverse(x, axis) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_ARRAY_OPERATIONS")
? new reverse_packed_gpu_ReversePackedProgram(x.shape, axis)
: new reverse_gpu_ReverseProgram(x.shape, axis);
return this.compileAndRun(program, [x]);
}
concat(tensors, axis) {
if (tensors[0].dtype === "complex64") {
const reals = tensors.map((t) => Object(dist["real"])(t));
const imags = tensors.map((t) => Object(dist["imag"])(t));
return Object(dist["complex"])(this.concat(reals, axis), this.concat(imags, axis));
}
if (this.shouldExecuteOnCPU(tensors)) {
return this.cpuBackend.concat(tensors, axis);
}
if (tensors.length === 1) {
return tensors[0];
}
if (tensors.length > Object(dist["env"])().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")) {
const midIndex = Math.floor(tensors.length / 2);
const leftSide = this.concat(tensors.slice(0, midIndex), axis);
const rightSide = this.concat(tensors.slice(midIndex), axis);
return this.concat([leftSide, rightSide], axis);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_ARRAY_OPERATIONS") && tensors[0].rank > 1) {
const program = new concat_packed_gpu_ConcatPackedProgram(
tensors.map((t) => t.shape),
axis
);
return this.compileAndRun(program, tensors);
}
// Any concat of n-dimensional tensors across any axis can be reduced to
// a concatenation of two-dimensional tensors across the axis 1 by first
// partitioning the axes of the original tensors into those less than the
// axis to be concatenated and the rest. Then reshape the tensors
// into a two-dimensional tensor by collapsing these two sets of axes and
// concatenate the resulting matrices across the axis 1, finally reshaping
// the result to have the proper shape.
const outShape = dist["backend_util"].computeOutShape(
tensors.map((t) => t.shape),
axis
);
const tensors2D = tensors.map((t) =>
t.as2D(-1, dist["util"].sizeFromShape(t.shape.slice(axis)))
);
const program = new concat_gpu_ConcatProgram(tensors2D.map((t) => t.shape));
const res = this.compileAndRun(program, tensors2D);
return res.reshape(outShape);
}
neg(x) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.neg(x);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
return this.packedUnaryOp(x, NEG, x.dtype);
}
const program = new UnaryOpProgram(x.shape, NEG);
return this.compileAndRun(program, [x]);
}
batchMatMul(a, b, transposeA, transposeB) {
const outerShapeA = transposeA ? a.shape[2] : a.shape[1];
const outerShapeB = transposeB ? b.shape[1] : b.shape[2];
const sharedDim = transposeA ? a.shape[1] : a.shape[2];
const [batch, ,] = a.shape;
// Since the matrices are vectors, it is faster to call mul().sum()
// because sum() is O(sqrt(N)) due to divide-and-conquer.
if ((outerShapeA === 1 || outerShapeB === 1) && sharedDim > MATMUL_SHARED_DIM_THRESHOLD) {
if (transposeA) {
a = Object(dist["transpose"])(a, [0, 2, 1]);
}
if (transposeB) {
b = Object(dist["transpose"])(b, [0, 2, 1]);
}
const a3D = outerShapeB === 1 ? a : a.as3D(batch, sharedDim, 1);
const axis = outerShapeB === 1 ? 2 : 1;
const b3D = outerShapeB === 1 ? b.as3D(batch, 1, sharedDim) : b;
return this.multiply(a3D, b3D).sum(axis, true /* keepDims */);
}
const dtype = Object(dist["upcastType"])(a.dtype, b.dtype);
const program = new MatMulPackedProgram(
a.shape,
[batch, outerShapeA, outerShapeB],
transposeA,
transposeB
);
return this.compileAndRun(program, [a, b], dtype);
}
fusedBatchMatMul({
a,
b,
transposeA,
transposeB,
bias,
activation,
preluActivationWeights,
}) {
const outerShapeA = transposeA ? a.shape[2] : a.shape[1];
const outerShapeB = transposeB ? b.shape[1] : b.shape[2];
const [batch, ,] = a.shape;
const dtype = Object(dist["upcastType"])(a.dtype, b.dtype);
const hasBias = bias != null;
const hasPreluActivationWeights = preluActivationWeights != null;
const fusedActivation = activation
? mapActivationToShaderProgram(activation, true)
: null;
const program = new MatMulPackedProgram(
a.shape,
[batch, outerShapeA, outerShapeB],
transposeA,
transposeB,
hasBias,
fusedActivation,
hasPreluActivationWeights
);
const inputs = [a, b];
if (bias) {
inputs.push(bias);
}
if (preluActivationWeights) {
inputs.push(preluActivationWeights);
}
return this.compileAndRun(program, inputs, dtype);
}
multiply(a, b) {
if (a.dtype === "complex64") {
const aData = this.texData.get(a.dataId);
const bData = this.texData.get(b.dataId);
const realProgram = new binaryop_complex_gpu_BinaryOpComplexProgram(
COMPLEX_MULTIPLY.REAL,
a.shape,
b.shape
);
const imagProgram = new binaryop_complex_gpu_BinaryOpComplexProgram(
COMPLEX_MULTIPLY.IMAG,
a.shape,
b.shape
);
const inputs = [
this.makeComplexComponentTensorInfo(a, aData.complexTensors.real),
this.makeComplexComponentTensorInfo(a, aData.complexTensors.imag),
this.makeComplexComponentTensorInfo(b, bData.complexTensors.real),
this.makeComplexComponentTensorInfo(b, bData.complexTensors.imag),
];
const real = this.compileAndRun(realProgram, inputs);
const imag = this.compileAndRun(imagProgram, inputs);
const complex = this.complex(real, imag);
real.dispose();
imag.dispose();
return complex;
}
if (this.shouldExecuteOnCPU([a, b])) {
return this.cpuBackend.multiply(a, b);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, MUL, a.dtype);
}
const program = new binaryop_gpu_BinaryOpProgram(MUL, a.shape, b.shape);
return this.compileAndRun(program, [a, b], a.dtype);
}
batchNorm(x, mean, variance, offset, scale, varianceEpsilon) {
const inputs = [x, mean, variance];
let offsetShape = null;
if (offset != null) {
offsetShape = offset.shape;
inputs.push(offset);
}
let scaleShape = null;
if (scale != null) {
scaleShape = scale.shape;
inputs.push(scale);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_NORMALIZATION")) {
const batchNormPackedProgram = new batchnorm_packed_gpu_BatchNormPackedProgram(
x.shape,
mean.shape,
variance.shape,
offsetShape,
scaleShape,
varianceEpsilon
);
return this.compileAndRun(batchNormPackedProgram, inputs);
}
const batchNormProgram = new batchnorm_gpu_BatchNormProgram(
x.shape,
mean.shape,
variance.shape,
offsetShape,
scaleShape,
varianceEpsilon
);
return this.compileAndRun(batchNormProgram, inputs);
}
localResponseNormalization4D(x, radius, bias, alpha, beta) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_NORMALIZATION")
? new LRNPackedProgram(x.shape, radius, bias, alpha, beta)
: new LRNProgram(x.shape, radius, bias, alpha, beta);
return this.compileAndRun(program, [x]);
}
LRNGrad(dy, inputImage, outputImage, depthRadius, bias, alpha, beta) {
const program = new LRNGradProgram(inputImage.shape, depthRadius, bias, alpha, beta);
return this.compileAndRun(program, [inputImage, outputImage, dy]);
}
tile(x, reps) {
if (x.dtype === "string") {
const data = this.readSync(x.dataId);
const decodedData = data.map((d) => dist["util"].decodeString(d));
const buf = Object(dist["buffer"])(x.shape, x.dtype, decodedData);
return tile(buf, reps);
}
const program = new tile_gpu_TileProgram(x.shape, reps);
return this.compileAndRun(program, [x]);
}
pad(x, paddings, constantValue) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_ARRAY_OPERATIONS")
? new pad_packed_gpu_PadPackedProgram(x.shape, paddings, constantValue)
: new pad_gpu_PadProgram(x.shape, paddings, constantValue);
return this.compileAndRun(program, [x]);
}
gather(x, indices, axis) {
if (this.shouldExecuteOnCPU([x, indices])) {
return this.cpuBackend.gather(x, indices, axis);
}
const program = new gather_gpu_GatherProgram(x.shape, indices.size, axis);
return this.compileAndRun(program, [x, indices]);
}
batchToSpaceND(x, blockShape, crops) {
dist["util"].assert(
x.rank <= 4,
() => "batchToSpaceND for rank > 4 with a WebGL backend not " + "implemented yet"
);
const prod = blockShape.reduce((a, b) => a * b);
const reshaped = dist["backend_util"].getReshaped(x.shape, blockShape, prod);
const permuted = dist["backend_util"].getPermuted(reshaped.length, blockShape.length);
const reshapedPermuted = dist["backend_util"].getReshapedPermuted(
x.shape,
blockShape,
prod
);
const sliceBeginCoords = dist["backend_util"].getSliceBeginCoords(
crops,
blockShape.length
);
const sliceSize = dist["backend_util"].getSliceSize(
reshapedPermuted,
crops,
blockShape.length
);
return Object(dist["transpose"])(x.reshape(reshaped), permuted)
.reshape(reshapedPermuted)
.slice(sliceBeginCoords, sliceSize);
}
spaceToBatchND(x, blockShape, paddings) {
dist["util"].assert(
x.rank <= 4,
() => "spaceToBatchND for rank > 4 with a WebGL backend not " + "implemented yet"
);
const prod = blockShape.reduce((a, b) => a * b);
const completePaddings = [[0, 0]];
completePaddings.push(...paddings);
for (let i = 1 + blockShape.length; i < x.shape.length; ++i) {
completePaddings.push([0, 0]);
}
const paddedX = x.pad(completePaddings);
const reshapedPaddedShape = dist["backend_util"].getReshaped(
paddedX.shape,
blockShape,
prod,
false
);
const permutedReshapedPaddedPermutation = dist["backend_util"].getPermuted(
reshapedPaddedShape.length,
blockShape.length,
false
);
const flattenShape = dist["backend_util"].getReshapedPermuted(
paddedX.shape,
blockShape,
prod,
false
);
return Object(dist["transpose"])(
paddedX.reshape(reshapedPaddedShape),
permutedReshapedPaddedPermutation
).reshape(flattenShape);
}
reduce(x, reduceType, dtype) {
const batchSize = x.shape[0];
const inSize = x.shape[1];
const windowSize = dist["backend_util"].computeOptimalWindowSize(inSize);
const reduceInfo = { windowSize, inSize, batchSize };
const program = new ReduceProgram(reduceInfo, reduceType);
const output = this.compileAndRun(program, [x], dtype);
// No need to run another GPGPU program.
if (output.shape[1] === 1) {
return output;
}
return this.reduce(output, reduceType, dtype);
}
argReduce(x, reduceType, bestIndicesA = null) {
let batchSize = x.shape[0];
let inSize = x.shape[1];
if (bestIndicesA != null) {
batchSize = bestIndicesA.shape[0];
inSize = bestIndicesA.shape[1];
}
const windowSize = dist["backend_util"].computeOptimalWindowSize(inSize);
const reduceInfo = { windowSize, inSize, batchSize };
const program = new ArgMinMaxProgram(reduceInfo, reduceType, bestIndicesA == null);
const inputs = [x];
if (bestIndicesA != null) {
inputs.push(bestIndicesA);
}
const output = this.compileAndRun(program, inputs, "int32");
// No need to run another GPGPU program.
if (output.shape[1] === 1) {
return output;
}
return this.argReduce(x, reduceType, output);
}
argReducePacked(x, reduceType, bestIndicesA = null) {
const inShape = bestIndicesA != null ? bestIndicesA.shape : x.shape;
const inSize = inShape[inShape.length - 1];
const windowSize = dist["backend_util"].computeOptimalWindowSize(inSize);
const program = new argminmax_packed_gpu_ArgMinMaxPackedProgram(
inShape,
windowSize,
reduceType,
bestIndicesA == null
);
const inputs = bestIndicesA == null ? [x] : [x, bestIndicesA];
const output = this.compileAndRun(program, inputs, "int32");
if (output.rank === x.rank) {
return this.argReducePacked(x, reduceType, output);
}
return output;
}
sum(x, axes) {
dist["backend_util"].assertAxesAreInnerMostDims("sum", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const inSize = dist["util"].sizeFromShape(reduceShape);
const a2D = x.as2D(-1, inSize);
const outputDType = dist["sumOutType"](x.dtype);
return this.reduce(a2D, "sum", outputDType).reshape(outShape);
}
prod(x, axes) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.prod(x, axes);
}
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const inSize = dist["util"].sizeFromShape(reduceShape);
const a2D = x.as2D(-1, inSize);
const outputDType = dist["sumOutType"](x.dtype);
return this.reduce(a2D, "prod", outputDType).reshape(outShape);
}
unsortedSegmentSum(x, segmentIds, numSegments) {
let axis = 0;
const permutation = dist["backend_util"].getAxesPermutation([axis], x.rank);
let permutedX = x;
if (permutation != null) {
permutedX = Object(dist["transpose"])(x, permutation);
axis = dist["backend_util"].getInnerMostAxes(1, x.rank)[0];
}
const outShape = segment_util.computeOutShape(permutedX.shape, axis, numSegments);
const inSize = dist["util"].sizeFromShape([permutedX.shape[axis]]);
const a2D = permutedX.as2D(-1, inSize);
const outputDType = dist["sumOutType"](x.dtype);
let result = this.segOpCompute(
a2D,
"unsortedSegmentSum",
segmentIds,
outputDType,
numSegments
).reshape(outShape);
if (permutation != null) {
result = Object(dist["transpose"])(
result,
dist["backend_util"].getUndoAxesPermutation(permutation)
);
}
return result;
}
segOpCompute(x, segOpType, segmentIds, dtype, numSegments) {
const batchSize = x.shape[0];
const inSize = x.shape[1];
const windowSize = segment_util.segOpComputeOptimalWindowSize(inSize, numSegments);
const segOpInfo = { windowSize, inSize, batchSize, numSegments };
const program = new SegmentOpProgram(segOpInfo, segOpType);
const output = this.compileAndRun(program, [x, segmentIds], dtype);
// No need to run another GPGPU program.
if (output.shape[1] === numSegments) {
return output;
}
segmentIds = Object(dist["range"])(0, numSegments).tile([inSize / windowSize]);
return this.segOpCompute(output, segOpType, segmentIds, dtype, numSegments);
}
argMinMaxReduce(x, axis, reduceType) {
const axes = [axis];
dist["backend_util"].assertAxesAreInnerMostDims(
"arg" + reduceType.charAt(0).toUpperCase() + reduceType.slice(1),
axes,
x.rank
);
if (!Object(dist["env"])().getBool("WEBGL_PACK_REDUCE") || x.rank <= 2) {
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const inSize = dist["util"].sizeFromShape(reduceShape);
const a2D = x.as2D(-1, inSize);
return this.argReduce(a2D, reduceType).reshape(outShape);
}
return this.argReducePacked(x, reduceType);
}
argMin(x, axis) {
return this.argMinMaxReduce(x, axis, "min");
}
argMax(x, axis) {
return this.argMinMaxReduce(x, axis, "max");
}
cumsum(x, axis, exclusive, reverse) {
if (axis !== x.rank - 1) {
throw new Error(
`WebGL cumsum shader expects an inner-most axis=${x.rank - 1} ` +
`but got axis=${axis}`
);
}
const program = new cumsum_gpu_CumSumProgram(x.shape, exclusive, reverse);
return this.compileAndRun(program, [x]);
}
equal(a, b) {
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_EQUAL, "bool");
}
const program = new binaryop_gpu_BinaryOpProgram(EQUAL, a.shape, b.shape);
return this.compileAndRun(program, [a, b], "bool");
}
notEqual(a, b) {
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_NOT_EQUAL, "bool");
}
const program = new binaryop_gpu_BinaryOpProgram(NOT_EQUAL, a.shape, b.shape);
return this.compileAndRun(program, [a, b], "bool");
}
less(a, b) {
if (this.shouldExecuteOnCPU([a, b])) {
return this.cpuBackend.less(a, b);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_LESS, "bool");
}
const program = new binaryop_gpu_BinaryOpProgram(LESS, a.shape, b.shape);
return this.compileAndRun(program, [a, b], "bool");
}
lessEqual(a, b) {
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_LESS_EQUAL, "bool");
}
const program = new binaryop_gpu_BinaryOpProgram(LESS_EQUAL, a.shape, b.shape);
return this.compileAndRun(program, [a, b], "bool");
}
greater(a, b) {
if (this.shouldExecuteOnCPU([a, b])) {
return this.cpuBackend.greater(a, b);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_GREATER, "bool");
}
const program = new binaryop_gpu_BinaryOpProgram(GREATER, a.shape, b.shape);
return this.compileAndRun(program, [a, b], "bool");
}
greaterEqual(a, b) {
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_GREATER_EQUAL, "bool");
}
const program = new binaryop_gpu_BinaryOpProgram(GREATER_EQUAL, a.shape, b.shape);
return this.compileAndRun(program, [a, b], "bool");
}
logicalNot(x) {
const program = new UnaryOpProgram(x.shape, LOGICAL_NOT);
return this.compileAndRun(program, [x]);
}
logicalAnd(a, b) {
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_LOGICAL_AND, "bool");
}
const program = new binaryop_gpu_BinaryOpProgram(LOGICAL_AND, a.shape, b.shape);
return this.compileAndRun(program, [a, b], "bool");
}
logicalOr(a, b) {
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_LOGICAL_OR, "bool");
}
const program = new binaryop_gpu_BinaryOpProgram(LOGICAL_OR, a.shape, b.shape);
return this.compileAndRun(program, [a, b], "bool");
}
select(condition, a, b) {
const program = new select_gpu_SelectProgram(condition.rank, a.shape, a.rank);
return this.compileAndRun(
program,
[condition, a, b],
Object(dist["upcastType"])(a.dtype, b.dtype)
);
}
where(condition) {
dist["backend_util"].warn(
"tf.where() in webgl locks the UI thread. " + "Call tf.whereAsync() instead"
);
const condVals = condition.dataSync();
return whereImpl(condition.shape, condVals);
}
topk(x, k, sorted) {
const xVals = x.dataSync();
return topkImpl(xVals, x.shape, x.dtype, k, sorted);
}
min(x, axes) {
dist["backend_util"].assertAxesAreInnerMostDims("min", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const inSize = dist["util"].sizeFromShape(reduceShape);
const a2D = x.as2D(-1, inSize);
return this.reduce(a2D, "min", a2D.dtype).reshape(outShape);
}
minimum(a, b) {
if (this.shouldExecuteOnCPU([a, b])) {
return this.cpuBackend.minimum(a, b);
}
const program = Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")
? new binaryop_packed_gpu_BinaryOpPackedProgram(
binaryop_packed_gpu_MIN,
a.shape,
b.shape
)
: new binaryop_gpu_BinaryOpProgram(MIN, a.shape, b.shape);
return this.compileAndRun(program, [a, b]);
}
mod(a, b) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")
? new binaryop_packed_gpu_BinaryOpPackedProgram(
binaryop_packed_gpu_MOD,
a.shape,
b.shape
)
: new binaryop_gpu_BinaryOpProgram(MOD, a.shape, b.shape);
return this.compileAndRun(program, [a, b]);
}
maximum(a, b) {
if (this.shouldExecuteOnCPU([a, b])) {
return this.cpuBackend.maximum(a, b);
}
const program = Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")
? new binaryop_packed_gpu_BinaryOpPackedProgram(
binaryop_packed_gpu_MAX,
a.shape,
b.shape
)
: new binaryop_gpu_BinaryOpProgram(MAX, a.shape, b.shape);
return this.compileAndRun(program, [a, b]);
}
all(x, axes) {
dist["backend_util"].assertAxesAreInnerMostDims("all", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const inSize = dist["util"].sizeFromShape(reduceShape);
const a2D = x.as2D(-1, inSize);
return this.reduce(a2D, "all", a2D.dtype).reshape(outShape);
}
any(x, axes) {
dist["backend_util"].assertAxesAreInnerMostDims("any", axes, x.rank);
const [outShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
x.shape,
axes
);
const inSize = dist["util"].sizeFromShape(reduceShape);
const a2D = x.as2D(-1, inSize);
return this.reduce(a2D, "any", a2D.dtype).reshape(outShape);
}
floorDiv(a, b) {
const op = INT_DIV;
const outputDtype = "int32";
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, binaryop_packed_gpu_INT_DIV, outputDtype);
}
const program = new binaryop_gpu_BinaryOpProgram(op, a.shape, b.shape);
return this.compileAndRun(program, [a, b], outputDtype);
}
add(a, b) {
if (a.dtype === "complex64" && b.dtype === "complex64") {
return this.complexSeparableBinaryOp(a, b, ADD);
}
if (this.shouldExecuteOnCPU([a, b])) {
return this.cpuBackend.add(a, b);
}
const dtype = Object(dist["upcastType"])(a.dtype, b.dtype);
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, ADD, dtype);
}
const program = new binaryop_gpu_BinaryOpProgram(ADD, a.shape, b.shape);
return this.compileAndRun(program, [a, b], dtype);
}
packedUnaryOp(x, op, dtype) {
const program = new UnaryOpPackedProgram(x.shape, op);
return this.compileAndRun(program, [x], dtype);
}
packedBinaryOp(a, b, op, dtype, checkOutOfBounds = false) {
const program = new binaryop_packed_gpu_BinaryOpPackedProgram(
op,
a.shape,
b.shape,
checkOutOfBounds
);
return this.compileAndRun(program, [a, b], dtype);
}
/**
* Computes a complex binary operation that can be decomposed into a simple
* binary operation on both the real and imagary parts.
*/
complexSeparableBinaryOp(a, b, op) {
const aData = this.texData.get(a.dataId);
const bData = this.texData.get(b.dataId);
const [real, imag] = [
[aData.complexTensors.real, bData.complexTensors.real],
[aData.complexTensors.imag, bData.complexTensors.imag],
].map((complexParts) => {
const [aPart, bPart] = complexParts;
const aHandle = this.makeComplexComponentTensorInfo(a, aPart);
const bHandle = this.makeComplexComponentTensorInfo(b, bPart);
const program = new binaryop_gpu_BinaryOpProgram(op, a.shape, b.shape);
return this.compileAndRun(
program,
[aHandle, bHandle],
Object(dist["upcastType"])(aPart.dtype, bPart.dtype)
);
});
const complex = this.complex(real, imag);
real.dispose();
imag.dispose();
return complex;
}
// Returns a TensorInfo with the complex shape and the dataId of the
// underlying part. We need to do this because a reshaped complex tensor is
// not reflected in its parts.
makeComplexComponentTensorInfo(complexTensor, complexPart) {
return {
dataId: complexPart.dataId,
dtype: complexPart.dtype,
shape: complexTensor.shape,
};
}
addN(tensors) {
if (tensors.length === 1) {
return tensors[0];
}
// Limit the number of uploaded textures for optimization.
if (tensors.length > Object(dist["env"])().get("WEBGL_MAX_TEXTURES_IN_SHADER")) {
const midIndex = Math.floor(tensors.length / 2);
const leftSide = this.addN(tensors.slice(0, midIndex));
const rightSide = this.addN(tensors.slice(midIndex));
return this.addN([leftSide, rightSide]);
}
const dtype = tensors
.map((t) => t.dtype)
.reduce((d1, d2) => Object(dist["upcastType"])(d1, d2));
const shapes = tensors.map((t) => t.shape);
// We can make sure shapes are identical in op level.
const usePackedOp = Object(dist["env"])().getBool("WEBGL_PACK");
const program = usePackedOp
? new AddNPackedProgram(tensors[0].shape, shapes)
: new AddNProgram(tensors[0].shape, shapes);
return this.compileAndRun(program, tensors, dtype);
}
subtract(a, b) {
if (a.dtype === "complex64" && b.dtype === "complex64") {
return this.complexSeparableBinaryOp(a, b, SUB);
}
if (this.shouldExecuteOnCPU([a, b])) {
return this.cpuBackend.subtract(a, b);
}
const dtype = Object(dist["upcastType"])(a.dtype, b.dtype);
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
return this.packedBinaryOp(a, b, SUB, a.dtype);
}
const program = new binaryop_gpu_BinaryOpProgram(SUB, a.shape, b.shape);
return this.compileAndRun(program, [a, b], dtype);
}
pow(a, b) {
const usePackedOp = Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS");
const program = usePackedOp
? new binaryop_packed_gpu_BinaryOpPackedProgram(
binaryop_packed_gpu_POW,
a.shape,
b.shape
)
: new binaryop_gpu_BinaryOpProgram(POW, a.shape, b.shape);
const dtype = Object(dist["upcastType"])(a.dtype, b.dtype);
return this.compileAndRun(program, [a, b], dtype);
}
ceil(x) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.ceil(x);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
return this.packedUnaryOp(x, CEIL, x.dtype);
}
const program = new UnaryOpProgram(x.shape, CEIL);
return this.compileAndRun(program, [x]);
}
floor(x) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.floor(x);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
return this.packedUnaryOp(x, FLOOR, x.dtype);
}
const program = new UnaryOpProgram(x.shape, FLOOR);
return this.compileAndRun(program, [x]);
}
sign(x) {
const program = new UnaryOpProgram(x.shape, SIGN);
return this.compileAndRun(program, [x]);
}
isNaN(x) {
const program = new UnaryOpProgram(x.shape, IS_NAN);
return this.compileAndRun(program, [x], "bool");
}
isInf(x) {
const program = new UnaryOpProgram(x.shape, IS_INF);
return this.compileAndRun(program, [x], "bool");
}
isFinite(x) {
const program = new UnaryOpProgram(x.shape, IS_FINITE);
return this.compileAndRun(program, [x], "bool");
}
round(x) {
const program = new UnaryOpProgram(x.shape, ROUND);
return this.compileAndRun(program, [x]);
}
exp(x) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.exp(x);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
return this.packedUnaryOp(x, EXP, x.dtype);
}
const program = new UnaryOpProgram(x.shape, EXP);
return this.compileAndRun(program, [x]);
}
expm1(x) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.expm1(x);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
return this.packedUnaryOp(x, EXPM1, x.dtype);
}
const program = new UnaryOpProgram(x.shape, EXPM1);
return this.compileAndRun(program, [x]);
}
softmax(logits, dim) {
const axes = dist["util"].parseAxisParam([dim], logits.shape);
// TODO(annxingyuan): Call maxImpl rather than op as part of softmax kernel
// modularization.
const maxLogit = Object(dist["max"])(logits, axes);
const expandedShape = dist["backend_util"].expandShapeToKeepDim(maxLogit.shape, axes);
const a = this.subtract(logits, maxLogit.reshape(expandedShape));
const b = this.exp(a);
const sumExp = this.sum(b, axes).reshape(expandedShape);
// TODO(annxingyuan): Call divImpl rather than op as part of softmax kernel
// modularization.
return Object(dist["div"])(b, sumExp);
}
log(x) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.log(x);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
return this.packedUnaryOp(x, unaryop_packed_gpu_LOG, x.dtype);
}
const program = new UnaryOpProgram(x.shape, LOG);
return this.compileAndRun(program, [x]);
}
log1p(x) {
const program = new UnaryOpProgram(x.shape, LOG1P);
return this.compileAndRun(program, [x]);
}
sqrt(x) {
const program = new UnaryOpProgram(x.shape, SQRT);
return this.compileAndRun(program, [x]);
}
rsqrt(x) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.rsqrt(x);
}
const program = new UnaryOpProgram(x.shape, RSQRT);
return this.compileAndRun(program, [x]);
}
reciprocal(x) {
const program = new UnaryOpProgram(x.shape, RECIPROCAL);
return this.compileAndRun(program, [x]);
}
relu(x) {
let program;
if (Object(dist["env"])().getBool("WEBGL_PACK")) {
program = new UnaryOpPackedProgram(x.shape, unaryop_packed_gpu_RELU);
} else {
program = new UnaryOpProgram(x.shape, RELU);
}
return this.compileAndRun(program, [x]);
}
relu6(x) {
let program;
if (Object(dist["env"])().getBool("WEBGL_PACK")) {
program = new UnaryOpPackedProgram(x.shape, unaryop_packed_gpu_RELU6);
} else {
program = new UnaryOpProgram(x.shape, RELU6);
}
return this.compileAndRun(program, [x]);
}
prelu(x, alpha) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")
? new binaryop_packed_gpu_BinaryOpPackedProgram(
binaryop_packed_gpu_PRELU,
x.shape,
alpha.shape
)
: new binaryop_gpu_BinaryOpProgram(PRELU, x.shape, alpha.shape);
return this.compileAndRun(program, [x, alpha]);
}
elu(x) {
if (Object(dist["env"])().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
return this.packedUnaryOp(x, unaryop_packed_gpu_ELU, x.dtype);
}
const program = new UnaryOpProgram(x.shape, ELU);
return this.compileAndRun(program, [x]);
}
eluDer(dy, y) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")
? new binaryop_packed_gpu_BinaryOpPackedProgram(
binaryop_packed_gpu_ELU_DER,
dy.shape,
y.shape
)
: new binaryop_gpu_BinaryOpProgram(ELU_DER, dy.shape, y.shape);
return this.compileAndRun(program, [dy, y]);
}
selu(x) {
const program = new UnaryOpProgram(x.shape, SELU);
return this.compileAndRun(program, [x]);
}
int(x) {
const program = new UnaryOpProgram(x.shape, TO_INT);
return this.compileAndRun(program, [x], "int32");
}
clip(x, min, max) {
let program;
if (Object(dist["env"])().getBool("WEBGL_PACK_CLIP")) {
program = new ClipPackedProgram(x.shape);
} else {
program = new ClipProgram(x.shape);
}
const customSetup = program.getCustomSetupFunc(min, max);
return this.compileAndRun(program, [x], null, customSetup);
}
abs(x) {
if (this.shouldExecuteOnCPU([x])) {
return this.cpuBackend.abs(x);
}
if (Object(dist["env"])().getBool("WEBGL_PACK_UNARY_OPERATIONS")) {
return this.packedUnaryOp(x, ABS, x.dtype);
}
const program = new UnaryOpProgram(x.shape, ABS);
return this.compileAndRun(program, [x]);
}
complexAbs(x) {
const xData = this.texData.get(x.dataId);
const program = new ComplexAbsProgram(x.shape);
const inputs = [
this.makeComplexComponentTensorInfo(x, xData.complexTensors.real),
this.makeComplexComponentTensorInfo(x, xData.complexTensors.imag),
];
return this.compileAndRun(program, inputs);
}
sigmoid(x) {
const program = new UnaryOpProgram(x.shape, SIGMOID);
return this.compileAndRun(program, [x]);
}
softplus(x) {
const program = new UnaryOpProgram(x.shape, SOFTPLUS);
return this.compileAndRun(program, [x]);
}
sin(x) {
const program = new UnaryOpProgram(x.shape, SIN);
return this.compileAndRun(program, [x]);
}
cos(x) {
const program = new UnaryOpProgram(x.shape, COS);
return this.compileAndRun(program, [x]);
}
tan(x) {
const program = new UnaryOpProgram(x.shape, TAN);
return this.compileAndRun(program, [x]);
}
asin(x) {
const program = new UnaryOpProgram(x.shape, ASIN);
return this.compileAndRun(program, [x]);
}
acos(x) {
const program = new UnaryOpProgram(x.shape, ACOS);
return this.compileAndRun(program, [x]);
}
atan(x) {
const program = new UnaryOpProgram(x.shape, ATAN);
return this.compileAndRun(program, [x]);
}
atan2(a, b) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")
? new binaryop_packed_gpu_BinaryOpPackedProgram(
binaryop_packed_gpu_ATAN2,
a.shape,
b.shape
)
: new binaryop_gpu_BinaryOpProgram(ATAN2, a.shape, b.shape);
return this.compileAndRun(program, [a, b]);
}
sinh(x) {
const program = new UnaryOpProgram(x.shape, SINH);
return this.compileAndRun(program, [x]);
}
cosh(x) {
const program = new UnaryOpProgram(x.shape, COSH);
return this.compileAndRun(program, [x]);
}
tanh(x) {
const program = new UnaryOpProgram(x.shape, TANH);
return this.compileAndRun(program, [x]);
}
asinh(x) {
const program = new UnaryOpProgram(x.shape, ASINH);
return this.compileAndRun(program, [x]);
}
acosh(x) {
const program = new UnaryOpProgram(x.shape, ACOSH);
return this.compileAndRun(program, [x]);
}
atanh(x) {
const program = new UnaryOpProgram(x.shape, ATANH);
return this.compileAndRun(program, [x]);
}
erf(x) {
const program = new UnaryOpProgram(x.shape, ERF);
return this.compileAndRun(program, [x]);
}
step(x, alpha) {
const program = new UnaryOpProgram(x.shape, STEP(alpha));
return this.compileAndRun(program, [x]);
}
conv2dByMatMul(x, filter, convInfo, bias, activation, preluActivationWeights) {
// Reshapes conv2D input to 2D tensors, uses matMul and then reshape the
// result from 2D to 4D.
const xShape = x.shape;
const xTexData = this.texData.get(x.dataId);
const sharedMatMulDim = convInfo.inChannels;
const outerShapeX = xShape[0] * xShape[1] * xShape[2];
const outerShapeFilter = convInfo.outChannels;
const isChannelsLast = convInfo.dataFormat === "channelsLast";
const transposeA = false;
const transposeB = false;
// TODO: Once reduction ops are packed, batchMatMul will always be packed
// and we can remove this condition.
const batchMatMulWillBeUnpacked =
(outerShapeX === 1 || outerShapeFilter === 1) &&
sharedMatMulDim > MATMUL_SHARED_DIM_THRESHOLD;
const reshapeWillBeExpensive = xShape[2] % 2 !== 0 && !!xTexData.isPacked;
if (
batchMatMulWillBeUnpacked ||
!Object(dist["env"])().getBool("WEBGL_LAZILY_UNPACK") ||
!Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS") ||
!reshapeWillBeExpensive
) {
const targetShape = isChannelsLast
? xShape[0] * xShape[1] * xShape[2]
: xShape[0] * xShape[2] * xShape[3];
const xReshaped = this.reshape(x, [1, targetShape, convInfo.inChannels]);
const filterReshaped = this.reshape(filter, [
1,
convInfo.inChannels,
convInfo.outChannels,
]);
return this.reshape(
this.fusedBatchMatMul({
a: xReshaped,
b: filterReshaped,
transposeA,
transposeB,
bias,
activation,
preluActivationWeights,
}),
convInfo.outShape
);
}
// Following optimization is specific to packed |x| with odd row count
// (For example, in channelLast mode, 'row count' refers to x.shape[2]):
// we avoid expensive packed 2x2 reshape by padding row count to next,
// even number. When x.shape[2] is odd, the result of packed batchMatMul is
// the same (has the same texture layout and and values in the texture) as
// it is for even x.shape[2] + 1. We make the odd-rows tensor to look like
// even-rows tensor before the operation and, after the batchMatMul,
// fix the even-rows result to have odd number of rows.
const targetShape = isChannelsLast
? xShape[0] * xShape[1] * (xShape[2] + 1)
: xShape[0] * xShape[2] * (xShape[3] + 1);
const xReshaped = {
dataId: x.dataId,
shape: [1, targetShape, convInfo.inChannels],
dtype: x.dtype,
};
// xTexData.shape gets referenced from GPGPUBinary.inShapeInfos.
// Decrementing row count, after batchMatMul->...->compileProgram leads to
// invalid row count within the reference in GPGPUBinary.inShapeInfos.
// Alternative fix would be to provide a copy to GPGPUBinary.inShapeInfos
// in compileProgram method, but that would affect compilation of all
// programs - instead, provide a copy here, with even row count, before
// calling batchMatMul->...->compileProgram and after that, the original
// xTexData.shape is restored.
const originalXTexDataShape = xTexData.shape;
xTexData.shape = xTexData.shape.slice();
xTexData.shape[xTexData.shape.length - 2]++;
dist["util"].assert(
isReshapeFree(xTexData.shape, xReshaped.shape),
() => `packed reshape ${xTexData.shape} to ${xReshaped.shape} isn't free`
);
const filterReshaped = this.reshape(filter, [
1,
convInfo.inChannels,
convInfo.outChannels,
]);
const pointwiseConv = this.fusedBatchMatMul({
a: xReshaped,
b: filterReshaped,
transposeA,
transposeB,
bias,
activation,
preluActivationWeights,
});
const pointwiseConvTexData = this.texData.get(pointwiseConv.dataId);
dist["util"].assert(
pointwiseConvTexData.isPacked,
() => "batchMatMul result is expected to be packed"
);
// Restore the input shape to original.
xTexData.shape = originalXTexDataShape;
// Set the output shape - there is no need for expensive reshape as data
// layout is already correct.
pointwiseConvTexData.shape = convInfo.outShape;
return Object(dist["engine"])().makeTensorFromDataId(
pointwiseConv.dataId,
convInfo.outShape,
pointwiseConv.dtype
);
}
conv2dWithIm2Row(x, filter, convInfo, bias, activation, preluActivationWeights) {
// Rearranges conv2d input so each block to be convolved over forms the
// column of a new matrix with shape [filterWidth * filterHeight *
// inChannels, outHeight * outWidth]. The filter is also rearranged so each
// output channel forms a row of a new matrix with shape [outChannels,
// filterWidth * filterHeight * inChannels]. The convolution is then
// computed by multiplying these matrices and reshaping the result.
const { filterWidth, filterHeight, inChannels, outWidth, outHeight, dataFormat } =
convInfo;
const isChannelsLast = dataFormat === "channelsLast";
const sharedDim = filterWidth * filterHeight * inChannels;
const numCols = outHeight * outWidth;
const x2ColShape = [sharedDim, numCols];
const transposeA = true;
const transposeB = false;
const xSqueezed = x.squeeze([0]);
const w2Row = filter.reshape([1, sharedDim, -1]);
const im2ColProgram = new im2col_packed_gpu_Im2ColPackedProgram(
x2ColShape,
xSqueezed.shape,
convInfo
);
const im2Col = this.compileAndRun(im2ColProgram, [xSqueezed]).reshape([
1,
x2ColShape[0],
x2ColShape[1],
]);
const hasBias = bias != null;
const hasPreluActivationWeights = preluActivationWeights != null;
const fusedActivation = activation
? mapActivationToShaderProgram(activation, true)
: null;
const matmulProgram = new MatMulPackedProgram(
im2Col.shape,
[1, numCols, convInfo.outChannels],
transposeA,
transposeB,
hasBias,
fusedActivation,
hasPreluActivationWeights
);
const inputs = [im2Col, w2Row];
if (bias) {
inputs.push(bias);
}
if (hasPreluActivationWeights) {
inputs.push(preluActivationWeights);
}
const product = this.compileAndRun(matmulProgram, inputs);
if (isChannelsLast) {
return product.reshape([1, outHeight, outWidth, convInfo.outChannels]);
} else {
return product.reshape([1, convInfo.outChannels, outHeight, outWidth]);
}
}
fusedConv2d({ input, filter, convInfo, bias, activation, preluActivationWeights }) {
if (
convInfo.filterHeight === 1 &&
convInfo.filterWidth === 1 &&
convInfo.dilationHeight === 1 &&
convInfo.dilationWidth === 1 &&
convInfo.strideHeight === 1 &&
convInfo.strideWidth === 1 &&
(convInfo.padInfo.type === "SAME" || convInfo.padInfo.type === "VALID")
) {
return this.conv2dByMatMul(
input,
filter,
convInfo,
bias,
activation,
preluActivationWeights
);
}
if (Object(dist["env"])().getBool("WEBGL_CONV_IM2COL") && input.shape[0] === 1) {
return this.conv2dWithIm2Row(
input,
filter,
convInfo,
bias,
activation,
preluActivationWeights
);
}
const hasBias = bias != null;
const hasPreluActivationWeights = preluActivationWeights != null;
const fusedActivation = activation
? mapActivationToShaderProgram(activation, false)
: null;
const program = new Conv2DProgram(
convInfo,
hasBias,
fusedActivation,
hasPreluActivationWeights
);
const inputs = [input, filter];
if (bias) {
inputs.push(bias);
}
if (preluActivationWeights) {
inputs.push(preluActivationWeights);
}
return this.compileAndRun(program, inputs);
}
conv2d(x, filter, convInfo) {
if (
convInfo.filterHeight === 1 &&
convInfo.filterWidth === 1 &&
convInfo.dilationHeight === 1 &&
convInfo.dilationWidth === 1 &&
convInfo.strideHeight === 1 &&
convInfo.strideWidth === 1 &&
(convInfo.padInfo.type === "SAME" || convInfo.padInfo.type === "VALID")
) {
return this.conv2dByMatMul(x, filter, convInfo);
}
if (Object(dist["env"])().getBool("WEBGL_CONV_IM2COL") && x.shape[0] === 1) {
return this.conv2dWithIm2Row(x, filter, convInfo);
}
const program = new Conv2DProgram(convInfo);
return this.compileAndRun(program, [x, filter]);
}
conv2dDerInput(dy, filter, convInfo) {
const program = new Conv2DDerInputProgram(convInfo);
return this.compileAndRun(program, [dy, filter]);
}
conv2dDerFilter(x, dy, convInfo) {
const program = new Conv2DDerFilterProgram(convInfo);
return this.compileAndRun(program, [x, dy]);
}
fusedDepthwiseConv2D({
input,
filter,
convInfo,
bias,
activation,
preluActivationWeights,
}) {
const shouldPackDepthwiseConv =
Object(dist["env"])().getBool("WEBGL_PACK_DEPTHWISECONV") &&
convInfo.strideWidth <= 2 &&
convInfo.outChannels / convInfo.inChannels === 1;
const fusedActivation = activation
? mapActivationToShaderProgram(activation, shouldPackDepthwiseConv)
: null;
const inputs = [input, filter];
const hasBias = bias != null;
const hasPreluActivationWeights = preluActivationWeights != null;
if (hasBias) {
inputs.push(bias);
}
if (hasPreluActivationWeights) {
inputs.push(preluActivationWeights);
}
let program;
if (shouldPackDepthwiseConv) {
program = new conv_packed_gpu_depthwise_DepthwiseConvPacked2DProgram(
convInfo,
hasBias,
fusedActivation,
hasPreluActivationWeights
);
return this.compileAndRun(program, inputs);
}
program = new DepthwiseConv2DProgram(
convInfo,
hasBias,
fusedActivation,
hasPreluActivationWeights
);
return this.compileAndRun(program, inputs);
}
depthwiseConv2D(x, filter, convInfo) {
let program;
if (
Object(dist["env"])().getBool("WEBGL_PACK_DEPTHWISECONV") &&
convInfo.strideWidth <= 2 &&
convInfo.outChannels / convInfo.inChannels === 1
) {
program = new conv_packed_gpu_depthwise_DepthwiseConvPacked2DProgram(convInfo);
return this.compileAndRun(program, [x, filter]);
}
program = new DepthwiseConv2DProgram(convInfo);
return this.compileAndRun(program, [x, filter]);
}
depthwiseConv2DDerInput(dy, filter, convInfo) {
const program = new DepthwiseConv2DDerInputProgram(convInfo);
return this.compileAndRun(program, [dy, filter]);
}
depthwiseConv2DDerFilter(x, dy, convInfo) {
const program = new DepthwiseConv2DDerFilterProgram(convInfo);
return this.compileAndRun(program, [x, dy]);
}
conv3d(x, filter, convInfo) {
const program = new Conv3DProgram(convInfo);
return this.compileAndRun(program, [x, filter]);
}
conv3dDerInput(dy, filter, convInfo) {
const program = new Conv3DDerInputProgram(convInfo);
return this.compileAndRun(program, [dy, filter]);
}
conv3dDerFilter(x, dy, convInfo) {
const program = new Conv3DDerFilterProgram(convInfo);
return this.compileAndRun(program, [x, dy]);
}
maxPool(x, convInfo) {
const program = new Pool2DProgram(convInfo, "max", false);
return this.compileAndRun(program, [x]);
}
avgPool(x, convInfo) {
const program = new Pool2DProgram(convInfo, "avg", false);
return this.compileAndRun(program, [x], "float32");
}
maxPoolBackprop(dy, x, y, convInfo) {
const getPositions = true;
const maxPoolPositionsProgram = new Pool2DProgram(convInfo, "max", getPositions);
const maxPoolPositions = this.compileAndRun(maxPoolPositionsProgram, [x]);
const maxPoolBackPropProgram = new MaxPool2DBackpropProgram(convInfo);
const result = this.compileAndRun(
maxPoolBackPropProgram,
[dy, maxPoolPositions],
x.dtype
);
maxPoolPositions.dispose();
return result;
}
avgPoolBackprop(dy, x, convInfo) {
const avgPoolBackpropProgram = new AvgPool2DBackpropProgram(convInfo);
return this.compileAndRun(avgPoolBackpropProgram, [dy], x.dtype);
}
cast(x, dtype) {
return dist["backend_util"].castTensor(x, dtype, this);
}
unstack(x, axis) {
const num = x.shape[axis];
const outShape = new Array(x.rank - 1);
let outIndex = 0;
for (let i = 0; i < x.rank; i++) {
if (i !== axis) {
outShape[outIndex++] = x.shape[i];
}
}
const begin = new Array(x.rank).fill(0);
const size = x.shape.slice();
size[axis] = 1;
const res = new Array(num);
for (let i = 0; i < res.length; i++) {
begin[axis] = i;
res[i] = this.slice(x, begin, size).reshape(outShape);
}
return res;
}
avgPool3d(x, convInfo) {
const program = new Pool3DProgram(convInfo, "avg", false);
return this.compileAndRun(program, [x], "float32");
}
avgPool3dBackprop(dy, x, convInfo) {
const avgPool3dBackpropProgram = new AvgPool3DBackpropProgram(convInfo);
return this.compileAndRun(avgPool3dBackpropProgram, [dy], x.dtype);
}
maxPool3d(x, convInfo) {
const program = new Pool3DProgram(convInfo, "max", false);
return this.compileAndRun(program, [x], "float32");
}
maxPool3dBackprop(dy, x, y, convInfo) {
const getPositions = true;
const maxPool3dPositionsProgram = new Pool3DProgram(convInfo, "max", getPositions);
const maxPool3dPositions = this.compileAndRun(maxPool3dPositionsProgram, [x]);
const maxPool3dBackPropProgram = new MaxPool3DBackpropProgram(convInfo);
const result = this.compileAndRun(
maxPool3dBackPropProgram,
[dy, maxPool3dPositions],
x.dtype
);
maxPool3dPositions.dispose();
return result;
}
reshape(x, shape) {
const texData = this.texData.get(x.dataId);
if (
texData.isPacked &&
!isReshapeFree(x.shape, shape) &&
!(texData.texture !== null && isReshapeFree(texData.shape, shape))
) {
const info = this.packedReshape(x, shape);
return Object(dist["engine"])().makeTensorFromDataId(
info.dataId,
info.shape,
info.dtype
);
}
return dist["backend_util"].reshapeTensor(x, shape);
}
resizeBilinear(x, newHeight, newWidth, alignCorners) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_IMAGE_OPERATIONS")
? new ResizeBilinearPackedProgram(x.shape, newHeight, newWidth, alignCorners)
: new ResizeBilinearProgram(x.shape, newHeight, newWidth, alignCorners);
return this.compileAndRun(program, [x], "float32");
}
resizeBilinearBackprop(dy, x, alignCorners) {
const program = new ResizeBilinearBackpropProgram(dy, x, alignCorners);
return this.compileAndRun(program, [dy]);
}
resizeNearestNeighbor(x, newHeight, newWidth, alignCorners) {
const program = new ResizeNearestNeighborProgram(
x.shape,
newHeight,
newWidth,
alignCorners
);
return this.compileAndRun(program, [x]);
}
resizeNearestNeighborBackprop(dy, x, alignCorners) {
const program = new ResizeNearestNeigborBackpropProgram(dy, x, alignCorners);
return this.compileAndRun(program, [dy]);
}
multinomial(logits, normalized, numSamples, seed) {
const probs = normalized ? logits : Object(dist["softmax"])(logits);
const batchSize = probs.shape[0];
const numOutcomes = probs.shape[1];
const program = new MultinomialProgram(batchSize, numOutcomes, numSamples);
const customSetup = program.getCustomSetupFunc(seed);
return this.compileAndRun(program, [probs], "int32", customSetup);
}
oneHot(indices, depth, onValue, offValue) {
const program = new OneHotProgram(indices.size, depth, onValue, offValue);
return this.compileAndRun(program, [indices]);
}
diag(x) {
const program = new DiagProgram(x.size);
return this.compileAndRun(program, [x]);
}
cropAndResize(image, boxes, boxIndex, cropSize, method, extrapolationValue) {
const program = new CropAndResizeProgram(
image.shape,
boxes.shape,
cropSize,
method,
extrapolationValue
);
return this.compileAndRun(program, [image, boxes, boxIndex], "float32");
}
depthToSpace(x, blockSize, dataFormat) {
dist["util"].assert(
blockSize > 1,
() => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`
);
const batchSize = x.shape[0];
const inputHeight = dataFormat === "NHWC" ? x.shape[1] : x.shape[2];
const inputWidth = dataFormat === "NHWC" ? x.shape[2] : x.shape[3];
const inputDepth = dataFormat === "NHWC" ? x.shape[3] : x.shape[1];
const outputHeight = inputHeight * blockSize;
const outputWidth = inputWidth * blockSize;
const outputDepth = inputDepth / (blockSize * blockSize);
const outputShape =
dataFormat === "NHWC"
? [batchSize, outputHeight, outputWidth, outputDepth]
: [batchSize, outputDepth, outputHeight, outputWidth];
const program = new DepthToSpaceProgram(outputShape, blockSize, dataFormat);
return this.compileAndRun(program, [x]);
}
split(x, sizeSplits, axis) {
return split(x, sizeSplits, axis);
}
scatterND(indices, updates, shape) {
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = dist[
"backend_util"
].calculateShapes(updates, indices, shape);
const flattenShape = [outputSize / sliceSize, sliceSize];
const flattenIndices = indices.reshape([numUpdates, sliceRank]);
const flattenX = updates.reshape([numUpdates, sliceSize]);
if (outputSize === 0) {
return dist["backend_util"].reshapeTensor(Object(dist["tensor"])([]), shape);
}
const defaultValue = Object(dist["scalar"])(0);
const program = new scatter_gpu_ScatterProgram(
numUpdates,
sliceRank,
flattenIndices.rank,
flattenX.rank,
strides,
flattenShape
);
const res = this.compileAndRun(program, [flattenX, flattenIndices, defaultValue]);
return res.reshape(shape);
}
sparseToDense(sparseIndices, sparseValues, outputShape, defaultValue) {
const { sliceRank, numUpdates, strides, outputSize } = dist[
"backend_util"
].calculateShapes(sparseValues, sparseIndices, outputShape);
const sumDupeIndices = false;
const program = new scatter_gpu_ScatterProgram(
numUpdates,
sliceRank,
sparseIndices.rank,
sparseValues.rank,
strides,
[outputSize, 1],
sumDupeIndices
);
const res = this.compileAndRun(program, [sparseValues, sparseIndices, defaultValue]);
return res.reshape(outputShape);
}
fft(x) {
const inverse = false;
return this.fftImpl(x, inverse);
}
ifft(x) {
const inverse = true;
return this.fftImpl(x, inverse);
}
fftImpl(x, inverse) {
const xData = this.texData.get(x.dataId);
const realProgram = new FFTProgram(COMPLEX_FFT.REAL, x.shape, inverse);
const imagProgram = new FFTProgram(COMPLEX_FFT.IMAG, x.shape, inverse);
const inputs = [
this.makeComplexComponentTensorInfo(x, xData.complexTensors.real),
this.makeComplexComponentTensorInfo(x, xData.complexTensors.imag),
];
const real = this.compileAndRun(realProgram, inputs);
const imag = this.compileAndRun(imagProgram, inputs);
const complex = this.complex(real, imag).as2D(x.shape[0], x.shape[1]);
real.dispose();
imag.dispose();
return complex;
}
gatherND(x, indices) {
const indicesShape = indices.shape;
const sliceRank = indicesShape[indicesShape.length - 1];
const [resultShape, numSlices, sliceSize, strides] = dist[
"backend_util"
].prepareAndValidate(x, indices);
const flattenIndices = indices.reshape([numSlices, sliceRank]);
const flattenX = x.reshape([x.size / sliceSize, sliceSize]);
const program = new gather_nd_gpu_GatherNDProgram(sliceRank, strides, [
numSlices,
sliceSize,
]);
const res = this.compileAndRun(program, [flattenX, flattenIndices]);
return res.reshape(resultShape);
}
fill(shape, value, dtype) {
dtype = dtype || dist["util"].inferDtype(value);
if (dtype === "string") {
// String type should be handled in CPU memory.
const values = dist["util"].getArrayFromDType(dtype, dist["util"].sizeFromShape(shape));
values.fill(value);
return Object(dist["engine"])().makeTensor(values, shape, dtype, this);
} else {
const program = new FillProgram(shape, value);
const customSetup = program.getCustomSetupFunc(value);
return this.compileAndRun(program, [], dtype, customSetup);
}
}
onesLike(x) {
if (x.dtype === "string") {
throw new Error("onesLike is not supported under string dtype");
} else {
// TODO(cais, smilkov): Add WebGL shader for onesLike:
// https://github.com/tensorflow/tfjs/issues/1293
return this.fill(x.shape, 1, x.dtype);
}
}
zerosLike(x) {
return this.fill(x.shape, x.dtype === "string" ? "" : 0, x.dtype);
}
linspace(start, stop, num) {
// TODO: Use CPU implementation due to the precision problem in Safari.
return dist["backend_util"].linspaceImpl(start, stop, num);
}
makeTensorInfo(shape, dtype) {
const dataId = this.write(null /* values */, shape, dtype);
this.texData.get(dataId).usage = null;
return { dataId, shape, dtype };
}
makeOutput(shape, dtype) {
const { dataId } = this.makeTensorInfo(shape, dtype);
return Object(dist["engine"])().makeTensorFromDataId(dataId, shape, dtype, this);
}
unpackTensor(input) {
const program = new unpack_gpu_UnpackProgram(input.shape);
return this.runWebGLProgram(program, [input], input.dtype);
}
packTensor(input) {
const program = new pack_gpu_PackProgram(input.shape);
const preventEagerUnpackingOutput = true;
return this.runWebGLProgram(
program,
[input],
input.dtype,
null /* customSetup */,
preventEagerUnpackingOutput
);
}
packedReshape(input, afterShape) {
const input3DShape = [getBatchDim(input.shape), ...getRowsCols(input.shape)];
const input3D = {
dtype: input.dtype,
shape: input3DShape,
dataId: input.dataId,
};
const afterShapeAs3D = [getBatchDim(afterShape), ...getRowsCols(afterShape)];
const program = new reshape_packed_gpu_ReshapePackedProgram(afterShapeAs3D, input3DShape);
const preventEagerUnpackingOfOutput = true;
const output = this.runWebGLProgram(
program,
[input3D],
input.dtype,
null /* customSetup */,
preventEagerUnpackingOfOutput
);
return { dataId: output.dataId, shape: afterShape, dtype: output.dtype };
}
decode(dataId) {
const texData = this.texData.get(dataId);
const { isPacked, shape, dtype } = texData;
const shapeAs3D = getShapeAs3D(shape);
let program;
if (isPacked) {
program = new decode_matrix_packed_gpu_DecodeMatrixPackedProgram(shapeAs3D);
} else {
program = new decode_matrix_gpu_DecodeMatrixProgram(shapeAs3D);
}
const preventEagerUnpackingOfOutput = true;
const out = this.runWebGLProgram(
program,
[{ shape: shapeAs3D, dtype, dataId }],
dtype,
null /* customSetup */,
preventEagerUnpackingOfOutput
);
return { dtype, shape, dataId: out.dataId };
}
runWebGLProgram(
program,
inputs,
outputDtype,
customSetup,
preventEagerUnpackingOfOutput = false
) {
const output = this.makeTensorInfo(program.outputShape, outputDtype);
const outData = this.texData.get(output.dataId);
if (program.packedOutput) {
outData.isPacked = true;
}
if (program.outPackingScheme === PackingScheme.DENSE) {
const texelShape = getDenseTexShape(program.outputShape);
// For a densely packed output, we explicitly set texShape
// so it doesn't get assigned later according to our typical packing
// scheme wherein a single texel can only contain values from adjacent
// rows/cols.
outData.texShape = texelShape.map((d) => d * 2);
}
if (program.outTexUsage != null) {
outData.usage = program.outTexUsage;
}
if (dist["util"].sizeFromShape(output.shape) === 0) {
// Short-circuit the computation since the result is empty (has 0 in its
// shape).
outData.values = dist["util"].getTypedArrayFromDType(output.dtype, 0);
return output;
}
const dataToDispose = [];
const inputsData = inputs.map((input) => {
if (input.dtype === "complex64") {
throw new Error(
`GPGPUProgram does not support complex64 input. For complex64 ` +
`dtypes, please separate the program into real and imaginary ` +
`parts.`
);
}
let texData = this.texData.get(input.dataId);
if (texData.texture == null) {
if (
!program.packedInputs &&
dist["util"].sizeFromShape(input.shape) <=
Object(dist["env"])().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM")
) {
// Upload small tensors that live on the CPU as uniforms, not as
// textures. Do this only when the environment supports 32bit floats
// due to problems when comparing 16bit floats with 32bit floats.
// TODO(https://github.com/tensorflow/tfjs/issues/821): Make it
// possible for packed shaders to sample from uniforms.
return {
shape: input.shape,
texData: null,
isUniform: true,
uniformValues: texData.values,
};
}
// This ensures that if a packed program's inputs have not yet been
// uploaded to the GPU, they get uploaded as packed right off the bat.
if (program.packedInputs) {
texData.isPacked = true;
texData.shape = input.shape;
}
} else if (!!texData.isPacked !== !!program.packedInputs) {
input = texData.isPacked ? this.unpackTensor(input) : this.packTensor(input);
dataToDispose.push(input);
texData = this.texData.get(input.dataId);
} else if (texData.isPacked && !isReshapeFree(texData.shape, input.shape)) {
// This is a special case where a texture exists for a tensor
// but the shapes are incompatible (due to packing constraints) because
// the tensor did not have a chance to go through the packed reshape
// shader. This only happens when we reshape the *same* tensor to form
// *distinct* inputs to an op, e.g. dotting a vector with itself. This
// case will disappear once packed uploading is the default.
const savedInput = input;
const targetShape = input.shape;
input.shape = texData.shape;
input = this.packedReshape(input, targetShape);
dataToDispose.push(input);
texData = this.texData.get(input.dataId);
savedInput.shape = targetShape;
}
this.uploadToGPU(input.dataId);
return { shape: input.shape, texData, isUniform: false };
});
this.uploadToGPU(output.dataId);
const outputData = { shape: output.shape, texData: outData, isUniform: false };
const key = makeShaderKey(program, inputsData, outputData);
const binary = this.getAndSaveBinary(key, () => {
return compileProgram(this.gpgpu, program, inputsData, outputData);
});
const shouldTimeProgram = this.activeTimers != null;
let query;
if (shouldTimeProgram) {
query = this.startTimer();
}
runProgram(this.gpgpu, binary, inputsData, outputData, customSetup);
dataToDispose.forEach((info) => this.disposeData(info.dataId));
if (shouldTimeProgram) {
query = this.endTimer(query);
this.activeTimers.push({
name: program.constructor.name,
query: this.getQueryTime(query),
});
}
if (
!Object(dist["env"])().getBool("WEBGL_LAZILY_UNPACK") &&
outData.isPacked &&
preventEagerUnpackingOfOutput === false
) {
const unpacked = this.unpackTensor(output);
this.disposeData(output.dataId);
return unpacked;
}
return output;
}
compileAndRun(
program,
inputs,
outputDtype,
customSetup,
preventEagerUnpackingOfOutput = false
) {
outputDtype = outputDtype || inputs[0].dtype;
const outInfo = this.runWebGLProgram(
program,
inputs,
outputDtype,
customSetup,
preventEagerUnpackingOfOutput
);
return Object(dist["engine"])().makeTensorFromDataId(
outInfo.dataId,
outInfo.shape,
outInfo.dtype
);
}
getAndSaveBinary(key, getBinary) {
if (!(key in this.binaryCache)) {
this.binaryCache[key] = getBinary();
}
return this.binaryCache[key];
}
getTextureManager() {
return this.textureManager;
}
dispose() {
if (this.disposed) {
return;
}
// Avoid disposing the compiled webgl programs during unit testing because
// it slows down test execution.
if (!Object(dist["env"])().getBool("IS_TEST")) {
const allKeys = Object.keys(this.binaryCache);
allKeys.forEach((key) => {
this.gpgpu.deleteProgram(this.binaryCache[key].webGLProgram);
delete this.binaryCache[key];
});
}
this.textureManager.dispose();
if (
this.canvas != null &&
typeof HTMLCanvasElement !== "undefined" &&
this.canvas instanceof HTMLCanvasElement
) {
this.canvas.remove();
} else {
this.canvas = null;
}
if (this.gpgpuCreatedLocally) {
this.gpgpu.program = null;
this.gpgpu.dispose();
}
this.disposed = true;
}
floatPrecision() {
if (this.floatPrecisionValue == null) {
this.floatPrecisionValue = Object(dist["tidy"])(() => {
if (!Object(dist["env"])().get("WEBGL_RENDER_FLOAT32_ENABLED")) {
// Momentarily switching DEBUG flag to false so we don't throw an
// error trying to upload a small value.
const debugFlag = Object(dist["env"])().getBool("DEBUG");
Object(dist["env"])().set("DEBUG", false);
const underflowCheckValue = this.abs(Object(dist["scalar"])(1e-8)).dataSync()[0];
Object(dist["env"])().set("DEBUG", debugFlag);
if (underflowCheckValue > 0) {
return 32;
}
}
return 16;
});
}
return this.floatPrecisionValue;
}
/** Returns the smallest representable number. */
epsilon() {
return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
}
uploadToGPU(dataId) {
const texData = this.texData.get(dataId);
const { shape, dtype, values, texture, usage, isPacked } = texData;
if (texture != null) {
// Array is already on GPU. No-op.
return;
}
const shouldTimeProgram = this.activeTimers != null;
let start;
if (shouldTimeProgram) {
start = dist["util"].now();
}
let texShape = texData.texShape;
if (texShape == null) {
texShape = getTextureShapeFromLogicalShape(shape, isPacked);
texData.texShape = texShape;
}
if (values != null) {
const shapeAs3D = getShapeAs3D(shape);
let program;
let width = texShape[1],
height = texShape[0];
const isByteArray = values instanceof Uint8Array;
if (isPacked) {
[width, height] = getPackedMatrixTextureShapeWidthHeight(texShape[0], texShape[1]);
program = new encode_matrix_packed_gpu_EncodeMatrixPackedProgram(
shapeAs3D,
[height, width],
isByteArray
);
} else {
program = new encode_matrix_gpu_EncodeMatrixProgram(
shapeAs3D,
[height, width],
isByteArray
);
}
const tempDenseInputHandle = this.makeTensorInfo([height, width], dtype);
if (isByteArray) {
this.texData.get(tempDenseInputHandle.dataId).usage = TextureUsage.PIXELS;
} else {
this.texData.get(tempDenseInputHandle.dataId).usage = TextureUsage.UPLOAD;
}
this.gpgpu.uploadDenseMatrixToTexture(
this.getTexture(tempDenseInputHandle.dataId),
width,
height,
values
);
// We want the output to remain packed regardless of the value of
// WEBGL_PACK.
const preventEagerUnpacking = true;
const encodedOutputTarget = this.runWebGLProgram(
program,
[tempDenseInputHandle],
dtype,
null,
preventEagerUnpacking
);
// Have the original texture assume the identity of the encoded output.
const outputTexData = this.texData.get(encodedOutputTarget.dataId);
texData.texture = outputTexData.texture;
texData.texShape = outputTexData.texShape;
texData.isPacked = outputTexData.isPacked;
texData.usage = outputTexData.usage;
this.disposeData(tempDenseInputHandle.dataId);
this.texData.delete(encodedOutputTarget.dataId);
// Once uploaded, don't store the values on cpu.
texData.values = null;
if (shouldTimeProgram) {
this.uploadWaitMs += dist["util"].now() - start;
}
} else {
const newTexture = this.acquireTexture(texShape, usage, dtype, isPacked);
texData.texture = newTexture;
}
}
convertAndCacheOnCPU(dataId, float32Values) {
const texData = this.texData.get(dataId);
const { dtype } = texData;
this.releaseGPUData(dataId);
if (float32Values != null) {
texData.values = float32ToTypedArray(float32Values, dtype);
}
return texData.values;
}
acquireTexture(texShape, texType, dtype, isPacked) {
this.numBytesInGPU += this.computeBytes(texShape, dtype);
if (
!this.warnedAboutMemory &&
this.numBytesInGPU > this.numMBBeforeWarning * 1024 * 1024
) {
const mb = (this.numBytesInGPU / 1024 / 1024).toFixed(2);
this.warnedAboutMemory = true;
console.warn(
`High memory usage in GPU: ${mb} MB, ` + `most likely due to a memory leak`
);
}
return this.textureManager.acquireTexture(texShape, texType, isPacked);
}
computeBytes(shape, dtype) {
return shape[0] * shape[1] * dist["util"].bytesPerElement(dtype);
}
}
function float32ToTypedArray(a, dtype) {
if (dtype === "float32" || dtype === "complex64") {
return a;
} else if (dtype === "int32" || dtype === "bool") {
const result = dtype === "int32" ? new Int32Array(a.length) : new Uint8Array(a.length);
for (let i = 0; i < result.length; ++i) {
result[i] = Math.round(a[i]);
}
return result;
} else {
throw new Error(`Unknown dtype ${dtype}`);
}
}
//# sourceMappingURL=backend_webgl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/version.js
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
const version_version = "2.0.1";
//# sourceMappingURL=version.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/Div_impl.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function divImpl(a, b, backend) {
let program = new binaryop_gpu_BinaryOpProgram(DIV, a.shape, b.shape);
if (Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")) {
program = new binaryop_packed_gpu_BinaryOpPackedProgram(
binaryop_packed_gpu_DIV,
a.shape,
b.shape,
true
);
}
const output = backend.runWebGLProgram(program, [a, b], "float32");
return output;
}
//# sourceMappingURL=Div_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/Div.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const divConfig = {
kernelName: dist["Div"],
backendName: "webgl",
kernelFunc: ({ inputs, backend }) => {
const { a, b } = inputs;
const webglBackend = backend;
return divImpl(a, b, webglBackend);
},
};
//# sourceMappingURL=Div.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/FromPixels_utils/from_pixels_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class from_pixels_gpu_FromPixelsProgram {
constructor(outputShape) {
this.variableNames = ["A"];
const glsl = getGlslDifferences();
const [height, width] = outputShape;
this.outputShape = outputShape;
this.userCode = `
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${width}.0, ${height}.0);
vec4 values = ${glsl.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`;
}
}
//# sourceMappingURL=from_pixels_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/FromPixels_utils/from_pixels_packed_gpu.js
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class from_pixels_packed_gpu_FromPixelsPackedProgram {
constructor(outputShape) {
this.variableNames = ["A"];
this.packedInputs = false;
this.packedOutput = true;
const glsl = getGlslDifferences();
const [height, width] = outputShape;
this.outputShape = outputShape;
this.userCode = `
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${width}.0, ${height}.0);
vec4 values = ${glsl.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${glsl.output} = result;
}
`;
}
}
//# sourceMappingURL=from_pixels_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/FromPixels.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.
* =============================================================================
*/
const fromPixelsConfig = {
kernelName: dist["FromPixels"],
backendName: "webgl",
kernelFunc: fromPixels,
};
let fromPixels2DContext;
function fromPixels(args) {
const { inputs, backend, attrs } = args;
let { pixels } = inputs;
const { numChannels } = attrs;
const isVideo =
typeof HTMLVideoElement !== "undefined" && pixels instanceof HTMLVideoElement;
const isImage =
typeof HTMLImageElement !== "undefined" && pixels instanceof HTMLImageElement;
const [width, height] = isVideo
? [pixels.videoWidth, pixels.videoHeight]
: [pixels.width, pixels.height];
const texShape = [height, width];
const outShape = [height, width, numChannels];
if (isImage || isVideo) {
if (fromPixels2DContext == null) {
fromPixels2DContext = document.createElement("canvas").getContext("2d");
}
fromPixels2DContext.canvas.width = width;
fromPixels2DContext.canvas.height = height;
fromPixels2DContext.drawImage(pixels, 0, 0, width, height);
pixels = fromPixels2DContext.canvas;
}
const tempPixelHandle = backend.makeTensorInfo(texShape, "int32");
// This is a byte texture with pixels.
backend.texData.get(tempPixelHandle.dataId).usage = TextureUsage.PIXELS;
backend.gpgpu.uploadPixelDataToTexture(backend.getTexture(tempPixelHandle.dataId), pixels);
const program = Object(dist["env"])().getBool("WEBGL_PACK")
? new from_pixels_packed_gpu_FromPixelsPackedProgram(outShape)
: new from_pixels_gpu_FromPixelsProgram(outShape);
const res = backend.runWebGLProgram(program, [tempPixelHandle], "int32");
backend.disposeData(tempPixelHandle.dataId);
return res;
}
//# sourceMappingURL=FromPixels.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/base.js + 3 modules
var base = __webpack_require__(31);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernel_utils/shared.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Import shared functionality from tfjs-backend-cpu without triggering
// side effects.
// tslint:disable-next-line: no-imports-from-dist
const { maxImpl: maxImplCPU, transposeImpl: transposeImplCPU } = base["b" /* shared */];
//# sourceMappingURL=shared.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernel_utils/reduce.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function reduce(x, dtype, reductionType, backend) {
const [batchSize, inSize] = x.shape;
const windowSize = dist["backend_util"].computeOptimalWindowSize(inSize);
const reduceInfo = { windowSize, inSize, batchSize };
const program = new ReduceProgram(reduceInfo, reductionType);
const output = backend.runWebGLProgram(program, [x], dtype);
if (output.shape[1] === 1) {
return output;
}
return reduce(output, dtype, reductionType, backend);
}
//# sourceMappingURL=reduce.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernel_utils/reshape.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function packedReshape(input, afterShape, backend) {
const input3DShape = [getBatchDim(input.shape), ...getRowsCols(input.shape)];
const input3D = {
dtype: input.dtype,
shape: input3DShape,
dataId: input.dataId,
};
const afterShapeAs3D = [getBatchDim(afterShape), ...getRowsCols(afterShape)];
const program = new reshape_packed_gpu_ReshapePackedProgram(afterShapeAs3D, input3DShape);
const preventEagerUnpackingOfOutput = true;
const output = backend.runWebGLProgram(
program,
[input3D],
input.dtype,
null /* customSetup */,
preventEagerUnpackingOfOutput
);
return { dataId: output.dataId, shape: afterShape, dtype: output.dtype };
}
function reshape(x, afterShape, backend) {
const xTexData = backend.texData.get(x.dataId);
if (
xTexData.isPacked &&
!isReshapeFree(x.shape, afterShape) &&
!(xTexData.texture !== null && isReshapeFree(xTexData.shape, afterShape))
) {
return packedReshape(x, afterShape, backend);
}
return { dataId: x.dataId, shape: afterShape, dtype: x.dtype };
}
//# sourceMappingURL=reshape.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/Max_impl.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function maxImpl(x, reduceShape, outShape, backend) {
const inSize = dist["util"].sizeFromShape(reduceShape);
const xSize = dist["util"].sizeFromShape(x.shape);
const batchSize = xSize / inSize;
const reshapedInput = reshape(x, [batchSize, inSize], backend);
const reduced = reduce(reshapedInput, x.dtype, "max", backend);
if (reshapedInput.dataId !== x.dataId) {
// dispose the output of the packed reshape.
backend.disposeData(reshapedInput.dataId);
}
return reshape(reduced, outShape, backend);
}
//# sourceMappingURL=Max_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/transpose_gpu.js
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class transpose_gpu_TransposeProgram {
constructor(aShape, newDim) {
this.variableNames = ["A"];
const outputShape = new Array(aShape.length);
for (let i = 0; i < outputShape.length; i++) {
outputShape[i] = aShape[newDim[i]];
}
this.outputShape = outputShape;
this.rank = outputShape.length;
const dtype = getCoordsDataType(this.rank);
const switched = getSwitchedCoords(newDim);
this.userCode = `
void main() {
${dtype} resRC = getOutputCoords();
setOutput(getA(${switched}));
}
`;
}
}
function getSwitchedCoords(newDim) {
const rank = newDim.length;
if (rank > 6) {
throw Error(`Transpose for rank ${rank} is not yet supported`);
}
const originalOrder = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u", "resRC.v"];
const switchedCoords = new Array(rank);
for (let i = 0; i < newDim.length; i++) {
switchedCoords[newDim[i]] = originalOrder[i];
}
return switchedCoords.join();
}
//# sourceMappingURL=transpose_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/transpose_packed_gpu.js
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class transpose_packed_gpu_TransposePackedProgram {
constructor(aShape, newDim) {
this.variableNames = ["A"];
this.packedInputs = true;
this.packedOutput = true;
const outputShape = new Array(aShape.length);
for (let i = 0; i < outputShape.length; i++) {
outputShape[i] = aShape[newDim[i]];
}
this.outputShape = outputShape;
this.rank = outputShape.length;
if (this.rank > 6) {
throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);
}
const dtype = getCoordsDataType(this.rank);
const outputOrder = getVecChannels("rc", this.rank);
const switchedOrder = new Array(this.rank);
for (let i = 0; i < newDim.length; i++) {
switchedOrder[newDim[i]] = outputOrder[i];
}
const innerDims = `vec2(${switchedOrder.slice(-2).join()})`;
const nextColumn = `++${outputOrder[this.rank - 1]} < ${outputShape[this.rank - 1]}`;
const getc = `getChannel(getA(${switchedOrder.join()}), ${innerDims})`;
this.userCode = `
void main() {
${dtype} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${getc};
if(${nextColumn}) {
result[1] = ${getc};
}
--${outputOrder[this.rank - 1]};
if(++${outputOrder[this.rank - 2]} < ${outputShape[this.rank - 2]}) {
result[2] = ${getc};
if(${nextColumn}) {
result[3] = ${getc};
}
}
setOutput(result);
}
`;
}
}
//# sourceMappingURL=transpose_packed_gpu.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/Transpose_impl.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function transposeImpl(x, perm, backend) {
const program = Object(dist["env"])().getBool("WEBGL_PACK_ARRAY_OPERATIONS")
? new transpose_packed_gpu_TransposePackedProgram(x.shape, perm)
: new transpose_gpu_TransposeProgram(x.shape, perm);
return backend.runWebGLProgram(program, [x], x.dtype);
}
//# sourceMappingURL=Transpose_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/Max.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxConfig = {
kernelName: dist["Max"],
backendName: "webgl",
kernelFunc: ({ inputs, attrs, backend }) => {
const { x } = inputs;
const { reductionIndices } = attrs;
const webglBackend = backend;
const xRank = x.shape.length;
const origAxes = dist["util"].parseAxisParam(reductionIndices, x.shape);
let axes = origAxes;
const permutedAxes = dist["backend_util"].getAxesPermutation(axes, xRank);
const maxInputIsTransposed = permutedAxes != null;
const shouldExecuteOnCPU = webglBackend.shouldExecuteOnCPU([x]);
let maxInput = x;
if (maxInputIsTransposed) {
if (shouldExecuteOnCPU) {
const xTexData = webglBackend.texData.get(maxInput.dataId);
const values = xTexData.values;
const newShape = new Array(xRank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = x.shape[permutedAxes[i]];
}
const maxInputValues = transposeImplCPU(
values,
x.shape,
x.dtype,
permutedAxes,
newShape
);
maxInput = webglBackend.makeTensorInfo(newShape, x.dtype);
const maxInputData = webglBackend.texData.get(maxInput.dataId);
maxInputData.values = maxInputValues;
} else {
maxInput = transposeImpl(x, permutedAxes, webglBackend);
}
axes = dist["backend_util"].getInnerMostAxes(axes.length, xRank);
}
dist["backend_util"].assertAxesAreInnerMostDims("max", axes, xRank);
const [maxOutShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
maxInput.shape,
axes
);
let out;
if (shouldExecuteOnCPU) {
const xTexData = webglBackend.texData.get(maxInput.dataId);
const values = xTexData.values;
const outValues = maxImplCPU(
values,
dist["util"].sizeFromShape(reduceShape),
maxOutShape,
x.dtype
);
out = webglBackend.makeTensorInfo(maxOutShape, x.dtype);
const outData = webglBackend.texData.get(out.dataId);
outData.values = outValues;
} else {
out = maxImpl(maxInput, reduceShape, maxOutShape, webglBackend);
}
if (maxInputIsTransposed) {
webglBackend.disposeData(maxInput.dataId);
}
return out;
},
};
//# sourceMappingURL=Max.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/MaxPoolWithArgmax_impl.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function maxPoolWithArgmaxImpl(x, includeBatchInIndex, convInfo, backend) {
let program = new Pool2DProgram(convInfo, "max", false);
const poolOutput = backend.runWebGLProgram(program, [x], "float32");
program = new Pool2DProgram(convInfo, "max", true, true, includeBatchInIndex);
const indexOutput = backend.runWebGLProgram(program, [x], "float32");
return [poolOutput, indexOutput];
}
//# sourceMappingURL=MaxPoolWithArgmax_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/MaxPoolWithArgmax.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxPoolWithArgmaxConfig = {
kernelName: dist["MaxPoolWithArgmax"],
backendName: "webgl",
kernelFunc: ({ inputs, attrs, backend }) => {
const { x } = inputs;
const { filterSize, strides, pad, includeBatchInIndex } = attrs;
const webglBackend = backend;
dist["util"].assert(
x.shape.length === 4,
() => `Error in maxPool: input must be rank 4 but got rank ${x.shape.length}.`
);
const dilations = [1, 1];
dist["util"].assert(
dist["backend_util"].eitherStridesOrDilationsAreOne(strides, dilations),
() =>
"Error in maxPool: Either strides or dilations must be 1. " +
`Got strides ${strides} and dilations '${dilations}'`
);
const convInfo = dist["backend_util"].computePool2DInfo(
x.shape,
filterSize,
strides,
dilations,
pad
);
const [result, indexes] = maxPoolWithArgmaxImpl(
x,
includeBatchInIndex,
convInfo,
webglBackend
);
return [result, indexes];
},
};
//# sourceMappingURL=MaxPoolWithArgmax.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/NonMaxSuppressionV3.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const nonMaxSuppressionV3Config = {
kernelName: dist["NonMaxSuppressionV3"],
backendName: "webgl",
kernelFunc: ({ inputs, backend, attrs }) => {
dist["backend_util"].warn(
"tf.nonMaxSuppression() in webgl locks the UI thread. " +
"Call tf.nonMaxSuppressionAsync() instead"
);
const { boxes, scores } = inputs;
const { maxOutputSize, iouThreshold, scoreThreshold } = attrs;
const gpuBackend = backend;
const boxesVals = gpuBackend.readSync(boxes.dataId);
const scoresVals = gpuBackend.readSync(scores.dataId);
const maxOutputSizeVal = maxOutputSize;
const iouThresholdVal = iouThreshold;
const scoreThresholdVal = scoreThreshold;
return dist["kernel_impls"].nonMaxSuppressionV3(
boxesVals,
scoresVals,
maxOutputSizeVal,
iouThresholdVal,
scoreThresholdVal
);
},
};
//# sourceMappingURL=NonMaxSuppressionV3.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/NonMaxSuppressionV5.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const nonMaxSuppressionV5 = dist["kernel_impls"].nonMaxSuppressionV5;
const nonMaxSuppressionV5Config = {
kernelName: dist["NonMaxSuppressionV5"],
backendName: "webgl",
kernelFunc: ({ inputs, backend, attrs }) => {
dist["backend_util"].warn(
"tf.nonMaxSuppression() in webgl locks the UI thread. " +
"Call tf.nonMaxSuppressionAsync() instead"
);
const { boxes, scores } = inputs;
const { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma } = attrs;
const gpuBackend = backend;
const boxesVals = gpuBackend.readSync(boxes.dataId);
const scoresVals = gpuBackend.readSync(scores.dataId);
const maxOutputSizeVal = maxOutputSize;
const iouThresholdVal = iouThreshold;
const scoreThresholdVal = scoreThreshold;
const softNmsSigmaVal = softNmsSigma;
const { selectedIndices, selectedScores } = nonMaxSuppressionV5(
boxesVals,
scoresVals,
maxOutputSizeVal,
iouThresholdVal,
scoreThresholdVal,
softNmsSigmaVal
);
return [selectedIndices, selectedScores];
},
};
//# sourceMappingURL=NonMaxSuppressionV5.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/Square.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.
* =============================================================================
*/
const squareConfig = {
kernelName: dist["Square"],
backendName: "webgl",
kernelFunc: ({ inputs, backend }) => {
const { x } = inputs;
const webglBackend = backend;
const program = new UnaryOpProgram(x.shape, SQUARE);
return webglBackend.runWebGLProgram(program, [x], x.dtype);
},
};
//# sourceMappingURL=Square.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/SquaredDifference.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const squaredDifferenceConfig = {
kernelName: dist["SquaredDifference"],
backendName: "webgl",
kernelFunc: ({ inputs, backend }) => {
const { a, b } = inputs;
const SQUARED_DIFFERENCE = "return (a - b) * (a - b);";
const webGLBackend = backend;
const program = Object(dist["env"])().getBool("WEBGL_PACK_BINARY_OPERATIONS")
? new binaryop_packed_gpu_BinaryOpPackedProgram(SQUARED_DIFFERENCE, a.shape, b.shape)
: new binaryop_gpu_BinaryOpProgram(SQUARED_DIFFERENCE, a.shape, b.shape);
return webGLBackend.compileAndRun(program, [a, b]);
},
};
//# sourceMappingURL=SquaredDifference.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/kernels/Transpose.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const transposeConfig = {
kernelName: dist["Transpose"],
backendName: "webgl",
kernelFunc: ({ inputs, attrs, backend }) => {
const { x } = inputs;
const { perm } = attrs;
const webglBackend = backend;
const xRank = x.shape.length;
const newShape = new Array(xRank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = x.shape[perm[i]];
}
let out;
if (webglBackend.shouldExecuteOnCPU([x])) {
const xTexData = webglBackend.texData.get(x.dataId);
const values = xTexData.values;
const outValues = transposeImplCPU(values, x.shape, x.dtype, perm, newShape);
out = webglBackend.makeTensorInfo(newShape, x.dtype);
const outData = webglBackend.texData.get(out.dataId);
outData.values = outValues;
} else {
out = transposeImpl(x, perm, webglBackend);
}
return out;
},
};
//# sourceMappingURL=Transpose.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/register_all_kernels.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// List all kernel configs here
const kernelConfigs = [
maxConfig,
fromPixelsConfig,
divConfig,
nonMaxSuppressionV3Config,
nonMaxSuppressionV5Config,
squareConfig,
squaredDifferenceConfig,
transposeConfig,
maxPoolWithArgmaxConfig,
];
for (const kernelConfig of kernelConfigs) {
Object(dist["registerKernel"])(kernelConfig);
}
//# sourceMappingURL=register_all_kernels.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/webgl.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.
* =============================================================================
*/
// WebGL specific utils.
/**
* Enforce use of half precision textures if available on the platform.
*/
/** @doc {heading: 'Environment', namespace: 'webgl'} */
function forceHalfFloat() {
Object(dist["env"])().set("WEBGL_FORCE_F16_TEXTURES", true);
}
//# sourceMappingURL=webgl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-webgl/dist/index.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
if (dist["device_util"].isBrowser()) {
Object(dist["registerBackend"])(
"webgl",
() => new backend_webgl_MathBackendWebGL(),
2 /* priority */
);
}
// Export webgl utilities
// Export forceHalfFlost under webgl namespace for the union bundle.
const webgl = { forceHalfFloat: forceHalfFloat };
//# sourceMappingURL=index.js.map
/***/
},
/* 87 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "CallbackList", function () {
return /* reexport */ CallbackList;
});
__webpack_require__.d(__webpack_exports__, "CustomCallback", function () {
return /* reexport */ base_callbacks_CustomCallback;
});
__webpack_require__.d(__webpack_exports__, "History", function () {
return /* reexport */ History;
});
__webpack_require__.d(__webpack_exports__, "Callback", function () {
return /* reexport */ callbacks_Callback;
});
__webpack_require__.d(__webpack_exports__, "callbacks", function () {
return /* reexport */ callbacks_callbacks;
});
__webpack_require__.d(__webpack_exports__, "EarlyStopping", function () {
return /* reexport */ callbacks_EarlyStopping;
});
__webpack_require__.d(__webpack_exports__, "InputSpec", function () {
return /* reexport */ InputSpec;
});
__webpack_require__.d(__webpack_exports__, "SymbolicTensor", function () {
return /* reexport */ topology_SymbolicTensor;
});
__webpack_require__.d(__webpack_exports__, "LayersModel", function () {
return /* reexport */ training_LayersModel;
});
__webpack_require__.d(__webpack_exports__, "input", function () {
return /* reexport */ exports_input;
});
__webpack_require__.d(__webpack_exports__, "loadLayersModel", function () {
return /* reexport */ loadLayersModel;
});
__webpack_require__.d(__webpack_exports__, "model", function () {
return /* reexport */ exports_model;
});
__webpack_require__.d(__webpack_exports__, "registerCallbackConstructor", function () {
return /* reexport */ registerCallbackConstructor;
});
__webpack_require__.d(__webpack_exports__, "sequential", function () {
return /* reexport */ sequential;
});
__webpack_require__.d(__webpack_exports__, "RNN", function () {
return /* reexport */ recurrent_RNN;
});
__webpack_require__.d(__webpack_exports__, "Sequential", function () {
return /* reexport */ models_Sequential;
});
__webpack_require__.d(__webpack_exports__, "LayerVariable", function () {
return /* reexport */ variables_LayerVariable;
});
__webpack_require__.d(__webpack_exports__, "version_layers", function () {
return /* reexport */ version;
});
__webpack_require__.d(__webpack_exports__, "constraints", function () {
return /* reexport */ exports_constraints_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "initializers", function () {
return /* reexport */ exports_initializers_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "layers", function () {
return /* reexport */ exports_layers_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "metrics", function () {
return /* reexport */ exports_metrics_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "models", function () {
return /* reexport */ exports_models_namespaceObject;
});
__webpack_require__.d(__webpack_exports__, "regularizers", function () {
return /* reexport */ exports_regularizers_namespaceObject;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-layers/dist/exports_constraints.js
var exports_constraints_namespaceObject = {};
__webpack_require__.r(exports_constraints_namespaceObject);
__webpack_require__.d(exports_constraints_namespaceObject, "maxNorm", function () {
return maxNorm;
});
__webpack_require__.d(exports_constraints_namespaceObject, "unitNorm", function () {
return unitNorm;
});
__webpack_require__.d(exports_constraints_namespaceObject, "nonNeg", function () {
return nonNeg;
});
__webpack_require__.d(exports_constraints_namespaceObject, "minMaxNorm", function () {
return minMaxNorm;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-layers/dist/exports_initializers.js
var exports_initializers_namespaceObject = {};
__webpack_require__.r(exports_initializers_namespaceObject);
__webpack_require__.d(exports_initializers_namespaceObject, "zeros", function () {
return zeros;
});
__webpack_require__.d(exports_initializers_namespaceObject, "ones", function () {
return exports_initializers_ones;
});
__webpack_require__.d(exports_initializers_namespaceObject, "constant", function () {
return constant;
});
__webpack_require__.d(exports_initializers_namespaceObject, "randomUniform", function () {
return randomUniform;
});
__webpack_require__.d(exports_initializers_namespaceObject, "randomNormal", function () {
return exports_initializers_randomNormal;
});
__webpack_require__.d(exports_initializers_namespaceObject, "truncatedNormal", function () {
return truncatedNormal;
});
__webpack_require__.d(exports_initializers_namespaceObject, "identity", function () {
return identity;
});
__webpack_require__.d(exports_initializers_namespaceObject, "varianceScaling", function () {
return varianceScaling;
});
__webpack_require__.d(exports_initializers_namespaceObject, "glorotUniform", function () {
return glorotUniform;
});
__webpack_require__.d(exports_initializers_namespaceObject, "glorotNormal", function () {
return glorotNormal;
});
__webpack_require__.d(exports_initializers_namespaceObject, "heNormal", function () {
return heNormal;
});
__webpack_require__.d(exports_initializers_namespaceObject, "heUniform", function () {
return heUniform;
});
__webpack_require__.d(exports_initializers_namespaceObject, "leCunNormal", function () {
return leCunNormal;
});
__webpack_require__.d(exports_initializers_namespaceObject, "leCunUniform", function () {
return leCunUniform;
});
__webpack_require__.d(exports_initializers_namespaceObject, "orthogonal", function () {
return orthogonal;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-layers/dist/exports_layers.js
var exports_layers_namespaceObject = {};
__webpack_require__.r(exports_layers_namespaceObject);
__webpack_require__.d(exports_layers_namespaceObject, "inputLayer", function () {
return exports_layers_inputLayer;
});
__webpack_require__.d(exports_layers_namespaceObject, "elu", function () {
return exports_layers_elu;
});
__webpack_require__.d(exports_layers_namespaceObject, "reLU", function () {
return reLU;
});
__webpack_require__.d(exports_layers_namespaceObject, "leakyReLU", function () {
return leakyReLU;
});
__webpack_require__.d(exports_layers_namespaceObject, "prelu", function () {
return prelu;
});
__webpack_require__.d(exports_layers_namespaceObject, "softmax", function () {
return softmax;
});
__webpack_require__.d(exports_layers_namespaceObject, "thresholdedReLU", function () {
return thresholdedReLU;
});
__webpack_require__.d(exports_layers_namespaceObject, "conv1d", function () {
return exports_layers_conv1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "conv2d", function () {
return exports_layers_conv2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "conv2dTranspose", function () {
return conv2dTranspose;
});
__webpack_require__.d(exports_layers_namespaceObject, "conv3d", function () {
return exports_layers_conv3d;
});
__webpack_require__.d(exports_layers_namespaceObject, "separableConv2d", function () {
return separableConv2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "cropping2D", function () {
return cropping2D;
});
__webpack_require__.d(exports_layers_namespaceObject, "upSampling2d", function () {
return upSampling2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "depthwiseConv2d", function () {
return exports_layers_depthwiseConv2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "activation", function () {
return exports_layers_activation;
});
__webpack_require__.d(exports_layers_namespaceObject, "dense", function () {
return dense;
});
__webpack_require__.d(exports_layers_namespaceObject, "dropout", function () {
return exports_layers_dropout;
});
__webpack_require__.d(exports_layers_namespaceObject, "spatialDropout1d", function () {
return spatialDropout1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "flatten", function () {
return exports_layers_flatten;
});
__webpack_require__.d(exports_layers_namespaceObject, "repeatVector", function () {
return repeatVector;
});
__webpack_require__.d(exports_layers_namespaceObject, "reshape", function () {
return reshape;
});
__webpack_require__.d(exports_layers_namespaceObject, "permute", function () {
return permute;
});
__webpack_require__.d(exports_layers_namespaceObject, "embedding", function () {
return embedding;
});
__webpack_require__.d(exports_layers_namespaceObject, "add", function () {
return exports_layers_add;
});
__webpack_require__.d(exports_layers_namespaceObject, "average", function () {
return exports_layers_average;
});
__webpack_require__.d(exports_layers_namespaceObject, "concatenate", function () {
return exports_layers_concatenate;
});
__webpack_require__.d(exports_layers_namespaceObject, "maximum", function () {
return exports_layers_maximum;
});
__webpack_require__.d(exports_layers_namespaceObject, "minimum", function () {
return exports_layers_minimum;
});
__webpack_require__.d(exports_layers_namespaceObject, "multiply", function () {
return exports_layers_multiply;
});
__webpack_require__.d(exports_layers_namespaceObject, "dot", function () {
return exports_layers_dot;
});
__webpack_require__.d(exports_layers_namespaceObject, "batchNormalization", function () {
return exports_layers_batchNormalization;
});
__webpack_require__.d(exports_layers_namespaceObject, "layerNormalization", function () {
return layerNormalization;
});
__webpack_require__.d(exports_layers_namespaceObject, "zeroPadding2d", function () {
return zeroPadding2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "averagePooling1d", function () {
return averagePooling1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "avgPool1d", function () {
return avgPool1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "avgPooling1d", function () {
return avgPooling1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "averagePooling2d", function () {
return averagePooling2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "avgPool2d", function () {
return avgPool2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "avgPooling2d", function () {
return avgPooling2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "averagePooling3d", function () {
return averagePooling3d;
});
__webpack_require__.d(exports_layers_namespaceObject, "avgPool3d", function () {
return avgPool3d;
});
__webpack_require__.d(exports_layers_namespaceObject, "avgPooling3d", function () {
return avgPooling3d;
});
__webpack_require__.d(exports_layers_namespaceObject, "globalAveragePooling1d", function () {
return globalAveragePooling1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "globalAveragePooling2d", function () {
return globalAveragePooling2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "globalMaxPooling1d", function () {
return globalMaxPooling1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "globalMaxPooling2d", function () {
return globalMaxPooling2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "maxPooling1d", function () {
return maxPooling1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "maxPooling2d", function () {
return maxPooling2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "maxPooling3d", function () {
return maxPooling3d;
});
__webpack_require__.d(exports_layers_namespaceObject, "gru", function () {
return gru;
});
__webpack_require__.d(exports_layers_namespaceObject, "gruCell", function () {
return gruCell;
});
__webpack_require__.d(exports_layers_namespaceObject, "lstm", function () {
return lstm;
});
__webpack_require__.d(exports_layers_namespaceObject, "lstmCell", function () {
return lstmCell;
});
__webpack_require__.d(exports_layers_namespaceObject, "simpleRNN", function () {
return simpleRNN;
});
__webpack_require__.d(exports_layers_namespaceObject, "simpleRNNCell", function () {
return simpleRNNCell;
});
__webpack_require__.d(exports_layers_namespaceObject, "rnn", function () {
return exports_layers_rnn;
});
__webpack_require__.d(exports_layers_namespaceObject, "stackedRNNCells", function () {
return stackedRNNCells;
});
__webpack_require__.d(exports_layers_namespaceObject, "bidirectional", function () {
return bidirectional;
});
__webpack_require__.d(exports_layers_namespaceObject, "timeDistributed", function () {
return timeDistributed;
});
__webpack_require__.d(exports_layers_namespaceObject, "globalMaxPool1d", function () {
return globalMaxPool1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "globalMaxPool2d", function () {
return globalMaxPool2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "maxPool1d", function () {
return maxPool1d;
});
__webpack_require__.d(exports_layers_namespaceObject, "maxPool2d", function () {
return maxPool2d;
});
__webpack_require__.d(exports_layers_namespaceObject, "Layer", function () {
return topology_Layer;
});
__webpack_require__.d(exports_layers_namespaceObject, "RNN", function () {
return recurrent_RNN;
});
__webpack_require__.d(exports_layers_namespaceObject, "RNNCell", function () {
return recurrent_RNNCell;
});
__webpack_require__.d(exports_layers_namespaceObject, "input", function () {
return exports_input;
});
__webpack_require__.d(exports_layers_namespaceObject, "gaussianNoise", function () {
return gaussianNoise;
});
__webpack_require__.d(exports_layers_namespaceObject, "gaussianDropout", function () {
return gaussianDropout;
});
__webpack_require__.d(exports_layers_namespaceObject, "alphaDropout", function () {
return alphaDropout;
});
__webpack_require__.d(exports_layers_namespaceObject, "masking", function () {
return masking;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-layers/dist/exports_metrics.js
var exports_metrics_namespaceObject = {};
__webpack_require__.r(exports_metrics_namespaceObject);
__webpack_require__.d(exports_metrics_namespaceObject, "binaryAccuracy", function () {
return exports_metrics_binaryAccuracy;
});
__webpack_require__.d(exports_metrics_namespaceObject, "binaryCrossentropy", function () {
return exports_metrics_binaryCrossentropy;
});
__webpack_require__.d(
exports_metrics_namespaceObject,
"sparseCategoricalAccuracy",
function () {
return exports_metrics_sparseCategoricalAccuracy;
}
);
__webpack_require__.d(exports_metrics_namespaceObject, "categoricalAccuracy", function () {
return exports_metrics_categoricalAccuracy;
});
__webpack_require__.d(
exports_metrics_namespaceObject,
"categoricalCrossentropy",
function () {
return exports_metrics_categoricalCrossentropy;
}
);
__webpack_require__.d(exports_metrics_namespaceObject, "precision", function () {
return exports_metrics_precision;
});
__webpack_require__.d(exports_metrics_namespaceObject, "recall", function () {
return exports_metrics_recall;
});
__webpack_require__.d(exports_metrics_namespaceObject, "cosineProximity", function () {
return exports_metrics_cosineProximity;
});
__webpack_require__.d(exports_metrics_namespaceObject, "meanAbsoluteError", function () {
return exports_metrics_meanAbsoluteError;
});
__webpack_require__.d(
exports_metrics_namespaceObject,
"meanAbsolutePercentageError",
function () {
return exports_metrics_meanAbsolutePercentageError;
}
);
__webpack_require__.d(exports_metrics_namespaceObject, "MAPE", function () {
return exports_metrics_MAPE;
});
__webpack_require__.d(exports_metrics_namespaceObject, "mape", function () {
return exports_metrics_mape;
});
__webpack_require__.d(exports_metrics_namespaceObject, "meanSquaredError", function () {
return exports_metrics_meanSquaredError;
});
__webpack_require__.d(exports_metrics_namespaceObject, "MSE", function () {
return exports_metrics_MSE;
});
__webpack_require__.d(exports_metrics_namespaceObject, "mse", function () {
return exports_metrics_mse;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-layers/dist/exports_models.js
var exports_models_namespaceObject = {};
__webpack_require__.r(exports_models_namespaceObject);
__webpack_require__.d(exports_models_namespaceObject, "modelFromJSON", function () {
return modelFromJSON;
});
// NAMESPACE OBJECT: ./node_modules/@tensorflow/tfjs-layers/dist/exports_regularizers.js
var exports_regularizers_namespaceObject = {};
__webpack_require__.r(exports_regularizers_namespaceObject);
__webpack_require__.d(exports_regularizers_namespaceObject, "l1l2", function () {
return l1l2;
});
__webpack_require__.d(exports_regularizers_namespaceObject, "l1", function () {
return exports_regularizers_l1;
});
__webpack_require__.d(exports_regularizers_namespaceObject, "l2", function () {
return exports_regularizers_l2;
});
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js + 269 modules
var dist = __webpack_require__(0);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/backend/common.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
let _epsilon;
/**
* Returns the value of the fuzz factor used in numeric expressions.
*/
function common_epsilon() {
if (_epsilon == null) {
_epsilon = Object(dist["backend"])().epsilon();
}
return _epsilon;
}
/**
* Sets the value of the fuzz factor used in numeric expressions.
* @param e New value of epsilon.
*/
function setEpsilon(e) {
_epsilon = e;
}
/**
* Returns the default image data format convention.
*/
function imageDataFormat() {
return "channelsLast";
}
//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/errors.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Explicit error types.
*
* See the following link for more information about why the code includes
* calls to setPrototypeOf:
*
* https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
*/
// tslint:enable
/**
* Equivalent of Python's AttributeError.
*/
class AttributeError extends Error {
constructor(message) {
super(message);
// Set the prototype explicitly.
Object.setPrototypeOf(this, AttributeError.prototype);
}
}
/**
* Equivalent of Python's RuntimeError.
*/
class RuntimeError extends Error {
constructor(message) {
super(message);
// Set the prototype explicitly.
Object.setPrototypeOf(this, RuntimeError.prototype);
}
}
/**
* Equivalent of Python's ValueError.
*/
class ValueError extends Error {
constructor(message) {
super(message);
// Set the prototype explicitly.
Object.setPrototypeOf(this, ValueError.prototype);
}
}
/**
* Equivalent of Python's NotImplementedError.
*/
class NotImplementedError extends Error {
constructor(message) {
super(message);
// Set the prototype explicitly.
Object.setPrototypeOf(this, NotImplementedError.prototype);
}
}
/**
* Equivalent of Python's AssertionError.
*/
class AssertionError extends Error {
constructor(message) {
super(message);
// Set the prototype explicitly.
Object.setPrototypeOf(this, AssertionError.prototype);
}
}
/**
* Equivalent of Python's IndexError.
*/
class IndexError extends Error {
constructor(message) {
super(message);
// Set the prototype explicitly.
Object.setPrototypeOf(this, IndexError.prototype);
}
}
//# sourceMappingURL=errors.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/utils/generic_utils.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original source: utils/generic_utils.py */
// tslint:enable
/**
* If `value` is an Array, equivalent to Python's `value * numValues`.
* If `value` is not an Array, equivalent to Python's `[value] * numValues`
*/
// tslint:disable-next-line:no-any
function pyListRepeat(value, numValues) {
if (Array.isArray(value)) {
// tslint:disable-next-line:no-any
let newArray = [];
for (let i = 0; i < numValues; i++) {
newArray = newArray.concat(value);
}
return newArray;
} else {
const newArray = new Array(numValues);
newArray.fill(value);
return newArray;
}
}
function assert(val, message) {
if (!val) {
throw new AssertionError(message);
}
}
/**
* Count the number of elements of the `array` that are equal to `reference`.
*/
function generic_utils_count(array, refernce) {
let counter = 0;
for (const item of array) {
if (item === refernce) {
counter++;
}
}
return counter;
}
/**
* If an array is of length 1, just return the first element. Otherwise, return
* the full array.
* @param tensors
*/
function singletonOrArray(xs) {
if (xs.length === 1) {
return xs[0];
}
return xs;
}
/**
* Normalizes a list/tensor into a list.
*
* If a tensor is passed, we return
* a list of size 1 containing the tensor.
*
* @param x target object to be normalized.
*/
// tslint:disable-next-line:no-any
function toList(x) {
if (Array.isArray(x)) {
return x;
}
return [x];
}
/**
* Generate a UID for a list
*/
// tslint:disable-next-line:no-any
function objectListUid(objs) {
const objectList = toList(objs);
let retVal = "";
for (const obj of objectList) {
if (obj.id == null) {
throw new ValueError(`Object ${obj} passed to objectListUid without an id`);
}
if (retVal !== "") {
retVal = retVal + ", ";
}
retVal = `${retVal}${Math.abs(obj.id)}`;
}
return retVal;
}
/**
* Converts string to snake-case.
* @param name
*/
function toSnakeCase(name) {
const intermediate = name.replace(/(.)([A-Z][a-z0-9]+)/g, "$1_$2");
const insecure = intermediate.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
/*
If the class is private the name starts with "_" which is not secure
for creating scopes. We prefix the name with "private" in this case.
*/
if (insecure[0] !== "_") {
return insecure;
}
return "private" + insecure;
}
function toCamelCase(identifier) {
// quick return for empty string or single character strings
if (identifier.length <= 1) {
return identifier;
}
// Check for the underscore indicating snake_case
if (identifier.indexOf("_") === -1) {
return identifier;
}
return identifier.replace(/[_]+(\w|$)/g, (m, p1) => p1.toUpperCase());
}
// tslint:disable-next-line:no-any
let _GLOBAL_CUSTOM_OBJECTS = {};
function serializeKerasObject(instance) {
if (instance === null || instance === undefined) {
return null;
}
const dict = {};
dict["className"] = instance.getClassName();
dict["config"] = instance.getConfig();
return dict;
}
/**
* Replace ndarray-style scalar objects in serialization objects with numbers.
*
* Background: In some versions of tf.keras, certain scalar values in the HDF5
* model save file can be serialized as: `{'type': 'ndarray', 'value': num}`,
* where in `num` is a plain number. This method converts such serialization
* to a `number`.
*
* @param config The keras-format serialization object to be processed
* (in place).
*/
function convertNDArrayScalarsInConfig(config) {
if (config == null || typeof config !== "object") {
return;
} else if (Array.isArray(config)) {
config.forEach((configItem) => convertNDArrayScalarsInConfig(configItem));
} else {
const fields = Object.keys(config);
for (const field of fields) {
const value = config[field];
if (value != null && typeof value === "object") {
if (
!Array.isArray(value) &&
value["type"] === "ndarray" &&
typeof value["value"] === "number"
) {
config[field] = value["value"];
} else {
convertNDArrayScalarsInConfig(value);
}
}
}
}
}
/**
* Deserialize a saved Keras Object
* @param identifier either a string ID or a saved Keras dictionary
* @param moduleObjects a list of Python class names to object constructors
* @param customObjects a list of Python class names to object constructors
* @param printableModuleName debug text for the object being reconstituted
* @param fastWeightInit Optional flag to use fast weight initialization
* during deserialization. This is applicable to cases in which
* the initialization will be immediately overwritten by loaded weight
* values. Default: `false`.
* @returns a TensorFlow.js Layers object
*/
// tslint:disable:no-any
function deserializeKerasObject(
identifier,
moduleObjects = {},
customObjects = {},
printableModuleName = "object",
fastWeightInit = false
) {
// tslint:enable
if (typeof identifier === "string") {
const functionName = identifier;
let fn;
if (functionName in customObjects) {
fn = customObjects[functionName];
} else if (functionName in _GLOBAL_CUSTOM_OBJECTS) {
fn = _GLOBAL_CUSTOM_OBJECTS[functionName];
} else {
fn = moduleObjects[functionName];
if (fn == null) {
throw new ValueError(
`Unknown ${printableModuleName}: ${identifier}. ` +
`This may be due to one of the following reasons:\n` +
`1. The ${printableModuleName} is defined in Python, in which ` +
`case it needs to be ported to TensorFlow.js or your JavaScript ` +
`code.\n` +
`2. The custom ${printableModuleName} is defined in JavaScript, ` +
`but is not registered properly with ` +
`tf.serialization.registerClass().`
);
// TODO(cais): Add link to tutorial page on custom layers.
}
}
return fn;
} else {
// In this case we are dealing with a Keras config dictionary.
const config = identifier;
if (config["className"] == null || config["config"] == null) {
throw new ValueError(
`${printableModuleName}: Improper config format: ` +
`${JSON.stringify(config)}.\n` +
`'className' and 'config' must set.`
);
}
const className = config["className"];
let cls, fromConfig;
if (className in customObjects) {
[cls, fromConfig] = customObjects[className];
} else if (className in _GLOBAL_CUSTOM_OBJECTS) {
[cls, fromConfig] = _GLOBAL_CUSTOM_OBJECTS["className"];
} else if (className in moduleObjects) {
[cls, fromConfig] = moduleObjects[className];
}
if (cls == null) {
throw new ValueError(
`Unknown ${printableModuleName}: ${className}. ` +
`This may be due to one of the following reasons:\n` +
`1. The ${printableModuleName} is defined in Python, in which ` +
`case it needs to be ported to TensorFlow.js or your JavaScript ` +
`code.\n` +
`2. The custom ${printableModuleName} is defined in JavaScript, ` +
`but is not registered properly with ` +
`tf.serialization.registerClass().`
);
// TODO(cais): Add link to tutorial page on custom layers.
}
if (fromConfig != null) {
// Porting notes: Instead of checking to see whether fromConfig accepts
// customObjects, we create a customObjects dictionary and tack it on to
// config['config'] as config['config'].customObjects. Objects can use it,
// if they want.
// tslint:disable-next-line:no-any
const customObjectsCombined = {};
for (const key of Object.keys(_GLOBAL_CUSTOM_OBJECTS)) {
customObjectsCombined[key] = _GLOBAL_CUSTOM_OBJECTS[key];
}
for (const key of Object.keys(customObjects)) {
customObjectsCombined[key] = customObjects[key];
}
// Add the customObjects to config
const nestedConfig = config["config"];
nestedConfig["customObjects"] = customObjectsCombined;
const backupCustomObjects = Object.assign({}, _GLOBAL_CUSTOM_OBJECTS);
for (const key of Object.keys(customObjects)) {
_GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key];
}
convertNDArrayScalarsInConfig(config["config"]);
const returnObj = fromConfig(cls, config["config"], customObjects, fastWeightInit);
_GLOBAL_CUSTOM_OBJECTS = Object.assign({}, backupCustomObjects);
return returnObj;
} else {
// Then `cls` may be a function returning a class.
// In this case by convention `config` holds
// the kwargs of the function.
const backupCustomObjects = Object.assign({}, _GLOBAL_CUSTOM_OBJECTS);
for (const key of Object.keys(customObjects)) {
_GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key];
}
// In python this is **config['config'], for tfjs-layers we require
// classes that use this fall-through construction method to take
// a config interface that mimics the expansion of named parameters.
const returnObj = new cls(config["config"]);
_GLOBAL_CUSTOM_OBJECTS = Object.assign({}, backupCustomObjects);
return returnObj;
}
}
}
/**
* Compares two numbers for sorting.
* @param a
* @param b
*/
function numberCompare(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* Comparison of two numbers for reverse sorting.
* @param a
* @param b
*/
function reverseNumberCompare(a, b) {
return -1 * numberCompare(a, b);
}
/**
* Convert a string into the corresponding DType.
* @param dtype
* @returns An instance of DType.
*/
function stringToDType(dtype) {
switch (dtype) {
case "float32":
return "float32";
default:
throw new ValueError(`Invalid dtype: ${dtype}`);
}
}
/**
* Test the element-by-element equality of two Arrays of strings.
* @param xs First array of strings.
* @param ys Second array of strings.
* @returns Wether the two arrays are all equal, element by element.
*/
function stringsEqual(xs, ys) {
if (xs == null || ys == null) {
return xs === ys;
}
if (xs.length !== ys.length) {
return false;
}
for (let i = 0; i < xs.length; ++i) {
if (xs[i] !== ys[i]) {
return false;
}
}
return true;
}
/**
* Get the unique elements of an array.
* @param xs Array.
* @returns An Array consisting of the unique elements in `xs`.
*/
function unique(xs) {
if (xs == null) {
return xs;
}
const out = [];
// TODO(cais): Maybe improve performance by sorting.
for (const x of xs) {
if (out.indexOf(x) === -1) {
out.push(x);
}
}
return out;
}
/**
* Determine if an Object is empty (i.e., does not have own properties).
* @param obj Object
* @returns Whether the Object is empty.
* @throws ValueError: If object is `null` or `undefined`.
*/
function isObjectEmpty(obj) {
if (obj == null) {
throw new ValueError(`Invalid value in obj: ${JSON.stringify(obj)}`);
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
/**
* Helper function used to build type union/enum run-time checkers.
* @param values The list of allowed values.
* @param label A string name for the type
* @param value The value to test.
* @throws ValueError: If the value is not in values nor `undefined`/`null`.
*/
function checkStringTypeUnionValue(values, label, value) {
if (value == null) {
return;
}
if (values.indexOf(value) < 0) {
throw new ValueError(
`${value} is not a valid ${label}. Valid values are ${values} or null/undefined.`
);
}
}
/**
* Helper function for verifying the types of inputs.
*
* Ensures that the elements of `x` are all of type `expectedType`.
* Also verifies that the length of `x` is within bounds.
*
* @param x Object to test.
* @param expectedType The string expected type of all of the elements in the
* Array.
* @param minLength Return false if x.length is less than this.
* @param maxLength Return false if x.length is greater than this.
* @returns true if and only if `x` is an `Array<expectedType>` with
* length >= `minLength` and <= `maxLength`.
*/
// tslint:disable:no-any
function checkArrayTypeAndLength(x, expectedType, minLength = 0, maxLength = Infinity) {
assert(minLength >= 0);
assert(maxLength >= minLength);
return (
Array.isArray(x) &&
x.length >= minLength &&
x.length <= maxLength &&
x.every((e) => typeof e === expectedType)
);
}
// tslint:enable:no-any
/**
* Assert that a value or an array of value are positive integer.
*
* @param value The value being asserted on. May be a single number or an array
* of numbers.
* @param name Name of the value, used to make the error message.
*/
function assertPositiveInteger(value, name) {
if (Array.isArray(value)) {
dist["util"].assert(value.length > 0, () => `${name} is unexpectedly an empty array.`);
value.forEach((v, i) => assertPositiveInteger(v, `element ${i + 1} of ${name}`));
} else {
dist["util"].assert(
Number.isInteger(value) && value > 0,
() =>
`Expected ${name} to be a positive integer, but got ` +
`${formatAsFriendlyString(value)}.`
);
}
}
/**
* Format a value into a display-friendly, human-readable fashion.
*
* - `null` is formatted as `'null'`
* - Strings are formated with flanking pair of quotes.
* - Arrays are formatted with flanking pair of square brackets.
*
* @param value The value to display.
* @return Formatted string.
*/
// tslint:disable-next-line:no-any
function formatAsFriendlyString(value) {
if (value === null) {
return "null";
} else if (Array.isArray(value)) {
return "[" + value.map((v) => formatAsFriendlyString(v)).join(",") + "]";
} else if (typeof value === "string") {
return `"${value}"`;
} else {
return `${value}`;
}
}
/**
* Returns a function `f2` (decorator) which wraps the original function
* `f`. `f2` guarantees that `f` can be called at most once
* every `waitMs` ms. If `f2` is called more often, it will return
* the last returned result of `f`.
*
* @param f The original function `f` to wrap.
* @param waitMs The time between two consecutive calls to `f` in ms.
*/
function debounce(f, waitMs) {
let lastTime = dist["util"].now();
let lastResult;
const f2 = (...args) => {
const now = dist["util"].now();
if (now - lastTime < waitMs) {
return lastResult;
}
lastTime = now;
lastResult = f(...args);
return lastResult;
};
return f2;
}
/**
* Returns the fusable activation given a layers identifier.
*
* @param activationName The layers identifier string.
* @return The name of the fusable activation.
*/
function mapActivationToFusedKernel(activationName) {
if (activationName === "relu") {
return "relu";
}
if (activationName === "linear") {
return "linear";
}
if (activationName === "elu") {
return "elu";
}
return null;
}
//# sourceMappingURL=generic_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/constraints.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original source: keras/contraints.py */
/**
* Helper function used by many of the Constraints to find the L2Norms.
*/
function calcL2Norms(w, axis) {
return Object(dist["tidy"])(() => dist["sqrt"](dist["sum"](dist["mul"](w, w), axis, true)));
}
/**
* Base class for functions that impose constraints on weight values
*/
/**
* @doc {
* heading: 'Constraints',
* subheading: 'Classes',
* namespace: 'constraints'
* }
*/
class constraints_Constraint extends dist["serialization"].Serializable {
getConfig() {
return {};
}
}
class constraints_MaxNorm extends constraints_Constraint {
constructor(args) {
super();
this.defaultMaxValue = 2;
this.defaultAxis = 0;
this.maxValue = args.maxValue != null ? args.maxValue : this.defaultMaxValue;
this.axis = args.axis != null ? args.axis : this.defaultAxis;
}
apply(w) {
return Object(dist["tidy"])(() => {
const norms = calcL2Norms(w, this.axis);
const desired = dist["clipByValue"](norms, 0, this.maxValue);
return dist["mul"](w, dist["div"](desired, dist["add"](common_epsilon(), norms)));
});
}
getConfig() {
return { maxValue: this.maxValue, axis: this.axis };
}
}
/** @nocollapse */
constraints_MaxNorm.className = "MaxNorm";
dist["serialization"].registerClass(constraints_MaxNorm);
class constraints_UnitNorm extends constraints_Constraint {
constructor(args) {
super();
this.defaultAxis = 0;
this.axis = args.axis != null ? args.axis : this.defaultAxis;
}
apply(w) {
return Object(dist["tidy"])(() =>
dist["div"](w, dist["add"](common_epsilon(), calcL2Norms(w, this.axis)))
);
}
getConfig() {
return { axis: this.axis };
}
}
/** @nocollapse */
constraints_UnitNorm.className = "UnitNorm";
dist["serialization"].registerClass(constraints_UnitNorm);
class constraints_NonNeg extends constraints_Constraint {
apply(w) {
return dist["relu"](w);
}
}
/** @nocollapse */
constraints_NonNeg.className = "NonNeg";
dist["serialization"].registerClass(constraints_NonNeg);
class constraints_MinMaxNorm extends constraints_Constraint {
constructor(args) {
super();
this.defaultMinValue = 0.0;
this.defaultMaxValue = 1.0;
this.defaultRate = 1.0;
this.defaultAxis = 0;
this.minValue = args.minValue != null ? args.minValue : this.defaultMinValue;
this.maxValue = args.maxValue != null ? args.maxValue : this.defaultMaxValue;
this.rate = args.rate != null ? args.rate : this.defaultRate;
this.axis = args.axis != null ? args.axis : this.defaultAxis;
}
apply(w) {
return Object(dist["tidy"])(() => {
const norms = calcL2Norms(w, this.axis);
const desired = dist["add"](
dist["mul"](this.rate, dist["clipByValue"](norms, this.minValue, this.maxValue)),
dist["mul"](1.0 - this.rate, norms)
);
return dist["mul"](w, dist["div"](desired, dist["add"](common_epsilon(), norms)));
});
}
getConfig() {
return {
minValue: this.minValue,
maxValue: this.maxValue,
rate: this.rate,
axis: this.axis,
};
}
}
/** @nocollapse */
constraints_MinMaxNorm.className = "MinMaxNorm";
dist["serialization"].registerClass(constraints_MinMaxNorm);
// Maps the JavaScript-like identifier keys to the corresponding registry
// symbols.
const CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
maxNorm: "MaxNorm",
minMaxNorm: "MinMaxNorm",
nonNeg: "NonNeg",
unitNorm: "UnitNorm",
};
function serializeConstraint(constraint) {
return serializeKerasObject(constraint);
}
function deserializeConstraint(config, customObjects = {}) {
return deserializeKerasObject(
config,
dist["serialization"].SerializationMap.getMap().classNameMap,
customObjects,
"constraint"
);
}
function getConstraint(identifier) {
if (identifier == null) {
return null;
}
if (typeof identifier === "string") {
const className =
identifier in CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP
? CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier]
: identifier;
const config = { className, config: {} };
return deserializeConstraint(config);
} else if (identifier instanceof constraints_Constraint) {
return identifier;
} else {
return deserializeConstraint(identifier);
}
}
//# sourceMappingURL=constraints.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/exports_constraints.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// tslint:disable-next-line:max-line-length
/**
* MaxNorm weight constraint.
*
* Constrains the weights incident to each hidden unit
* to have a norm less than or equal to a desired value.
*
* References
* - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting
* Srivastava, Hinton, et al.
* 2014](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf)
*/
/** @doc {heading: 'Constraints',namespace: 'constraints'} */
function maxNorm(args) {
return new constraints_MaxNorm(args);
}
/**
* Constrains the weights incident to each hidden unit to have unit norm.
*/
/** @doc {heading: 'Constraints', namespace: 'constraints'} */
function unitNorm(args) {
return new constraints_UnitNorm(args);
}
/**
* Constains the weight to be non-negative.
*/
/** @doc {heading: 'Constraints', namespace: 'constraints'} */
function nonNeg() {
return new constraints_NonNeg();
}
/** @doc {heading: 'Constraints', namespace: 'constraints'} */
function minMaxNorm(config) {
return new constraints_MinMaxNorm(config);
}
//# sourceMappingURL=exports_constraints.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/keras_format/common.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const VALID_DATA_FORMAT_VALUES = ["channelsFirst", "channelsLast"];
const VALID_PADDING_MODE_VALUES = ["valid", "same", "causal"];
const VALID_POOL_MODE_VALUES = ["max", "avg"];
const VALID_BIDIRECTIONAL_MERGE_MODES = ["sum", "mul", "concat", "ave"];
const VALID_SAMPLE_WEIGHT_MODES = ["temporal"];
//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/common.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Common functions for TensorFlow.js Layers.
*/
// A map from the requested scoped name of a Tensor to the number of Tensors
// wanting that name so far. This allows enforcing name uniqueness by appending
// an incrementing index, e.g. scope/name, scope/name_1, scope/name_2, etc.
const nameMap = new Map();
function checkDataFormat(value) {
checkStringTypeUnionValue(VALID_DATA_FORMAT_VALUES, "DataFormat", value);
}
function checkPaddingMode(value) {
checkStringTypeUnionValue(VALID_PADDING_MODE_VALUES, "PaddingMode", value);
}
function checkPoolMode(value) {
checkStringTypeUnionValue(VALID_POOL_MODE_VALUES, "PoolMode", value);
}
const _nameScopeStack = [];
const _nameScopeDivider = "/";
/**
* Enter namescope, which can be nested.
*/
function nameScope(name, fn) {
_nameScopeStack.push(name);
try {
const val = fn();
_nameScopeStack.pop();
return val;
} catch (e) {
_nameScopeStack.pop();
throw e;
}
}
/**
* Get the current namescope as a flat, concatenated string.
*/
function currentNameScopePrefix() {
if (_nameScopeStack.length === 0) {
return "";
} else {
return _nameScopeStack.join(_nameScopeDivider) + _nameScopeDivider;
}
}
/**
* Get the name a Tensor (or Variable) would have if not uniqueified.
* @param tensorName
* @return Scoped name string.
*/
function getScopedTensorName(tensorName) {
if (!isValidTensorName(tensorName)) {
throw new Error("Not a valid tensor name: '" + tensorName + "'");
}
return currentNameScopePrefix() + tensorName;
}
/**
* Get unique names for Tensors and Variables.
* @param scopedName The fully-qualified name of the Tensor, i.e. as produced by
* `getScopedTensorName()`.
* @return A unique version of the given fully scoped name.
* If this is the first time that the scoped name is seen in this session,
* then the given `scopedName` is returned unaltered. If the same name is
* seen again (producing a collision), an incrementing suffix is added to the
* end of the name, so it takes the form 'scope/name_1', 'scope/name_2', etc.
*/
function getUniqueTensorName(scopedName) {
if (!isValidTensorName(scopedName)) {
throw new Error("Not a valid tensor name: '" + scopedName + "'");
}
if (!nameMap.has(scopedName)) {
nameMap.set(scopedName, 0);
}
const index = nameMap.get(scopedName);
nameMap.set(scopedName, nameMap.get(scopedName) + 1);
if (index > 0) {
const result = `${scopedName}_${index}`;
// Mark the composed name as used in case someone wants
// to call getUniqueTensorName("name_1").
nameMap.set(result, 1);
return result;
} else {
return scopedName;
}
}
const tensorNameRegex = new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);
/**
* Determine whether a string is a valid tensor name.
* @param name
* @returns A Boolean indicating whether `name` is a valid tensor name.
*/
function isValidTensorName(name) {
return !!name.match(tensorNameRegex);
}
//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/utils/math_utils.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Math utility functions.
*
* This file contains some frequently used math function that operates on
* number[] or Float32Array and return a number. Many of these functions are
* not-so-thick wrappers around TF.js Core functions. But they offer the
* convenience of
* 1) not having to convert the inputs into Tensors,
* 2) not having to convert the returned Tensors to numbers.
*/
/**
* Determine if a number is an integer.
*/
function isInteger(x) {
return x === parseInt(x.toString(), 10);
}
/**
* Calculate the product of an array of numbers.
* @param array The array to calculate the product over.
* @param begin Beginning index, inclusive.
* @param end Ending index, exclusive.
* @return The product.
*/
function arrayProd(array, begin, end) {
if (begin == null) {
begin = 0;
}
if (end == null) {
end = array.length;
}
let prod = 1;
for (let i = begin; i < end; ++i) {
prod *= array[i];
}
return prod;
}
/**
* A helper function transforms the two input types to an instance of Tensor1D,
* so the return value can be fed directly into various TF.js Core functions.
* @param array
*/
function toArray1D(array) {
array = Array.isArray(array) ? new Float32Array(array) : array;
return Object(dist["tensor1d"])(array);
}
/**
* Compute minimum value.
* @param array
* @return minimum value.
*/
function min(array) {
return dist["min"](toArray1D(array)).dataSync()[0];
}
/**
* Compute maximum value.
* @param array
* @return maximum value
*/
function max(array) {
return dist["max"](toArray1D(array)).dataSync()[0];
}
/**
* Compute sum of array.
* @param array
* @return The sum.
*/
function sum(array) {
return dist["sum"](toArray1D(array)).dataSync()[0];
}
/**
* Compute mean of array.
* @param array
* @return The mean.
*/
function math_utils_mean(array) {
return sum(array) / array.length;
}
/**
* Compute variance of array.
* @param array
* @return The variance.
*/
function math_utils_variance(array) {
const demeaned = dist["sub"](
toArray1D(array),
Object(dist["scalar"])(math_utils_mean(array))
);
const sumSquare = dist["sum"](dist["mul"](demeaned, demeaned)).dataSync()[0];
return sumSquare / array.length;
}
/**
* Compute median of array.
* @param array
* @return The median value.
*/
function median(array) {
const arraySorted = array.slice().sort((a, b) => a - b);
const lowIdx = Math.floor((arraySorted.length - 1) / 2);
const highIdx = Math.ceil((arraySorted.length - 1) / 2);
if (lowIdx === highIdx) {
return arraySorted[lowIdx];
}
return (arraySorted[lowIdx] + arraySorted[highIdx]) / 2;
}
/**
* Generate an array of integers in [begin, end).
* @param begin Beginning integer, inclusive.
* @param end Ending integer, exclusive.
* @returns Range array.
* @throws ValueError, iff `end` < `begin`.
*/
function range(begin, end) {
if (end < begin) {
throw new ValueError(`end (${end}) < begin (${begin}) is forbidden.`);
}
const out = [];
for (let i = begin; i < end; ++i) {
out.push(i);
}
return out;
}
//# sourceMappingURL=math_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/backend/tfjs_backend.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* deeplearn.js backend.
*/
// tslint:enable
/* Setting and getting backend from deeplearn.js. */
// Default deeplearn.js backend is WebGL (GPU).
let backend = "webgl";
function setBackend(requestedBackend) {
dist["setBackend"](requestedBackend);
backend = requestedBackend;
}
function getBackend() {
return backend;
}
/**
* Indicates whether the backend is operating symbolically.
*
* This function will be used to determine how to interpret user code. If
* it returns true, calls to the backend construct a symbolic graph; if
* it returns false, calls to the backend execute immediately.
*/
function isBackendSymbolic() {
return false;
}
/**
* Get the number of elements in a Tensor.
* @param x The Tensor.
* @return Number of elements in `x`.
*/
function countParams(x) {
const shape = x.shape;
if (shape.length > 0) {
return shape.reduce((a, b) => a * b);
} else {
// Scalar.
return 1;
}
}
/**
* Casts a tensor to a different dtype and returns it.
* @param x Input tensor.
* @param dtype String: 'float32'|'int32'|'bool'.
* @returns Tensor of the specified `dtype`.
*/
function cast(x, dtype) {
return x.asType(dtype);
}
/**
* Adds a 1-sized dimension at index "axis".
* @param x Input tensor.
* @param axis Position where to add the new axis.
* @returns Result of the dimension expansion.
*/
function expandDims(x, axis = -1) {
const outShape = x.shape.slice();
if (axis < 0) {
axis = outShape.length + axis + 1;
}
outShape.splice(axis, 0, 1);
return x.reshape(outShape);
}
/**
* Repeats a 2D tensor.
*
* If `x` has shape `[samples, dim]` and `n` is 2, for example, the output
* will have shape `[samples, 2, dim]`.
*
* @param x Input tensor.
* @param n Integer, number of times to repeat.
* @returns The result of the repeat operation.
* @throws ValueError: If input tensor is not 2D.
*/
function repeat(x, n) {
return Object(dist["tidy"])(() => {
if (x.shape.length !== 2) {
throw new ValueError(
`repeat() expects a rank-2 tensor, but received a ` + `rank-${x.shape.length} tensor.`
);
}
const y = expandDims(x, 1);
return tile(y, [1, n, 1]);
});
}
/**
* Flatten a Tensor into 1D.
* @param x Input tensor.
* @return The result of the flattening `x`.
*/
function flatten(x) {
const newShape = [arrayProd(x.shape)];
return x.reshape(newShape);
}
/**
* Turn a nD tensor into a 2D tensor with same 0th dimension.
* In other words, it flattens each data samples of a batch.
*
* @param x The tensor to flatten. The rank of this tensor is required to be 2
* or higher.
* @return The result of the flattening.
*/
function batchFlatten(x) {
if (x.rank <= 1) {
throw new ValueError(`batchFlatten requires a minimum rank of 2. Got rank: ${x.rank}.`);
}
const newShape = [x.shape[0], arrayProd(x.shape, 1)];
return x.reshape(newShape);
}
/**
* Do slicing along the first axis.
* @param array input `tf.Tensor`.
* @param start starting index, inclusive.
* @param size size of the slice along the first axis.
* @returns result of the slicing.
* @throws ValueError: If `array` is of an unsupported subtype of `tf.Tensor`.
*/
function sliceAlongFirstAxis(array, start, size) {
return Object(dist["tidy"])(() => {
switch (array.rank) {
case 1:
return dist["slice1d"](array, start, size);
case 2:
return dist["slice2d"](array, [start, 0], [size, array.shape[1]]);
case 3:
return dist["slice3d"](array, [start, 0, 0], [size, array.shape[1], array.shape[2]]);
case 4:
return dist["slice4d"](
array,
[start, 0, 0, 0],
[size, array.shape[1], array.shape[2], array.shape[3]]
);
case 5:
return dist["slice"](
array,
[start, 0, 0, 0, 0],
[size, array.shape[1], array.shape[2], array.shape[3], array.shape[4]]
);
case 6:
return dist["slice"](
array,
[start, 0, 0, 0, 0, 0],
[
size,
array.shape[1],
array.shape[2],
array.shape[3],
array.shape[4],
array.shape[5],
]
);
default:
throw new ValueError(
`sliceAlongFirstAxis() received an unsupported tensor rank: ` + `${array.rank}`
);
}
});
}
/**
* Do slicing along the last axis.
* @param array input `tf.Tensor`.
* @param start starting index, inclusive.
* @param size size of the slice along the last axis.
* @returns result of the slicing.
* @throws ValueError: If `array` is of an unsupported subtype of `tf.Tensor`.
*/
function sliceAlongLastAxis(array, start, size) {
return Object(dist["tidy"])(() => {
switch (array.rank) {
case 1:
return dist["slice1d"](array, start, size);
case 2:
return dist["slice2d"](array, [0, start], [array.shape[0], size]);
case 3:
return dist["slice3d"](array, [0, 0, start], [array.shape[0], array.shape[1], size]);
case 4:
return dist["slice4d"](
array,
[0, 0, 0, start],
[array.shape[0], array.shape[1], array.shape[2], size]
);
default:
throw new ValueError(
`sliceAlongLastAxis() received an unsupported tensor rank: ` + `${array.rank}`
);
}
});
}
/**
* Do slicing along the sepcified axis.
* @param array input `tf.Tensor`.
* @param start starting index, inclusive.
* @param size of the slice along the chosen axis.
* @param choose an axis.
* @returns result of the slicing.
* @throws ValueError: If `array` is of an unsupported subtype of `tf.Tensor`.
*/
function sliceAlongAxis(array, start, size, axis) {
return Object(dist["tidy"])(() => {
switch (array.rank) {
case 1:
return dist["slice1d"](array, start, size);
case 2:
switch (axis) {
case 1:
return sliceAlongFirstAxis(array, start, size);
case 2:
return sliceAlongLastAxis(array, start, size);
default:
throw new ValueError(
`The axis is not within the rank of the tensor ` + `${axis}`
);
}
case 3:
switch (axis) {
case 1:
return sliceAlongFirstAxis(array, start, size);
case 2:
return dist["slice3d"](
array,
[0, start, 0],
[array.shape[0], size, array.shape[2]]
);
case 3:
return sliceAlongLastAxis(array, start, size);
default:
throw new ValueError(
`The axis is not within the rank of the tensor ` + `${axis}`
);
}
case 4:
switch (axis) {
case 1:
return sliceAlongFirstAxis(array, start, size);
case 2:
return dist["slice4d"](
array,
[0, start, 0, 0],
[array.shape[0], size, array.shape[2], array.shape[3]]
);
case 3:
return dist["slice4d"](
array,
[0, 0, start, 0],
[array.shape[0], array.shape[1], size, array.shape[3]]
);
case 4:
return sliceAlongLastAxis(array, start, size);
default:
throw new ValueError(
`The axis is not within the rank of the tensor ` + `${axis}`
);
}
default:
throw new ValueError(
`sliceAlongLastAxis() received an unsupported tensor rank: ` + `${array.rank}`
);
}
});
}
/**
* Concatenates a list of tensors alongside the specified axis.
* @param tensors `Array` of tensors to concatenate.
* @param axis Concatenation axis.
* @returns The result of the concatenation.
*/
function concatenate(tensors, axis = -1) {
let rank;
if (axis < 0) {
rank = tensors[0].rank;
if (rank !== 0) {
axis = rank;
} else {
axis = 0;
}
}
if (axis === tensors[0].rank) {
// Porting Note: This is necessary because tfc.concat() requires axis to be
// in the interval [-rank, rank).
axis = -1;
}
// Porting Note: Sparse concat is not supported yet.
return dist["concat"](tensors, axis);
}
/**
* Concatenate two arrays along the first dimension.
* @param a The 1st `tf.Tensor` to concatenate.
* @param b The 2nd `tf.Tensor` to concatenate.
* @returns Result of the concatenation.
* @throws ValueError: If `a` is of an unsupported subtype of `tf.Tensor`.
*/
function concatAlongFirstAxis(a, b) {
switch (a.rank) {
case 1:
return dist["concat1d"]([a, b]);
case 2:
return dist["concat2d"]([a, b], 0);
case 3:
return dist["concat3d"]([a, b], 0);
case 4:
return dist["concat4d"]([a, b], 0);
default:
throw new ValueError(
`concatAlongFirstAxis() received an unsupported ` + `tensor rank: ${a.rank}`
);
}
}
/**
* Creates a tensor by tiling `x` by `n`.
* @param x A tensor.
* @param n An Array of integers or a single integer. If an Array, the length
* must be the same as the number of dimensions in `x`. If a single integer,
* it will be treated as an Array of length 1.
*/
function tile(x, n) {
if (!Array.isArray(n)) {
n = [n];
}
if (x.rank !== n.length) {
throw new ValueError(
`The length of input n (${n.length}) does not match ` +
`the number of dimensions in input x (${x.rank})`
);
}
return dist["tile"](x, n);
}
/* Creation of random tensors. */
/**
* Get a tensor with normal distribution of values.
*
* @param shape Shape of the tensor.
* @param mean mean value of the normal distribution.
* @param stddev standard deviation of the normal distribution.
* @param dtype
* @param seed
* @return The normal tensor.
*/
function randomNormal(shape, mean = 0.0, stddev = 1.0, dtype, seed) {
return dist["randomNormal"](shape, mean, stddev, dtype, seed);
}
/* Linear Algebra */
/**
* Multiply two tensors and returns the result as a tensor.
*
* For 2D tensors, this is equivalent to matrix multiplication (matMul).
* For tensors of higher ranks, it follows the Theano behavior,
* (e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`). From the Theano documentation:
*
* For N dimensions it is a sum product over the last axis of x and the
* second-to-last of y:
*
* @param a A tensor of at least rank 2.
* @param b A tensor of at least rank 2.
* @param activation (optional) A string identifying the activation
* function.
* @return Result of the dot operation.
*/
function dot(a, b, activation, bias) {
if (a.rank < 2 || b.rank < 2) {
throw new NotImplementedError(
`dot requires both inputs to be rank >= 2` +
` but got x shape = ${a.shape} and y shape = ${b.shape}`
);
}
if (b.rank >= 3) {
const xLastDim = a.shape.slice(-1)[0];
const ySecondLastDim = b.shape.slice(-2)[0];
if (xLastDim !== ySecondLastDim) {
throw new NotImplementedError(
`If rank y >= 3, then the second last dim` +
` of y must equal the last dim of x but got x shape = ${a.shape} and ` +
` y shape = ${b.shape}`
);
}
}
// Handle basic 2D x 2D case.
if (a.rank === 2 && b.rank === 2) {
const transposeA = false;
const transposeB = false;
// tfc.fused.matMul only fuses certain activation functions. Unsupported
// activation functions are treated as 'linear' activations, which is
// equivalent to a no-op.
return dist["fused"].matMul({
a,
b: b,
transposeA,
transposeB,
bias: bias ? reshapeBias(a.rank, bias, imageDataFormat()) : null,
activation,
});
} else {
// Reshape x into the analogous 2D Tensor.
const aFirstDims = a.shape.slice(); // Holds all but the last dim of x.
const aLastDim = aFirstDims.pop();
a = a.reshape([-1, aLastDim]);
// Reshape y into the analogous 2D Tensor, and keep track of the
// required dimensions to reproduce the output shape.
const bShape = b.shape.slice();
const bLastDim = bShape.pop();
const ySecondLastDim = bShape.pop();
const yOtherDims = [...bShape, bLastDim];
// permutation should be like [r-2, 0, 1, 2, ... r-4, r-3, r-1]
// where r is the rank of y.
const perm = Array.from({ length: b.rank }, (_, i) => {
if (i === 0) {
return b.rank - 2;
} else if (i <= b.rank - 2) {
return i - 1;
}
return i;
});
b = b.transpose(perm).reshape([ySecondLastDim, -1]);
// Multiply x and y as 2D Tensors, and then reshape back to original.
const outputShape = [...aFirstDims, ...yOtherDims];
const transposeA = false;
const transposeB = false;
return dist["fused"]
.matMul({
a,
b,
transposeA,
transposeB,
bias: bias ? reshapeBias(a.rank, bias, imageDataFormat()) : null,
activation,
})
.reshape(outputShape);
}
}
/**
* Compute the sign Tensor of an input Tensor.
*
* Elements of the input `tf.Tensor` that are === 0 are mapped to 0.
* Elements of the input `tf.Tensor` that are > 0 are mapped to 1.
* Elements of the input `tf.Tensor` that are < 0 are mapped to -1.
*
* @param x Input `tf.Tensor`.
* @return The sign `tf.Tensor`.
*/
function sign(x) {
// TODO(cais): Move to the core.
return Object(dist["tidy"])(() => {
const zerosLikeX = Object(dist["zerosLike"])(x);
const onesLikeX = Object(dist["onesLike"])(x);
return Object(dist["where"])(
dist["equal"](x, zerosLikeX),
zerosLikeX,
Object(dist["where"])(
dist["greater"](x, Object(dist["zerosLike"])(x)),
onesLikeX,
dist["mul"](-1, onesLikeX)
)
);
});
}
/**
* Computes the one-hot representation of an integer tensor.
* @param indices nD integer tensor of shape
* `(batch_size, dim1, dim2, ... dim(n-1))`
* @param numClasses Integer, number of classes to consider.
* @returns (n + 1)D one hot representation of the input
* with shape `(batch_size, dim1, dim2, ... dim(n-1), num_classes)`
*/
function oneHot(indices, numClasses) {
return Object(dist["tidy"])(() => {
if (indices.rank !== 1) {
throw new Error(
"Only 1D one-hot tensors are supported in the " + "deeplearn backend, at present."
);
}
indices = indices.toInt();
return dist["oneHot"](indices, numClasses).toFloat();
});
}
/* Elementary math functions. */
/**
* Retrieves the elements of indices `indices` in the tensor `reference`.
* @param reference A tensor.
* @param indices An integer tensor of indices or an `Array` of integers.
* @param axis Axis along which to perform the gather operation.
* @returns The result of the gathering as a tensor.
*/
function gather(reference, indices, axis) {
return Object(dist["tidy"])(() => {
if (Array.isArray(indices)) {
indices = Object(dist["tensor1d"])(indices, "int32");
} else {
indices = indices.toInt();
}
return dist["gather"](reference, indices, axis);
});
}
/**
* Element-wise square.
* @param x Input tensor.
* @return element-wise x^2
*/
function square(x) {
return dist["mul"](x, x);
}
/**
* Element-wise exponentiation.
*
* Porting Note: In PyKeras, `a` (the exponent) is a Python integer, which
* takes advatnage of the backend's (e.g., TensorFlow's) automatic
* conversion to tensor. Here we allow `a` to be either a number or a tensor.
*
* @param x The base tensor.
* @param a The exponent, tensor or number. If a number, it is rounded to the
* nearest integer and converted to a tensor.
* @returns A tensor of the same shape as `x`.
*/
function pow(x, a) {
return Object(dist["tidy"])(() => {
if (typeof a === "number") {
a = Object(dist["scalar"])(Math.round(a), "int32");
}
if (a.dtype !== "int32") {
throw new NotImplementedError(
`Non-int32 dtype (${a.dtype}) is not supported by pow() yet`
);
}
return dist["pow"](x, a);
});
}
/**
* Reshapes bias tensor according to rank of x.
*/
function reshapeBias(xRank, bias, dataFormat) {
const biasShape = bias.shape;
if (bias.rank !== 1 && bias.rank !== xRank) {
throw new ValueError(
`Unexpected bias dimensions: ${bias.rank}` + `; expected it to be 1 or ${xRank}`
);
}
if (xRank === 5) {
if (dataFormat === "channelsFirst") {
if (biasShape.length === 1) {
return bias.reshape([1, biasShape[0], 1, 1, 1]);
} else {
return bias.reshape([1, biasShape[3], biasShape[0], biasShape[1], biasShape[2]]);
}
} else if (dataFormat === "channelsLast") {
if (biasShape.length === 1) {
return bias.reshape([1, 1, 1, 1, biasShape[0]]);
} else {
return bias.reshape([1].concat(biasShape));
}
}
} else if (xRank === 4) {
if (dataFormat === "channelsFirst") {
if (biasShape.length === 1) {
return bias.reshape([1, biasShape[0], 1, 1]);
} else {
return bias.reshape([1, biasShape[2], biasShape[0], biasShape[1]]);
}
} else if (dataFormat === "channelsLast") {
if (biasShape.length === 1) {
return bias.reshape([1, 1, 1, biasShape[0]]);
} else {
return bias.reshape([1].concat(biasShape));
}
}
} else if (xRank === 3) {
if (dataFormat === "channelsFirst") {
if (biasShape.length === 1) {
return bias.reshape([1, biasShape[0], 1]);
} else {
return bias.reshape([1, biasShape[1], biasShape[0]]);
}
} else if (dataFormat === "channelsLast") {
if (biasShape.length === 1) {
return bias.reshape([1, 1, biasShape[0]]);
} else {
return bias.reshape([1].concat(biasShape));
}
}
} else if (xRank < 3) {
return bias;
}
throw new ValueError(`Unsupported input rank by biasAdd: ${bias.rank}`);
}
/* Neural-network operations. */
/**
* Add a bias to a tensor.
*
* @param x The tensor to add the bias to.
* @param bias The bias to add to `x`. Must be 1D or the same rank as `x`.
* @return Result of the bias adding.
* @throws ValueError: If the rank of `bias` is incorrect.
*/
function biasAdd(x, bias, dataFormat) {
return Object(dist["tidy"])(() => {
if (dataFormat == null) {
dataFormat = imageDataFormat();
}
checkDataFormat(dataFormat);
return x.add(reshapeBias(x.rank, bias, dataFormat));
});
}
/**
* Exponential linear unit (ELU).
* @param x A tensor or variable to compute the activation function for.
* @param alpha: A scalar, a scaling factor for the negative section.
* @return Output of the ELU operation.
*/
function elu(x, alpha = 1) {
// TODO(cais): Add support for alpha values other than 1.
if (alpha !== 1) {
throw new NotImplementedError(
`Support for alpha values other than 1 (${alpha}) is not implemented ` + `yet.`
);
}
return dist["elu"](x);
}
/**
* Softsign of a tensor.
*
* Defined as x / (abs(x) + 1), element-wise.
*
* @param x: Input.
* @returns Output.
*/
function softsign(x) {
return Object(dist["tidy"])(() => dist["div"](x, dist["abs"](x).add(1)));
}
/**
* Sets entries in `x` to zero at random, while scaling the entire tensor.
*
* @param x input tensor.
* @param level fraction of the entries in the tensor that will be set to 0.
* @param noiseShape shape of randomly generated keep/drop flags, must be
* broadcastable to the shape of `x`. Optional.
* @param seed random seed to ensure determinism. Optional.
* @returns Result of the dropout operation.
*/
function dropout(x, level, noiseShape, seed) {
return Object(dist["tidy"])(() => dist["dropout"](x, level, noiseShape, seed));
}
/**
* Element-wise, segment-wise linear approximation of sigmoid.
*
* Returns `0.` if `x < -2.5`, `1.` if `x > 2.5`.
* In `-2.5 <= x <= 2.5`, returns `0.2 * x + 0.5`.
*
* @param x Input tensor.
* @returns Output tensor.
*/
function hardSigmoid(x) {
return Object(dist["tidy"])(() => {
const y = dist["add"](0.5, dist["mul"](0.2, x));
return dist["clipByValue"](y, 0, 1);
});
}
/**
* Invoke `x` in the training phase, and `alt` otherwise.
*
* Porting Note: We do not create placeholder tensors for the `training`
* boolean flag here, because there is no such thing in the TF.js imperative
* backend.
*
* @param x The function to invoke iff `training` is `true`.
* @param alt The function to invoke iff `training` is `false`.
* @param training Boolean flag for whether training phase is active.
* @returns The return value of `x()` if `training` is `true`, or the return
* value of `alt()` if `training` is `false`.
*/
function inTrainPhase(x, alt, training = false) {
return training ? x() : alt();
}
//# sourceMappingURL=tfjs_backend.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/keras_format/initializer_config.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const VALID_FAN_MODE_VALUES = ["fanIn", "fanOut", "fanAvg"];
const VALID_DISTRIBUTION_VALUES = ["normal", "uniform", "truncatedNormal"];
// We can't easily extract a string[] from the string union type, but we can
// recapitulate the list, enforcing at compile time that the values are valid
// and that we have the right number of them.
/**
* A string array of valid Initializer class names.
*
* This is guaranteed to match the `InitializerClassName` union type.
*/
const initializerClassNames = [
"Zeros",
"Ones",
"Constant",
"RandomNormal",
"RandomUniform",
"TruncatedNormal",
"VarianceScaling",
"Orthogonal",
"Identity",
];
//# sourceMappingURL=initializer_config.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/initializers.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function checkFanMode(value) {
checkStringTypeUnionValue(VALID_FAN_MODE_VALUES, "FanMode", value);
}
function checkDistribution(value) {
checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES, "Distribution", value);
}
/**
* Initializer base class.
*
* @doc {
* heading: 'Initializers', subheading: 'Classes', namespace: 'initializers'}
*/
class initializers_Initializer extends dist["serialization"].Serializable {
fromConfigUsesCustomObjects() {
return false;
}
getConfig() {
return {};
}
}
class initializers_Zeros extends initializers_Initializer {
apply(shape, dtype) {
return Object(dist["zeros"])(shape, dtype);
}
}
/** @nocollapse */
initializers_Zeros.className = "Zeros";
dist["serialization"].registerClass(initializers_Zeros);
class initializers_Ones extends initializers_Initializer {
apply(shape, dtype) {
return Object(dist["ones"])(shape, dtype);
}
}
/** @nocollapse */
initializers_Ones.className = "Ones";
dist["serialization"].registerClass(initializers_Ones);
class initializers_Constant extends initializers_Initializer {
constructor(args) {
super();
if (typeof args !== "object") {
throw new ValueError(`Expected argument of type ConstantConfig but got ${args}`);
}
if (args.value === undefined) {
throw new ValueError(`config must have value set but got ${args}`);
}
this.value = args.value;
}
apply(shape, dtype) {
return Object(dist["tidy"])(() =>
Object(dist["mul"])(
Object(dist["scalar"])(this.value),
Object(dist["ones"])(shape, dtype)
)
);
}
getConfig() {
return {
value: this.value,
};
}
}
/** @nocollapse */
initializers_Constant.className = "Constant";
dist["serialization"].registerClass(initializers_Constant);
class initializers_RandomUniform extends initializers_Initializer {
constructor(args) {
super();
this.DEFAULT_MINVAL = -0.05;
this.DEFAULT_MAXVAL = 0.05;
this.minval = args.minval || this.DEFAULT_MINVAL;
this.maxval = args.maxval || this.DEFAULT_MAXVAL;
this.seed = args.seed;
}
apply(shape, dtype) {
return Object(dist["randomUniform"])(shape, this.minval, this.maxval, dtype);
}
getConfig() {
return { minval: this.minval, maxval: this.maxval, seed: this.seed };
}
}
/** @nocollapse */
initializers_RandomUniform.className = "RandomUniform";
dist["serialization"].registerClass(initializers_RandomUniform);
class initializers_RandomNormal extends initializers_Initializer {
constructor(args) {
super();
this.DEFAULT_MEAN = 0;
this.DEFAULT_STDDEV = 0.05;
this.mean = args.mean || this.DEFAULT_MEAN;
this.stddev = args.stddev || this.DEFAULT_STDDEV;
this.seed = args.seed;
}
apply(shape, dtype) {
dtype = dtype || "float32";
if (dtype !== "float32" && dtype !== "int32") {
throw new NotImplementedError(`randomNormal does not support dType ${dtype}.`);
}
return randomNormal(shape, this.mean, this.stddev, dtype, this.seed);
}
getConfig() {
return { mean: this.mean, stddev: this.stddev, seed: this.seed };
}
}
/** @nocollapse */
initializers_RandomNormal.className = "RandomNormal";
dist["serialization"].registerClass(initializers_RandomNormal);
class initializers_TruncatedNormal extends initializers_Initializer {
constructor(args) {
super();
this.DEFAULT_MEAN = 0;
this.DEFAULT_STDDEV = 0.05;
this.mean = args.mean || this.DEFAULT_MEAN;
this.stddev = args.stddev || this.DEFAULT_STDDEV;
this.seed = args.seed;
}
apply(shape, dtype) {
dtype = dtype || "float32";
if (dtype !== "float32" && dtype !== "int32") {
throw new NotImplementedError(`truncatedNormal does not support dType ${dtype}.`);
}
return Object(dist["truncatedNormal"])(shape, this.mean, this.stddev, dtype, this.seed);
}
getConfig() {
return { mean: this.mean, stddev: this.stddev, seed: this.seed };
}
}
/** @nocollapse */
initializers_TruncatedNormal.className = "TruncatedNormal";
dist["serialization"].registerClass(initializers_TruncatedNormal);
class initializers_Identity extends initializers_Initializer {
constructor(args) {
super();
this.gain = args.gain != null ? args.gain : 1.0;
}
apply(shape, dtype) {
return Object(dist["tidy"])(() => {
if (shape.length !== 2 || shape[0] !== shape[1]) {
throw new ValueError(
"Identity matrix initializer can only be used for" + " 2D square matrices."
);
} else {
return Object(dist["mul"])(this.gain, Object(dist["eye"])(shape[0]));
}
});
}
getConfig() {
return { gain: this.gain };
}
}
/** @nocollapse */
initializers_Identity.className = "Identity";
dist["serialization"].registerClass(initializers_Identity);
/**
* Computes the number of input and output units for a weight shape.
* @param shape Shape of weight.
* @param dataFormat data format to use for convolution kernels.
* Note that all kernels in Keras are standardized on the
* CHANNEL_LAST ordering (even when inputs are set to CHANNEL_FIRST).
* @return An length-2 array: fanIn, fanOut.
*/
function computeFans(shape, dataFormat = "channelsLast") {
let fanIn;
let fanOut;
checkDataFormat(dataFormat);
if (shape.length === 2) {
fanIn = shape[0];
fanOut = shape[1];
} else if ([3, 4, 5].indexOf(shape.length) !== -1) {
if (dataFormat === "channelsFirst") {
const receptiveFieldSize = arrayProd(shape, 2);
fanIn = shape[1] * receptiveFieldSize;
fanOut = shape[0] * receptiveFieldSize;
} else if (dataFormat === "channelsLast") {
const receptiveFieldSize = arrayProd(shape, 0, shape.length - 2);
fanIn = shape[shape.length - 2] * receptiveFieldSize;
fanOut = shape[shape.length - 1] * receptiveFieldSize;
}
} else {
const shapeProd = arrayProd(shape);
fanIn = Math.sqrt(shapeProd);
fanOut = Math.sqrt(shapeProd);
}
return [fanIn, fanOut];
}
class initializers_VarianceScaling extends initializers_Initializer {
/**
* Constructor of VarianceScaling.
* @throws ValueError for invalid value in scale.
*/
constructor(args) {
super();
if (args.scale < 0.0) {
throw new ValueError(`scale must be a positive float. Got: ${args.scale}`);
}
this.scale = args.scale == null ? 1.0 : args.scale;
this.mode = args.mode == null ? "fanIn" : args.mode;
checkFanMode(this.mode);
this.distribution = args.distribution == null ? "normal" : args.distribution;
checkDistribution(this.distribution);
this.seed = args.seed;
}
apply(shape, dtype) {
const fans = computeFans(shape);
const fanIn = fans[0];
const fanOut = fans[1];
let scale = this.scale;
if (this.mode === "fanIn") {
scale /= Math.max(1, fanIn);
} else if (this.mode === "fanOut") {
scale /= Math.max(1, fanOut);
} else {
scale /= Math.max(1, (fanIn + fanOut) / 2);
}
if (this.distribution === "normal") {
const stddev = Math.sqrt(scale);
dtype = dtype || "float32";
if (dtype !== "float32" && dtype !== "int32") {
throw new NotImplementedError(
`${this.getClassName()} does not support dType ${dtype}.`
);
}
return Object(dist["truncatedNormal"])(shape, 0, stddev, dtype, this.seed);
} else {
const limit = Math.sqrt(3 * scale);
return Object(dist["randomUniform"])(shape, -limit, limit, dtype);
}
}
getConfig() {
return {
scale: this.scale,
mode: this.mode,
distribution: this.distribution,
seed: this.seed,
};
}
}
/** @nocollapse */
initializers_VarianceScaling.className = "VarianceScaling";
dist["serialization"].registerClass(initializers_VarianceScaling);
class GlorotUniform extends initializers_VarianceScaling {
/**
* Constructor of GlorotUniform
* @param scale
* @param mode
* @param distribution
* @param seed
*/
constructor(args) {
super({
scale: 1.0,
mode: "fanAvg",
distribution: "uniform",
seed: args == null ? null : args.seed,
});
}
getClassName() {
// In Python Keras, GlorotUniform is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return initializers_VarianceScaling.className;
}
}
/** @nocollapse */
GlorotUniform.className = "GlorotUniform";
dist["serialization"].registerClass(GlorotUniform);
class GlorotNormal extends initializers_VarianceScaling {
/**
* Constructor of GlorotNormal.
* @param scale
* @param mode
* @param distribution
* @param seed
*/
constructor(args) {
super({
scale: 1.0,
mode: "fanAvg",
distribution: "normal",
seed: args == null ? null : args.seed,
});
}
getClassName() {
// In Python Keras, GlorotNormal is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return initializers_VarianceScaling.className;
}
}
/** @nocollapse */
GlorotNormal.className = "GlorotNormal";
dist["serialization"].registerClass(GlorotNormal);
class HeNormal extends initializers_VarianceScaling {
constructor(args) {
super({
scale: 2.0,
mode: "fanIn",
distribution: "normal",
seed: args == null ? null : args.seed,
});
}
getClassName() {
// In Python Keras, HeNormal is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return initializers_VarianceScaling.className;
}
}
/** @nocollapse */
HeNormal.className = "HeNormal";
dist["serialization"].registerClass(HeNormal);
class HeUniform extends initializers_VarianceScaling {
constructor(args) {
super({
scale: 2.0,
mode: "fanIn",
distribution: "uniform",
seed: args == null ? null : args.seed,
});
}
getClassName() {
// In Python Keras, HeUniform is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return initializers_VarianceScaling.className;
}
}
/** @nocollapse */
HeUniform.className = "HeUniform";
dist["serialization"].registerClass(HeUniform);
class LeCunNormal extends initializers_VarianceScaling {
constructor(args) {
super({
scale: 1.0,
mode: "fanIn",
distribution: "normal",
seed: args == null ? null : args.seed,
});
}
getClassName() {
// In Python Keras, LeCunNormal is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return initializers_VarianceScaling.className;
}
}
/** @nocollapse */
LeCunNormal.className = "LeCunNormal";
dist["serialization"].registerClass(LeCunNormal);
class LeCunUniform extends initializers_VarianceScaling {
constructor(args) {
super({
scale: 1.0,
mode: "fanIn",
distribution: "uniform",
seed: args == null ? null : args.seed,
});
}
getClassName() {
// In Python Keras, LeCunUniform is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return initializers_VarianceScaling.className;
}
}
/** @nocollapse */
LeCunUniform.className = "LeCunNormal";
dist["serialization"].registerClass(LeCunUniform);
class initializers_Orthogonal extends initializers_Initializer {
constructor(args) {
super();
this.DEFAULT_GAIN = 1;
this.gain = args.gain == null ? this.DEFAULT_GAIN : args.gain;
this.seed = args.seed;
if (this.seed != null) {
throw new NotImplementedError(
"Random seed is not implemented for Orthogonal Initializer yet."
);
}
}
apply(shape, dtype) {
return Object(dist["tidy"])(() => {
if (shape.length !== 2) {
throw new NotImplementedError(
"The Orthogonal Initializer does not support non-2D shapes yet."
);
}
if (shape[0] * shape[1] > 2000) {
console.warn(
`Orthogonal initializer is being called on a matrix with more ` +
`than 2000 (${shape[0] * shape[1]}) elements: ` +
`Slowness may result.`
);
}
// TODO(cais): Add seed support.
const normalizedShape = shape[0] > shape[1] ? [shape[1], shape[0]] : shape;
const a = randomNormal(normalizedShape, 0, 1, "float32");
let q = dist["linalg"].gramSchmidt(a);
if (shape[0] > shape[1]) {
q = q.transpose();
}
return Object(dist["mul"])(this.gain, q);
});
}
getConfig() {
return {
gain: this.gain,
seed: this.seed,
};
}
}
/** @nocollapse */
initializers_Orthogonal.className = "Orthogonal";
dist["serialization"].registerClass(initializers_Orthogonal);
// Maps the JavaScript-like identifier keys to the corresponding registry
// symbols.
const INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
constant: "Constant",
glorotNormal: "GlorotNormal",
glorotUniform: "GlorotUniform",
heNormal: "HeNormal",
heUniform: "HeUniform",
identity: "Identity",
leCunNormal: "LeCunNormal",
leCunUniform: "LeCunUniform",
ones: "Ones",
orthogonal: "Orthogonal",
randomNormal: "RandomNormal",
randomUniform: "RandomUniform",
truncatedNormal: "TruncatedNormal",
varianceScaling: "VarianceScaling",
zeros: "Zeros",
};
function deserializeInitializer(config, customObjects = {}) {
return deserializeKerasObject(
config,
dist["serialization"].SerializationMap.getMap().classNameMap,
customObjects,
"initializer"
);
}
function serializeInitializer(initializer) {
return serializeKerasObject(initializer);
}
function getInitializer(identifier) {
if (typeof identifier === "string") {
const className =
identifier in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP
? INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier]
: identifier;
/* We have four 'helper' classes for common initializers that
all get serialized as 'VarianceScaling' and shouldn't go through
the deserializeInitializer pathway. */
if (className === "GlorotNormal") {
return new GlorotNormal();
} else if (className === "GlorotUniform") {
return new GlorotUniform();
} else if (className === "HeNormal") {
return new HeNormal();
} else if (className === "HeUniform") {
return new HeUniform();
} else if (className === "LeCunNormal") {
return new LeCunNormal();
} else if (className === "LeCunUniform") {
return new LeCunUniform();
} else {
const config = {};
config["className"] = className;
config["config"] = {};
return deserializeInitializer(config);
}
} else if (identifier instanceof initializers_Initializer) {
return identifier;
} else {
return deserializeInitializer(identifier);
}
}
//# sourceMappingURL=initializers.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/exports_initializers.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// tslint:disable-next-line:max-line-length
/**
* Initializer that generates tensors initialized to 0.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function zeros() {
return new initializers_Zeros();
}
/**
* Initializer that generates tensors initialized to 1.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function exports_initializers_ones() {
return new initializers_Ones();
}
/**
* Initializer that generates values initialized to some constant.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function constant(args) {
return new initializers_Constant(args);
}
/**
* Initializer that generates random values initialized to a uniform
* distribution.
*
* Values will be distributed uniformly between the configured minval and
* maxval.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function randomUniform(args) {
return new initializers_RandomUniform(args);
}
/**
* Initializer that generates random values initialized to a normal
* distribution.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function exports_initializers_randomNormal(args) {
return new initializers_RandomNormal(args);
}
/**
* Initializer that generates random values initialized to a truncated normal.
* distribution.
*
* These values are similar to values from a `RandomNormal` except that values
* more than two standard deviations from the mean are discarded and re-drawn.
* This is the recommended initializer for neural network weights and filters.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function truncatedNormal(args) {
return new initializers_TruncatedNormal(args);
}
/**
* Initializer that generates the identity matrix.
* Only use for square 2D matrices.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function identity(args) {
return new initializers_Identity(args);
}
/**
* Initializer capable of adapting its scale to the shape of weights.
* With distribution=NORMAL, samples are drawn from a truncated normal
* distribution centered on zero, with `stddev = sqrt(scale / n)` where n is:
* - number of input units in the weight tensor, if mode = FAN_IN.
* - number of output units, if mode = FAN_OUT.
* - average of the numbers of input and output units, if mode = FAN_AVG.
* With distribution=UNIFORM,
* samples are drawn from a uniform distribution
* within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
*/
/** @doc {heading: 'Initializers',namespace: 'initializers'} */
function varianceScaling(config) {
return new initializers_VarianceScaling(config);
}
/**
* Glorot uniform initializer, also called Xavier uniform initializer.
* It draws samples from a uniform distribution within [-limit, limit]
* where `limit` is `sqrt(6 / (fan_in + fan_out))`
* where `fan_in` is the number of input units in the weight tensor
* and `fan_out` is the number of output units in the weight tensor
*
* Reference:
* Glorot & Bengio, AISTATS 2010
* http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function glorotUniform(args) {
return new GlorotUniform(args);
}
/**
* Glorot normal initializer, also called Xavier normal initializer.
* It draws samples from a truncated normal distribution centered on 0
* with `stddev = sqrt(2 / (fan_in + fan_out))`
* where `fan_in` is the number of input units in the weight tensor
* and `fan_out` is the number of output units in the weight tensor.
*
* Reference:
* Glorot & Bengio, AISTATS 2010
* http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function glorotNormal(args) {
return new GlorotNormal(args);
}
/**
* He normal initializer.
*
* It draws samples from a truncated normal distribution centered on 0
* with `stddev = sqrt(2 / fanIn)`
* where `fanIn` is the number of input units in the weight tensor.
*
* Reference:
* He et al., http://arxiv.org/abs/1502.01852
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function heNormal(args) {
return new HeNormal(args);
}
/**
* He uniform initializer.
*
* It draws samples from a uniform distribution within [-limit, limit]
* where `limit` is `sqrt(6 / fan_in)`
* where `fanIn` is the number of input units in the weight tensor.
*
* Reference:
* He et al., http://arxiv.org/abs/1502.01852
*/
/** @doc {heading: 'Initializers',namespace: 'initializers'} */
function heUniform(args) {
return new HeUniform(args);
}
/**
* LeCun normal initializer.
*
* It draws samples from a truncated normal distribution centered on 0
* with `stddev = sqrt(1 / fanIn)`
* where `fanIn` is the number of input units in the weight tensor.
*
* References:
* [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
* [Efficient Backprop](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function leCunNormal(args) {
return new LeCunNormal(args);
}
/**
* LeCun uniform initializer.
*
* It draws samples from a uniform distribution in the interval
* `[-limit, limit]` with `limit = sqrt(3 / fanIn)`,
* where `fanIn` is the number of input units in the weight tensor.
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function leCunUniform(args) {
return new LeCunUniform(args);
}
/**
* Initializer that generates a random orthogonal matrix.
*
* Reference:
* [Saxe et al., http://arxiv.org/abs/1312.6120](http://arxiv.org/abs/1312.6120)
*/
/** @doc {heading: 'Initializers', namespace: 'initializers'} */
function orthogonal(args) {
return new initializers_Orthogonal(args);
}
//# sourceMappingURL=exports_initializers.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/backend/state.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Utilities related to persistent state in the backend.
*/
/**
* An ID to track `tf.SymbolicTensor`s and derived classes.
* Required in different places in engine/topology.ts to identify unique
* tensors.
*/
let _nextUniqueTensorId = 0;
function getNextUniqueTensorId() {
return _nextUniqueTensorId++;
}
const _uidPrefixes = {};
/**
* Provides a unique UID given a string prefix.
*
* @param prefix
*/
function getUid(prefix = "") {
if (!(prefix in _uidPrefixes)) {
_uidPrefixes[prefix] = 0;
}
_uidPrefixes[prefix] += 1;
return prefix + _uidPrefixes[prefix].toString();
}
//# sourceMappingURL=state.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/utils/types_utils.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// tslint:enable
/**
* Determine whether the input is an Array of Shapes.
*/
function isArrayOfShapes(x) {
return Array.isArray(x) && Array.isArray(x[0]);
}
/**
* Special case of normalizing shapes to lists.
*
* @param x A shape or list of shapes to normalize into a list of Shapes.
* @return A list of Shapes.
*/
function normalizeShapeList(x) {
if (x.length === 0) {
return [];
}
if (!Array.isArray(x[0])) {
return [x];
}
return x;
}
/**
* Helper function to obtain exactly one Tensor.
* @param xs: A single `tf.Tensor` or an `Array` of `tf.Tensor`s.
* @return A single `tf.Tensor`. If `xs` is an `Array`, return the first one.
* @throws ValueError: If `xs` is an `Array` and its length is not 1.
*/
function getExactlyOneTensor(xs) {
let x;
if (Array.isArray(xs)) {
if (xs.length !== 1) {
throw new ValueError(`Expected Tensor length to be 1; got ${xs.length}`);
}
x = xs[0];
} else {
x = xs;
}
return x;
}
/**
* Helper function to obtain exactly on instance of Shape.
*
* @param shapes Input single `Shape` or Array of `Shape`s.
* @returns If input is a single `Shape`, return it unchanged. If the input is
* an `Array` containing exactly one instance of `Shape`, return the instance.
* Otherwise, throw a `ValueError`.
* @throws ValueError: If input is an `Array` of `Shape`s, and its length is not
* 1.
*/
function getExactlyOneShape(shapes) {
if (Array.isArray(shapes) && Array.isArray(shapes[0])) {
if (shapes.length === 1) {
shapes = shapes;
return shapes[0];
} else {
throw new ValueError(`Expected exactly 1 Shape; got ${shapes.length}`);
}
} else {
return shapes;
}
}
//# sourceMappingURL=types_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/utils/variable_utils.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Count the elements in an Array of LayerVariables.
*
* @param weights: The LayerVariables of which the constituent numbers are to
* be counted.
* @returns A count of the elements in all the LayerVariables
*/
function countParamsInWeights(weights) {
let count = 0;
for (const weight of weights) {
if (weight.shape.length === 0) {
count += 1;
} else {
count += weight.shape.reduce((a, b) => a * b);
}
}
return count;
}
//# sourceMappingURL=variable_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/variables.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const DEFAULT_VARIABLE_NAME_PREFIX = "Variable";
/**
* A `tf.layers.LayerVariable` is similar to a `tf.Tensor` in that it has a
* dtype and shape, but its value is mutable. The value is itself represented
* as a`tf.Tensor`, and can be read with the `read()` method and updated with
* the `write()` method.
*/
class variables_LayerVariable {
/**
* Construct Variable from a `tf.Tensor`.
*
* If not explicitly named, the Variable will be given a name with the
* prefix 'Variable'. Variable names are unique. In the case of name
* collision, suffixies '_<num>' will be added to the name.
*
* @param val Initial value of the Variable.
* @param name Name of the variable. If `null` or `undefined` is provided, it
* will default a name with the prefix 'Variable'.
* @param constraint Optional, projection function to be applied to the
* variable after optimize updates
* @throws ValueError if `name` is `null` or `undefined`.
*/
constructor(
val,
dtype = "float32",
name = DEFAULT_VARIABLE_NAME_PREFIX,
trainable = true,
constraint = null
) {
this.dtype = dtype == null ? "float32" : dtype;
this.shape = val.shape;
this.id = getNextUniqueTensorId();
name = name == null ? DEFAULT_VARIABLE_NAME_PREFIX : name;
this.originalName = getScopedTensorName(name);
this.name = getUniqueTensorName(this.originalName);
this.trainable_ = trainable;
this.constraint = constraint;
this.val = dist["variable"](val, this.trainable_, this.name, this.dtype);
}
/**
* Get a snapshot of the Variable's value.
*
* The returned value is a snapshot of the Variable's value at the time of
* the invocation. Future mutations in the value of the tensor will only
* be reflected by future calls to this method.
*/
read() {
this.assertNotDisposed();
return this.val;
}
/**
* Update the value of the Variable.
*
* @param newVal: The new value to update to. Must be consistent with the
* dtype and shape of the Variable.
* @return This Variable.
*/
write(newVal) {
// TODO(cais): Once TF.js Core supports Tensor.dtype, check dtype match.
this.assertNotDisposed();
checkShapesMatch(this.val, newVal);
// Skip updating if this is the exact same tensor.
if (this.val.id !== newVal.id) {
this.val.assign(newVal);
if (this.constraint != null) {
this.val.assign(this.constraint.apply(this.val));
}
}
return this;
}
/**
* Dispose this LayersVariable instance from memory.
*/
dispose() {
this.assertNotDisposed();
this.val.dispose();
}
assertNotDisposed() {
if (this.val.isDisposed) {
throw new Error(`LayersVariable ${this.name} is already disposed.`);
}
}
get trainable() {
return this.trainable_;
}
set trainable(trainable) {
this.trainable_ = trainable;
this.val.trainable = trainable;
}
}
function checkShapesMatch(x, y) {
if (x.shape.toString() !== y.shape.toString()) {
throw new Error(
"Shape mismatch: " + JSON.stringify(x.shape) + " vs. " + JSON.stringify(y.shape)
);
}
}
/**
* Create a Variable.
* @param x The initial value of the `Variable`.
* @param dtype optional, the type of the variable.
* @param name optional, the name of the variable, default provided by
* Variable.
* @param constraint optional, a constraint to be applied after every update.
* @return The newly instantiated `Variable`.
*/
function variables_variable(x, dtype, name, constraint) {
return new variables_LayerVariable(x, dtype, name, true, constraint);
}
/**
* Instantiates an all-zeros Variable and returns it.
*
* @param shape Shape of the tensor.
* @param dtype DType of the tensor.
* @param name Name of the tensor.
* @return An all-zero Variable.
*/
function zerosVariable(shape, dtype, name) {
// TODO(cais): Implement logic for dtype.
return new variables_LayerVariable(dist["zeros"](shape), dtype, name);
}
/**
* Instantiates an all-zeros tensor of the same shape as another tensor.
*
* @param x The other tensor.
* @param dtype DType of the tensor.
* @param name Name of the tensor.
* @return A newly instantiated Variable.
*/
function zerosLike(x, dtype, name) {
return new variables_LayerVariable(dist["zerosLike"](x), dtype, name);
}
/**
* Instantiates an all-ones tensor and returns it.
*
* @param shape Shape of the tensor.
* @param dtype DType of the tensor.
* @param name Name of the tensor.
* @return An all-ones Variable.
*/
function onesVariable(shape, dtype, name) {
// TODO(cais): Implement logic for dtype.
const allocated = dist["ones"](shape);
return new variables_LayerVariable(allocated, dtype, name);
}
/**
* Instantiates an all-ones tensor of the same shape as another tensor.
*
* @param x The other tensor.
* @param dtype DType of the tensor.
* @param name Name of the tensor.
* @return A newly instantiated Variable.
*/
function onesLike(x, dtype, name) {
const allocated = dist["onesLike"](x);
return new variables_LayerVariable(allocated, dtype, name);
}
/**
* Instantiate an identity matrix and returns it, as a Variable
*
* @param size Number of rows/columns.
* @param dtype Data type of returned Variable.
* @param name Name of returned Variable.
* @return A Variable, an identity matrix.
*/
function eyeVariable(size, dtype, name) {
return new variables_LayerVariable(dist["eye"](size), dtype, name);
}
/**
* Get a Variable with uniform distribution of values.
* @param shape Shape of the tensor.
* @param minval Lower bound of the uniform distribution.
* @param maxval Upper bound of the uniform distribution.
* @param dtype
* @param seed
* @param name Optional name.
* @return The uniform-random Variable.
*/
function randomUniformVariable(shape, minval, maxval, dtype, seed, name = "randomUniform") {
return new variables_LayerVariable(
dist["randomUniform"](shape, minval, maxval, dtype),
dtype,
name
);
}
/**
* Get a Variable with truncated-normal distribution of values.
* @param shape Shape of the tensor.
* @param mean mean value of the normal distribution.
* @param stddev standard deviation of the normal distribution.
* @param dtype
* @param seed
* @param name Optional name.
* @return The truncated-normal-random Variable.
*/
function truncatedNormalVariable(
shape,
mean = 0.0,
stddev = 1.0,
dtype,
seed,
name = "truncatedNormal"
) {
// TODO(cais): Implement logic for dtype and seed once they are supported
// by deeplearn.js.
dtype = dtype || "float32";
if (dtype !== "float32" && dtype !== "int32") {
throw new NotImplementedError(`randomNormal does not support dType ${dtype}.`);
}
return new variables_LayerVariable(
dist["truncatedNormal"](shape, mean, stddev, dtype, seed),
dtype,
name
);
}
/**
* Get a Variable with normal distribution of values.
* @param shape Shape of the tensor.
* @param mean mean value of the normal distribution.
* @param stddev standard deviation of the normal distribution.
* @param dtype
* @param seed
* @param name Optional name.
* @return The truncated-normal-random Variable.
*/
function randomNormalVariable(
shape,
mean = 0.0,
stddev = 1.0,
dtype,
seed,
name = "randomNormal"
) {
dtype = dtype || "float32";
if (dtype !== "float32" && dtype !== "int32") {
throw new NotImplementedError(`randomNormalVariable does not support dType ${dtype}.`);
}
return new variables_LayerVariable(
dist["randomNormal"](shape, mean, stddev, dtype, seed),
dtype,
name
);
}
/**
* Update the value of a Variable.
* @param x The Variable to be updated.
* @param xNew The new value to update to.
* @return The Variable updated.
*/
function update(x, xNew) {
return x.write(xNew);
}
/**
* Update the value of a Variable by adding an increment.
* @param x The Variable to be updated.
* @param increment The incrment to add to `x`.
* @return The Variable updated.
*/
function updateAdd(x, increment) {
return x.write(dist["add"](x.read(), increment));
}
/**
* Update the value of a Variable by subtracting a decrement.
* @param x The Variable to be updated.
* @param decrement The decrement to subtract from `x`.
* @return The Variable updated.
*/
function updateSub(x, decrement) {
return x.write(dist["sub"](x.read(), decrement));
}
/**
* Get the values of an array of Variables.
*
* @param tensors An `Array` of `Variable`s to get the values of.
* @return The values of the inputs, as an `Array` of`tf.Tensor`s.
*/
function batchGetValue(xs) {
return xs.map((x) => x.read());
}
/**
* Update the value of multiple Variables at once.
*
* @param variablesAndValues An `Array`, each element is of type
* [Variable, Tensor]. The first item is the
* `Variable` of which the value is to be updated. The second item
* carries the new value.
*/
function batchSetValue(variablesAndValues) {
variablesAndValues.forEach((variableAndValue) => {
const variable = variableAndValue[0];
variable.write(variableAndValue[1]);
});
}
/**
* Returns the gradients of `variables` w.r.t. the return value of `lossFn`.
* @param lossFn A function which returns a Scalar to be used as the function
* value (i.e., numerator) for differentiation.
* @param variables List of variables to be used as the independent variables
* (i.e., denominator) for differentiation.
* @returns An Array of gradients tensors.
*/
function gradients(lossFn, variables) {
// TODO(cais): The return type signature can be simplified if deeplearn makes
// the corresponding type public.
const variableList = variables.map((variable) => variable.read());
const valudAndGrads = Object(dist["variableGrads"])(lossFn, variableList);
return variables.map((variable) => valudAndGrads.grads[variable.name]);
}
//# sourceMappingURL=variables.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/engine/topology.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original source: keras/engine/topology.py */
/**
* Specifies the ndim, dtype and shape of every input to a layer.
*
* Every layer should expose (if appropriate) an `inputSpec` attribute:
* a list of instances of InputSpec (one per input tensor).
*
* A null entry in a shape is compatible with any dimension,
* a null shape is compatible with any shape.
*/
class InputSpec {
constructor(args) {
this.dtype = args.dtype;
this.shape = args.shape;
/*
TODO(michaelterry): Could throw error if ndim and shape are both defined
(then backport).
*/
if (args.shape != null) {
this.ndim = args.shape.length;
} else {
this.ndim = args.ndim;
}
this.maxNDim = args.maxNDim;
this.minNDim = args.minNDim;
this.axes = args.axes || {};
}
}
/**
* `tf.SymbolicTensor` is a placeholder for a Tensor without any concrete value.
*
* They are most often encountered when building a graph of `Layer`s for a
* a `tf.LayersModel` and the input data's shape, but not values are known.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
class topology_SymbolicTensor {
/**
*
* @param dtype
* @param shape
* @param sourceLayer The Layer that produced this symbolic tensor.
* @param inputs The inputs passed to sourceLayer's __call__() method.
* @param nodeIndex
* @param tensorIndex
* @param callArgs The keyword arguments passed to the __call__() method.
* @param name
* @param outputTensorIndex The index of this tensor in the list of outputs
* returned by apply().
*/
constructor(dtype, shape, sourceLayer, inputs, callArgs, name, outputTensorIndex) {
this.dtype = dtype;
this.shape = shape;
this.sourceLayer = sourceLayer;
this.inputs = inputs;
this.callArgs = callArgs;
this.outputTensorIndex = outputTensorIndex;
this.id = getNextUniqueTensorId();
if (name != null) {
this.originalName = getScopedTensorName(name);
this.name = getUniqueTensorName(this.originalName);
}
this.rank = shape.length;
}
}
let _nextNodeID = 0;
/**
* A `Node` describes the connectivity between two layers.
*
* Each time a layer is connected to some new input,
* a node is added to `layer.inboundNodes`.
*
* Each time the output of a layer is used by another layer,
* a node is added to `layer.outboundNodes`.
*
* `nodeIndices` and `tensorIndices` are basically fine-grained coordinates
* describing the origin of the `inputTensors`, verifying the following:
*
* `inputTensors[i] ==
* inboundLayers[i].inboundNodes[nodeIndices[i]].outputTensors[
* tensorIndices[i]]`
*
* A node from layer A to layer B is added to:
* A.outboundNodes
* B.inboundNodes
*/
class Node {
constructor(
args,
// TODO(michaelterry): Define actual type for this.
callArgs
) {
this.callArgs = callArgs;
this.id = _nextNodeID++;
/*
Layer instance (NOT a list).
this is the layer that takes a list of input tensors
and turns them into a list of output tensors.
the current node will be added to
the inboundNodes of outboundLayer.
*/
this.outboundLayer = args.outboundLayer;
/*
The following 3 properties describe where
the input tensors come from: which layers,
and for each layer, which node and which
tensor output of each node.
*/
// List of layer instances.
this.inboundLayers = args.inboundLayers;
// List of integers, 1:1 mapping with inboundLayers.
this.nodeIndices = args.nodeIndices;
// List of integers, 1:1 mapping with inboundLayers.
this.tensorIndices = args.tensorIndices;
/*
Following 2 properties:
tensor inputs and outputs of outboundLayer.
*/
// List of tensors. 1:1 mapping with inboundLayers.
this.inputTensors = args.inputTensors;
// List of tensors, created by outboundLayer.call().
this.outputTensors = args.outputTensors;
/*
Following 2 properties: input and output masks.
List of tensors, 1:1 mapping with inputTensor.
*/
this.inputMasks = args.inputMasks;
// List of tensors, created by outboundLayer.computeMask().
this.outputMasks = args.outputMasks;
// Following 2 properties: input and output shapes.
// List of shape tuples, shapes of inputTensors.
this.inputShapes = args.inputShapes;
// List of shape tuples, shapes of outputTensors.
this.outputShapes = args.outputShapes;
// Add nodes to all layers involved.
for (const layer of args.inboundLayers) {
if (layer != null) {
layer.outboundNodes.push(this);
}
}
args.outboundLayer.inboundNodes.push(this);
}
getConfig() {
const inboundNames = [];
for (const layer of this.inboundLayers) {
if (layer != null) {
inboundNames.push(layer.name);
} else {
inboundNames.push(null);
}
}
return {
outboundLayer: this.outboundLayer ? this.outboundLayer.name : null,
inboundLayers: inboundNames,
nodeIndices: this.nodeIndices,
tensorIndices: this.tensorIndices,
};
}
}
let _nextLayerID = 0;
/**
* A layer is a grouping of operations and weights that can be composed to
* create a `tf.LayersModel`.
*
* Layers are constructed by using the functions under the
* [tf.layers](#Layers-Basic) namespace.
*/
/** @doc {heading: 'Layers', subheading: 'Classes', namespace: 'layers'} */
class topology_Layer extends dist["serialization"].Serializable {
constructor(args = {}) {
super();
this._callHook = null;
this._addedWeightNames = [];
// Porting Notes: PyKeras does not have this property in this base Layer
// class. Instead lets Layer subclass set it dynamically and checks the
// value with `hasattr`. In tfjs-layers, we let this be a member of this
// base class.
this._stateful = false;
this.id = _nextLayerID++;
this.activityRegularizer = null;
this.inputSpec = null;
this.supportsMasking = false;
// These properties will be set upon call of this.build()
this._trainableWeights = [];
this._nonTrainableWeights = [];
this._losses = [];
this._updates = [];
this._built = false;
/*
These lists will be filled via successive calls
to this.addInboundNode().
*/
this.inboundNodes = [];
this.outboundNodes = [];
let name = args.name;
if (!name) {
const prefix = this.getClassName();
name = toSnakeCase(prefix) + "_" + getUid(prefix);
}
this.name = name;
this.trainable_ = args.trainable == null ? true : args.trainable;
if (args.inputShape != null || args.batchInputShape != null) {
/*
In this case we will later create an input layer
to insert before the current layer
*/
let batchInputShape;
if (args.batchInputShape != null) {
batchInputShape = args.batchInputShape;
} else if (args.inputShape != null) {
let batchSize = null;
if (args.batchSize != null) {
batchSize = args.batchSize;
}
batchInputShape = [batchSize].concat(args.inputShape);
}
this.batchInputShape = batchInputShape;
// Set dtype.
let dtype = args.dtype;
if (dtype == null) {
dtype = args.inputDType;
}
if (dtype == null) {
dtype = "float32";
}
this.dtype = dtype;
}
if (args.weights != null) {
this.initialWeights = args.weights;
} else {
this.initialWeights = null;
}
// The value of `_refCount` is initialized to null. When the layer is used
// in a symbolic way for the first time, it will be set to 1.
this._refCount = null;
this.fastWeightInitDuringBuild = false;
}
/**
* Converts a layer and its index to a unique (immutable type) name.
* This function is used internally with `this.containerNodes`.
* @param layer The layer.
* @param nodeIndex The layer's position (e.g. via enumerate) in a list of
* nodes.
*
* @returns The unique name.
*/
static nodeKey(layer, nodeIndex) {
return layer.name + "_ib-" + nodeIndex.toString();
}
/**
* Returns this.inboundNode at index nodeIndex.
*
* Porting note: This is a replacement for _get_node_attribute_at_index()
* @param nodeIndex
* @param attrName The name of the attribute related to request for this node.
*/
getNodeAtIndex(nodeIndex, attrName) {
if (this.inboundNodes.length === 0) {
throw new RuntimeError(
"The layer has never been called " + `and thus has no defined ${attrName}.`
);
}
if (this.inboundNodes.length <= nodeIndex) {
throw new ValueError(
`Asked to get ${attrName} at node ${nodeIndex}, ` +
`but the layer has only ${this.inboundNodes.length} inbound nodes.`
);
}
return this.inboundNodes[nodeIndex];
}
/**
* Retrieves the input tensor(s) of a layer at a given node.
*
* @param nodeIndex Integer, index of the node from which to retrieve the
* attribute. E.g. `nodeIndex=0` will correspond to the first time the layer
* was called.
*
* @return A tensor (or list of tensors if the layer has multiple inputs).
*/
getInputAt(nodeIndex) {
return singletonOrArray(this.getNodeAtIndex(nodeIndex, "input").inputTensors);
}
/**
* Retrieves the output tensor(s) of a layer at a given node.
*
* @param nodeIndex Integer, index of the node from which to retrieve the
* attribute. E.g. `nodeIndex=0` will correspond to the first time the layer
* was called.
*
* @return A tensor (or list of tensors if the layer has multiple outputs).
*/
getOutputAt(nodeIndex) {
return singletonOrArray(this.getNodeAtIndex(nodeIndex, "output").outputTensors);
}
// Properties
/**
* Retrieves the input tensor(s) of a layer.
*
* Only applicable if the layer has exactly one inbound node,
* i.e. if it is connected to one incoming layer.
*
* @return Input tensor or list of input tensors.
*
* @exception AttributeError if the layer is connected to more than one
* incoming layers.
*/
get input() {
if (this.inboundNodes.length > 1) {
throw new AttributeError(
`Layer ${this.name}` +
" has multiple inbound nodes, " +
'hence the notion of "layer input" ' +
"is ill-defined. " +
"Use `getInputAt(nodeIndex)` instead."
);
} else if (this.inboundNodes.length === 0) {
throw new AttributeError(
`Layer ${this.name}` + " is not connected, no input to return."
);
}
return singletonOrArray(this.getNodeAtIndex(0, "input").inputTensors);
}
/**
* Retrieves the output tensor(s) of a layer.
*
* Only applicable if the layer has exactly one inbound node,
* i.e. if it is connected to one incoming layer.
*
* @return Output tensor or list of output tensors.
*
* @exception AttributeError if the layer is connected to more than one
* incoming layers.
*/
get output() {
if (this.inboundNodes.length === 0) {
throw new AttributeError(`Layer ${this.name}` + " has no inbound nodes.");
}
if (this.inboundNodes.length > 1) {
throw new AttributeError(
`Layer ${this.name}` +
" has multiple inbound nodes, " +
'hence the notion of "layer output" ' +
"is ill-defined. " +
"Use `getOutputAt(nodeIndex)` instead."
);
}
return singletonOrArray(this.getNodeAtIndex(0, "output").outputTensors);
}
get losses() {
return this._losses;
}
/**
* Retrieves the Layer's current loss values.
*
* Used for regularizers during training.
*/
calculateLosses() {
// Porting Node: This is an augmentation to Layer.loss in PyKeras.
// In PyKeras, Layer.loss returns symbolic tensors. Here a concrete
// Tensor (specifically Scalar) values are returned. This is due to the
// imperative backend.
return this.losses.map((lossFn) => lossFn());
}
get updates() {
return this._updates;
}
get built() {
return this._built;
}
set built(built) {
this._built = built;
}
get trainable() {
return this.trainable_;
}
set trainable(trainable) {
this._trainableWeights.forEach((w) => (w.trainable = trainable));
this.trainable_ = trainable;
}
get trainableWeights() {
if (this.trainable_) {
return this._trainableWeights.filter((w) => w.trainable);
} else {
return [];
}
}
set trainableWeights(weights) {
this._trainableWeights = weights;
}
get nonTrainableWeights() {
if (this.trainable) {
return this._trainableWeights
.filter((w) => !w.trainable)
.concat(this._nonTrainableWeights);
} else {
return this._trainableWeights.concat(this._nonTrainableWeights);
}
}
set nonTrainableWeights(weights) {
this._nonTrainableWeights = weights;
}
/**
* The concatenation of the lists trainableWeights and nonTrainableWeights
* (in this order).
*/
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
get stateful() {
return this._stateful;
}
/**
* Reset the states of the layer.
*
* This method of the base Layer class is essentially a no-op.
* Subclasses that are stateful (e.g., stateful RNNs) should override this
* method.
*/
resetStates() {
if (!this.stateful) {
throw new Error(
"Cannot call the resetStates() method of a non-stateful Layer " + "object."
);
}
}
/**
* Checks compatibility between the layer and provided inputs.
*
* This checks that the tensor(s) `input`
* verify the input assumptions of the layer
* (if any). If not, exceptions are raised.
*
* @param inputs Input tensor or list of input tensors.
*
* @exception ValueError in case of mismatch between
* the provided inputs and the expectations of the layer.
*/
assertInputCompatibility(inputs) {
inputs = toList(inputs);
if (this.inputSpec == null || this.inputSpec.length === 0) {
return;
}
const inputSpec = toList(this.inputSpec);
if (inputs.length !== inputSpec.length) {
throw new ValueError(
`Layer ${this.name} expects ${inputSpec.length} inputs, ` +
`but it received ${inputs.length} input tensors. ` +
`Input received: ${inputs}`
);
}
for (let inputIndex = 0; inputIndex < inputs.length; inputIndex++) {
const x = inputs[inputIndex];
const spec = inputSpec[inputIndex];
if (spec == null) {
continue;
}
// Check ndim.
const ndim = x.rank;
if (spec.ndim != null) {
if (ndim !== spec.ndim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}: ` +
`expected ndim=${spec.ndim}, found ndim=${ndim}`
);
}
}
if (spec.maxNDim != null) {
if (ndim > spec.maxNDim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}` +
`: expected max_ndim=${spec.maxNDim}, found ndim=${ndim}`
);
}
}
if (spec.minNDim != null) {
if (ndim < spec.minNDim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}` +
`: expected min_ndim=${spec.minNDim}, found ndim=${ndim}.`
);
}
}
// Check dtype.
if (spec.dtype != null) {
if (x.dtype !== spec.dtype) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name} ` +
`: expected dtype=${spec.dtype}, found dtype=${x.dtype}.`
);
}
}
// Check specific shape axes.
if (spec.axes) {
const xShape = x.shape;
for (const key in spec.axes) {
const axis = Number(key);
const value = spec.axes[key];
// Perform Python-style slicing in case axis < 0;
// TODO(cais): Use https://github.com/alvivi/typescript-underscore to
// ensure type safety through Underscore calls.
const xShapeAtAxis = axis >= 0 ? xShape[axis] : xShape[xShape.length + axis];
if (value != null && [value, null].indexOf(xShapeAtAxis) === -1) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ` +
`${this.name}: expected axis ${axis} of input shape to ` +
`have value ${value} but got shape ${xShape}.`
);
}
}
}
// Check shape.
if (spec.shape != null) {
for (let i = 0; i < spec.shape.length; ++i) {
const specDim = spec.shape[i];
const dim = x.shape[i];
if (specDim != null && dim != null) {
if (specDim !== dim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ` +
`${this.name}: expected shape=${spec.shape}, ` +
`found shape=${x.shape}.`
);
}
}
}
}
}
}
/**
* This is where the layer's logic lives.
*
* @param inputs Input tensor, or list/tuple of input tensors.
* @param kwargs Additional keyword arguments.
*
* @return A tensor or list/tuple of tensors.
*/
call(inputs, kwargs) {
return inputs;
}
invokeCallHook(inputs, kwargs) {
if (this._callHook != null) {
this._callHook(inputs, kwargs);
}
}
/**
* Set call hook.
* This is currently used for testing only.
* @param callHook
*/
setCallHook(callHook) {
this._callHook = callHook;
}
/**
* Clear call hook.
* This is currently used for testing only.
*/
clearCallHook() {
this._callHook = null;
}
/**
* Builds or executes a `Layer's logic.
*
* When called with `tf.Tensor`(s), execute the `Layer`s computation and
* return Tensor(s). For example:
*
* ```js
* const denseLayer = tf.layers.dense({
* units: 1,
* kernelInitializer: 'zeros',
* useBias: false
* });
*
* // Invoke the layer's apply() method with a `tf.Tensor` (with concrete
* // numeric values).
* const input = tf.ones([2, 2]);
* const output = denseLayer.apply(input);
*
* // The output's value is expected to be [[0], [0]], due to the fact that
* // the dense layer has a kernel initialized to all-zeros and does not have
* // a bias.
* output.print();
* ```
*
* When called with `tf.SymbolicTensor`(s), this will prepare the layer for
* future execution. This entails internal book-keeping on shapes of
* expected Tensors, wiring layers together, and initializing weights.
*
* Calling `apply` with `tf.SymbolicTensor`s are typically used during the
* building of non-`tf.Sequential` models. For example:
*
* ```js
* const flattenLayer = tf.layers.flatten();
* const denseLayer = tf.layers.dense({units: 1});
*
* // Use tf.layers.input() to obtain a SymbolicTensor as input to apply().
* const input = tf.input({shape: [2, 2]});
* const output1 = flattenLayer.apply(input);
*
* // output1.shape is [null, 4]. The first dimension is the undetermined
* // batch size. The second dimension comes from flattening the [2, 2]
* // shape.
* console.log(JSON.stringify(output1.shape));
*
* // The output SymbolicTensor of the flatten layer can be used to call
* // the apply() of the dense layer:
* const output2 = denseLayer.apply(output1);
*
* // output2.shape is [null, 1]. The first dimension is the undetermined
* // batch size. The second dimension matches the number of units of the
* // dense layer.
* console.log(JSON.stringify(output2.shape));
*
* // The input and output and be used to construct a model that consists
* // of the flatten and dense layers.
* const model = tf.model({inputs: input, outputs: output2});
* ```
*
* @param inputs a `tf.Tensor` or `tf.SymbolicTensor` or an Array of them.
* @param kwargs Additional keyword arguments to be passed to `call()`.
*
* @return Output of the layer's `call` method.
*
* @exception ValueError error in case the layer is missing shape information
* for its `build` call.
*/
// Porting Note: This is a replacement for __call__() in Python.
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
apply(inputs, kwargs) {
kwargs = kwargs || {};
this.assertNotDisposed();
// Ensure inputs are all the same type.
const inputsList = toList(inputs);
let allAreSymbolic = true;
for (const input of inputsList) {
if (!(input instanceof topology_SymbolicTensor)) {
allAreSymbolic = false;
break;
}
}
let noneAreSymbolic = true;
for (const input of inputsList) {
if (input instanceof topology_SymbolicTensor) {
noneAreSymbolic = false;
break;
}
}
if (allAreSymbolic === noneAreSymbolic) {
throw new ValueError(
"Arguments to apply() must be all " + "SymbolicTensors or all Tensors"
);
}
// TODO(michaelterry): nameScope() may not be necessary.
return nameScope(this.name, () => {
// Handle laying building (weight creating, input spec locking).
if (!this.built) {
/*
Throw exceptions in case the input is not compatible
with the inputSpec specified in the layer constructor.
*/
this.assertInputCompatibility(inputs);
// Collect input shapes to build layer.
const inputShapes = [];
for (const xElem of toList(inputs)) {
inputShapes.push(xElem.shape);
}
this.build(singletonOrArray(inputShapes));
this.built = true;
// Load weights that were specified at layer instantiation.
if (this.initialWeights) {
this.setWeights(this.initialWeights);
}
if (this._refCount === null && noneAreSymbolic) {
// The first use of this layer is a non-symbolic call, set ref count
// to 1 so the Layer can be properly disposed if its dispose() method
// is called.
this._refCount = 1;
}
}
/*
Throw exceptions in case the input is not compatible
with the inputSpec set at build time.
*/
this.assertInputCompatibility(inputs);
// Handle mask propagation.
// TODO(michaelterry): Mask propagation not currently implemented.
// Actually call the layer, collecting output(s), mask(s), and shape(s).
if (noneAreSymbolic) {
let output = this.call(inputs, kwargs);
// TODO(michaelterry): Compute the outputMask
// If the layer returns tensors from its inputs, unmodified,
// we copy them to avoid loss of tensor metadata.
const outputList = toList(output);
const outputListCopy = [];
// TODO(michaelterry): This copying may not be necessary given our eager
// backend.
for (let x of outputList) {
if (inputsList.indexOf(x) !== -1) {
x = x.clone();
}
outputListCopy.push(x);
}
output = singletonOrArray(outputListCopy);
if (this.activityRegularizer != null) {
throw new NotImplementedError(
"Layer invocation in the presence of activity " +
"regularizer(s) is not supported yet."
);
}
// TODO(michaelterry): Call addInboundNode()?
return output;
} else {
const inputShape = collectInputShape(inputs);
const outputShape = this.computeOutputShape(inputShape);
let output;
const outputDType = guessOutputDType(inputs);
this.warnOnIncompatibleInputShape(Array.isArray(inputs) ? inputShape[0] : inputShape);
if (outputShape != null && outputShape.length > 0 && Array.isArray(outputShape[0])) {
// We have multiple output shapes. Create multiple output tensors.
output = outputShape.map(
(shape, index) =>
new topology_SymbolicTensor(
outputDType,
shape,
this,
toList(inputs),
kwargs,
this.name,
index
)
);
} else {
output = new topology_SymbolicTensor(
outputDType,
outputShape,
this,
toList(inputs),
kwargs,
this.name
);
}
/*
Add an inbound node to the layer, so that it keeps track
of the call and of all new variables created during the call.
This also updates the layer history of the output tensor(s).
If the input tensor(s) had no previous history,
this does nothing.
*/
this.addInboundNode(inputs, output, null, null, inputShape, outputShape, kwargs);
this._refCount++;
if (this.activityRegularizer != null) {
throw new NotImplementedError(
"Layer invocation in the presence of activity " +
"regularizer(s) is not supported yet."
);
}
return output;
}
});
}
/**
* Check compatibility between input shape and this layer's batchInputShape.
*
* Print warning if any incompatibility is found.
*
* @param inputShape Input shape to be checked.
*/
warnOnIncompatibleInputShape(inputShape) {
if (this.batchInputShape == null) {
return;
} else if (inputShape.length !== this.batchInputShape.length) {
console.warn(
`The rank of the input tensor provided (shape: ` +
`${JSON.stringify(inputShape)}) does not match that of the ` +
`batchInputShape (${JSON.stringify(this.batchInputShape)}) ` +
`of the layer ${this.name}`
);
} else {
let dimMismatch = false;
this.batchInputShape.forEach((dimension, i) => {
if (dimension != null && inputShape[i] != null && inputShape[i] !== dimension) {
dimMismatch = true;
}
});
if (dimMismatch) {
console.warn(
`The shape of the input tensor ` +
`(${JSON.stringify(inputShape)}) does not ` +
`match the expectation of layer ${this.name}: ` +
`${JSON.stringify(this.batchInputShape)}`
);
}
}
}
/**
* Retrieves the output shape(s) of a layer.
*
* Only applicable if the layer has only one inbound node, or if all inbound
* nodes have the same output shape.
*
* @returns Output shape or shapes.
* @throws AttributeError: if the layer is connected to more than one incoming
* nodes.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
get outputShape() {
if (this.inboundNodes == null || this.inboundNodes.length === 0) {
throw new AttributeError(
`The layer ${this.name} has never been called and thus has no ` +
`defined output shape.`
);
}
const allOutputShapes = [];
for (const node of this.inboundNodes) {
const shapeString = JSON.stringify(node.outputShapes);
if (allOutputShapes.indexOf(shapeString) === -1) {
allOutputShapes.push(shapeString);
}
}
if (allOutputShapes.length === 1) {
const outputShapes = this.inboundNodes[0].outputShapes;
if (
Array.isArray(outputShapes) &&
Array.isArray(outputShapes[0]) &&
outputShapes.length === 1
) {
return outputShapes[0];
} else {
return outputShapes;
}
} else {
throw new AttributeError(
`The layer ${this.name} has multiple inbound nodes with different ` +
`output shapes. Hence the notion of "outut shape" is ill-defined ` +
`for the layer.`
);
// TODO(cais): Implement getOutputShapeAt().
}
}
/**
* Counts the total number of numbers (e.g., float32, int32) in the
* weights.
*
* @returns An integer count.
* @throws RuntimeError: If the layer is not built yet (in which case its
* weights are not defined yet.)
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
countParams() {
if (!this.built) {
throw new RuntimeError(
`You tried to call countParams() on ${this.name}, ` +
`but the layer is not built yet. Build it first by calling ` +
`build(batchInputShape).`
);
}
return countParamsInWeights(this.weights);
}
/**
* Creates the layer weights.
*
* Must be implemented on all layers that have weights.
*
* Called when apply() is called to construct the weights.
*
* @param inputShape A `Shape` or array of `Shape` (unused).
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
build(inputShape) {
this.built = true;
}
/**
* Returns the current values of the weights of the layer.
*
* @param trainableOnly Whether to get the values of only trainable weights.
* @returns Weight values as an `Array` of `tf.Tensor`s.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
getWeights(trainableOnly = false) {
return batchGetValue(trainableOnly ? this.trainableWeights : this.weights);
}
/**
* Sets the weights of the layer, from Tensors.
*
* @param weights a list of Tensors. The number of arrays and their shape
* must match number of the dimensions of the weights of the layer (i.e.
* it should match the output of `getWeights`).
*
* @exception ValueError If the provided weights list does not match the
* layer's specifications.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
setWeights(weights) {
Object(dist["tidy"])(() => {
const params = this.weights;
if (params.length !== weights.length) {
// TODO(cais): Restore the following and use `providedWeights`, instead
// of `weights` in the error message, once the deeplearn.js bug is
// fixed: https://github.com/PAIR-code/deeplearnjs/issues/498 const
// providedWeights = JSON.stringify(weights).substr(0, 50);
throw new ValueError(
`You called setWeights(weights) on layer "${this.name}" ` +
`with a weight list of length ${weights.length}, ` +
`but the layer was expecting ${params.length} weights. ` +
`Provided weights: ${weights}...`
);
}
if (params.length === 0) {
return;
}
const weightValueTuples = [];
const paramValues = batchGetValue(params);
for (let i = 0; i < paramValues.length; ++i) {
const pv = paramValues[i];
const p = params[i];
const w = weights[i];
if (!dist["util"].arraysEqual(pv.shape, w.shape)) {
throw new ValueError(
`Layer weight shape ${pv.shape} ` +
`not compatible with provided weight shape ${w.shape}`
);
}
weightValueTuples.push([p, w]);
}
batchSetValue(weightValueTuples);
});
}
/**
* Adds a weight variable to the layer.
*
* @param name Name of the new weight variable.
* @param shape The shape of the weight.
* @param dtype The dtype of the weight.
* @param initializer An initializer instance.
* @param regularizer A regularizer instance.
* @param trainable Whether the weight should be trained via backprop or not
* (assuming that the layer itself is also trainable).
* @param constraint An optional trainable.
* @return The created weight variable.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
addWeight(name, shape, dtype, initializer, regularizer, trainable, constraint) {
// Reject duplicate weight names.
if (this._addedWeightNames.indexOf(name) !== -1) {
throw new ValueError(`Duplicate weight name ${name} for layer ${this.name}`);
}
this._addedWeightNames.push(name);
if (dtype == null) {
dtype = "float32";
}
if (this.fastWeightInitDuringBuild) {
initializer = getInitializer("zeros");
}
const initValue = initializer.apply(shape, dtype);
const weight = new variables_LayerVariable(initValue, dtype, name, trainable, constraint);
initValue.dispose();
// Request backend not to dispose the weights of the model on scope() exit.
if (regularizer != null) {
this.addLoss(() => regularizer.apply(weight.read()));
}
if (trainable == null) {
trainable = true;
}
if (trainable) {
this._trainableWeights.push(weight);
} else {
this._nonTrainableWeights.push(weight);
}
return weight;
}
/**
* Set the fast-weight-initialization flag.
*
* In cases where the initialized weight values will be immediately
* overwritten by loaded weight values during model loading, setting
* the flag to `true` saves unnecessary calls to potentially expensive
* initializers and speeds up the loading process.
*
* @param value Target value of the flag.
*/
setFastWeightInitDuringBuild(value) {
this.fastWeightInitDuringBuild = value;
}
/**
* Add losses to the layer.
*
* The loss may potentionally be conditional on some inputs tensors,
* for instance activity losses are conditional on the layer's inputs.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
addLoss(losses) {
if (losses == null || (Array.isArray(losses) && losses.length === 0)) {
return;
}
// Update this.losses
losses = toList(losses);
if (this._losses !== undefined && this._losses !== null) {
this.losses.push(...losses);
}
}
/**
* Computes the output shape of the layer.
*
* Assumes that the layer will be built to match that input shape provided.
*
* @param inputShape A shape (tuple of integers) or a list of shape tuples
* (one per output tensor of the layer). Shape tuples can include null for
* free dimensions, instead of an integer.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
computeOutputShape(inputShape) {
return inputShape;
}
/**
* Computes an output mask tensor.
*
* @param inputs Tensor or list of tensors.
* @param mask Tensor or list of tensors.
*
* @return null or a tensor (or list of tensors, one per output tensor of the
* layer).
*/
computeMask(inputs, mask) {
if (!this.supportsMasking) {
if (mask != null) {
if (Array.isArray(mask)) {
mask.forEach((maskElement) => {
if (maskElement != null) {
throw new TypeError(
`Layer ${this.name} does not support masking, ` +
"but was passed an inputMask."
);
}
});
} else {
throw new TypeError(
`Layer ${this.name} does not support masking, ` + "but was passed an inputMask."
);
}
}
// masking not explicitly supported: return null as mask
return null;
}
// if masking is explictly supported, by default
// carry over the input mask
return mask;
}
/**
* Internal method to create an inbound node for the layer.
*
* @param inputTensors List of input tensors.
* @param outputTensors List of output tensors.
* @param inputMasks List of input masks (a mask can be a tensor, or null).
* @param outputMasks List of output masks (a mask can be a tensor, or null).
* @param inputShapes List of input shape tuples.
* @param outputShapes List of output shape tuples.
* @param kwargs Dictionary of keyword arguments that were passed to the
* `call` method of the layer at the call that created the node.
*/
addInboundNode(
inputTensors,
outputTensors,
inputMasks,
outputMasks,
inputShapes,
outputShapes,
kwargs = null
) {
const inputTensorList = toList(inputTensors);
outputTensors = toList(outputTensors);
inputMasks = toList(inputMasks);
outputMasks = toList(outputMasks);
inputShapes = normalizeShapeList(inputShapes);
outputShapes = normalizeShapeList(outputShapes);
// Collect input tensor(s) coordinates.
const inboundLayers = [];
const nodeIndices = [];
const tensorIndices = [];
for (const x of inputTensorList) {
/*
* TODO(michaelterry): Keras adds this value to tensors; it's not
* clear whether we'll use this or not.
*/
inboundLayers.push(x.sourceLayer);
nodeIndices.push(x.nodeIndex);
tensorIndices.push(x.tensorIndex);
}
// Create node, add it to inbound nodes.
// (This call has side effects.)
// tslint:disable-next-line:no-unused-expression
new Node(
{
outboundLayer: this,
inboundLayers,
nodeIndices,
tensorIndices,
inputTensors: inputTensorList,
outputTensors,
inputMasks,
outputMasks,
inputShapes,
outputShapes,
},
kwargs
);
// Update tensor history
for (let i = 0; i < outputTensors.length; i++) {
// TODO(michaelterry: _uses_learning_phase not tracked.
outputTensors[i].sourceLayer = this;
outputTensors[i].nodeIndex = this.inboundNodes.length - 1;
outputTensors[i].tensorIndex = i;
}
}
/**
* Returns the config of the layer.
*
* A layer config is a TS dictionary (serializable)
* containing the configuration of a layer.
* The same layer can be reinstantiated later
* (without its trained weights) from this configuration.
*
* The config of a layer does not include connectivity
* information, nor the layer class name. These are handled
* by 'Container' (one layer of abstraction above).
*
* Porting Note: The TS dictionary follows TS naming standrds for
* keys, and uses tfjs-layers type-safe Enums. Serialization methods
* should use a helper function to convert to the pythonic storage
* standard. (see serialization_utils.convertTsToPythonic)
*
* @returns TS dictionary of configuration.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
getConfig() {
const config = { name: this.name, trainable: this.trainable };
if (this.batchInputShape != null) {
config["batchInputShape"] = this.batchInputShape;
}
if (this.dtype != null) {
config["dtype"] = this.dtype;
}
return config;
}
/**
* Dispose the weight variables that this Layer instance holds.
*
* @returns {number} Number of disposed variables.
*/
disposeWeights() {
this.weights.forEach((weight) => weight.dispose());
return this.weights.length;
}
assertNotDisposed() {
if (this._refCount === 0) {
throw new Error(`Layer '${this.name}' is already disposed.`);
}
}
/**
* Attempt to dispose layer's weights.
*
* This method decrease the reference count of the Layer object by 1.
*
* A Layer is reference-counted. Its reference count is incremented by 1
* the first item its `apply()` method is called and when it becomes a part
* of a new `Node` (through calling the `apply()`) method on a
* `tf.SymbolicTensor`).
*
* If the reference count of a Layer becomes 0, all the weights will be
* disposed and the underlying memory (e.g., the textures allocated in WebGL)
* will be freed.
*
* Note: If the reference count is greater than 0 after the decrement, the
* weights of the Layer will *not* be disposed.
*
* After a Layer is disposed, it cannot be used in calls such as `apply()`,
* `getWeights()` or `setWeights()` anymore.
*
* @returns A DisposeResult Object with the following fields:
* - refCountAfterDispose: The reference count of the Container after this
* `dispose()` call.
* - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed
* during this `dispose()` call.
* @throws {Error} If the layer is not built yet, or if the layer has already
* been disposed.
*/
/** @doc {heading: 'Models', 'subheading': 'Classes'} */
dispose() {
if (!this.built) {
throw new Error(
`Cannot dispose Layer ${this.name} because it has not been ` + `built yet.`
);
}
if (this._refCount === null) {
throw new Error(
`Cannot dispose Layer ${this.name} because it has not been used ` + `yet.`
);
}
this.assertNotDisposed();
let numDisposedVariables = 0;
if (--this._refCount === 0) {
numDisposedVariables = this.disposeWeights();
}
return { refCountAfterDispose: this._refCount, numDisposedVariables };
}
}
/**
* Collects the input shape(s) of a list of `tf.Tensor`s or
* `tf.SymbolicTensor`s.
*
* TODO(michaelterry): Update PyKeras docs (backport).
*
* @param inputTensors List of input tensors (or single input tensor).
*
* @return List of shape tuples (or single tuple), one tuple per input.
*/
function collectInputShape(inputTensors) {
inputTensors = toList(inputTensors);
const shapes = [];
for (const x of inputTensors) {
shapes.push(x.shape);
}
return singletonOrArray(shapes);
}
/**
* Guesses output dtype based on inputs.
*
* At present, just returns 'float32' for any input.
*
* @param inputTensors List of input tensors (or single input tensor).
*
* @return The guessed DType. At present, always returns 'float32'.
*/
function guessOutputDType(inputTensors) {
return "float32";
}
/**
* Returns the list of input tensors necessary to compute `tensor`.
*
* Output will always be a list of tensors (potentially with 1 element).
*
* @param tensor The tensor to start from.
* @param layer Origin layer of the tensor.
* @param nodeIndex Origin node index of the tensor.
*
* @return Array of input tensors.
*/
function getSourceInputs(tensor, layer, nodeIndex) {
if (layer == null || (nodeIndex != null && nodeIndex > 0)) {
layer = tensor.sourceLayer;
nodeIndex = tensor.nodeIndex;
}
if (layer.inboundNodes.length === 0) {
return [tensor];
} else {
const node = layer.inboundNodes[nodeIndex];
if (node.inboundLayers.length === 0) {
return node.inputTensors;
} else {
const sourceTensors = [];
for (let i = 0; i < node.inboundLayers.length; i++) {
const x = node.inputTensors[i];
const layer = node.inboundLayers[i];
const nodeIndex = node.nodeIndices[i];
const previousSources = getSourceInputs(x, layer, nodeIndex);
// Avoid input redundancy.
for (const x of previousSources) {
if (sourceTensors.indexOf(x) === -1) {
sourceTensors.push(x);
}
}
}
return sourceTensors;
}
}
}
//# sourceMappingURL=topology.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/engine/input_layer.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class input_layer_InputLayer extends topology_Layer {
constructor(args) {
super({
dtype: args.dtype,
name: args.name != null ? args.name : getUid("input").toString(),
});
// Normalize config.batchSize and config.sparse
if (args.batchSize == null) {
args.batchSize = null;
}
if (args.sparse == null) {
args.sparse = false;
}
this.trainable = false;
this.built = true;
this.sparse = args.sparse;
if (args.inputShape != null && args.batchInputShape != null) {
throw new ValueError(
"Only provide the inputShape OR " +
"batchInputShape argument to inputLayer, not both at the same time."
);
}
let batchInputShape = args.batchInputShape;
if (batchInputShape == null) {
if (args.inputShape == null) {
throw new ValueError(
"An InputLayer should be passed either a " + "`batchInputShape` or an `inputShape`."
);
} else {
batchInputShape = [args.batchSize].concat(args.inputShape);
}
} else {
// TODO(michaelterry): Backport to PyKeras
if (args.batchSize != null) {
throw new ValueError(
"Cannot specify batchSize if batchInputShape is " +
"specified when creating an InputLayer."
);
}
}
const dtype = args.dtype || "float32";
this.batchInputShape = batchInputShape;
this.dtype = dtype;
// TODO(michaelterry): Backport this to PyKeras?
this.inputSpec = [{ shape: batchInputShape }];
const inputTensor = new topology_SymbolicTensor(
this.dtype,
this.batchInputShape,
this,
[],
{},
this.name
);
inputTensor.nodeIndex = 0;
inputTensor.tensorIndex = 0;
// Create an input node to add to this.outboundNode.
// (This call has side effects.)
// tslint:disable-next-line:no-unused-expression
new Node({
outboundLayer: this,
inboundLayers: [],
nodeIndices: [],
tensorIndices: [],
inputTensors: [inputTensor],
outputTensors: [inputTensor],
inputMasks: [null],
outputMasks: [null],
inputShapes: [batchInputShape],
outputShapes: [batchInputShape],
});
}
apply(inputs, kwargs) {
throw new ValueError(
"Cannot pass any input to an " +
`InputLayer's apply() method. InputLayer name: ${this.name}`
);
}
dispose() {
// dispose() for InputLayer is overridden as no-op.
return { refCountAfterDispose: this._refCount, numDisposedVariables: 0 };
}
getConfig() {
return {
batchInputShape: this.batchInputShape,
dtype: this.dtype,
sparse: this.sparse,
name: this.name,
};
}
}
/** @nocollapse */
input_layer_InputLayer.className = "InputLayer";
dist["serialization"].registerClass(input_layer_InputLayer);
function Input(config) {
if (config.batchShape == null && config.shape == null) {
throw new Error(
"Please provide to Input either a `shape`" +
" or a `batchShape` argument. Note that " +
"`shape` does not include the batch " +
"dimension."
);
}
if (config.batchShape != null && config.shape != null) {
// TODO(michaelterry): Backport to PyKeras.
throw new ValueError(
"Please provide either a `shape` or `batchShape` " + "argument to Input, but not both."
);
}
let batchShape = config.batchShape;
if (config.shape != null && batchShape == null) {
batchShape = [null].concat(config.shape);
}
let dtype = config.dtype;
if (dtype == null) {
dtype = "float32";
}
const inputLayer = new input_layer_InputLayer({
batchInputShape: batchShape,
name: config.name,
dtype,
sparse: config.sparse,
});
const outputs = inputLayer.inboundNodes[0].outputTensors;
return outputs[0];
}
//# sourceMappingURL=input_layer.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/logs.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Turn any Scalar values in a Logs object into actual number values.
*
* @param logs The `Logs` object to be resolved in place.
*/
async function resolveScalarsInLogs(logs) {
if (logs == null) {
return;
}
const promises = [];
const keys = [];
const scalarsToDispose = [];
for (const key in logs) {
const value = logs[key];
if (typeof value !== "number") {
const valueScalar = value;
promises.push(valueScalar.data());
keys.push(key);
scalarsToDispose.push(valueScalar);
}
}
if (promises.length > 0) {
const values = await Promise.all(promises);
for (let i = 0; i < values.length; ++i) {
logs[keys[i]] = values[i][0];
}
// Dispose the original scalar tensors.
Object(dist["dispose"])(scalarsToDispose);
}
}
/**
* Dispose all Tensors in an UnresolvedLogs object.
*
* @param logs An `UnresolvedLogs` object potentially containing `tf.Tensor`s in
* places where the values can be `tf.Tensor` or `number`.
*/
function disposeTensorsInLogs(logs) {
if (logs == null) {
return;
}
for (const key in logs) {
const value = logs[key];
if (typeof value !== "number") {
value.dispose();
}
}
}
//# sourceMappingURL=logs.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/base_callbacks.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original source: keras/callbacks.py */
/** Verbosity logging level when fitting a model. */
var ModelLoggingVerbosity;
(function (ModelLoggingVerbosity) {
ModelLoggingVerbosity[(ModelLoggingVerbosity["SILENT"] = 0)] = "SILENT";
ModelLoggingVerbosity[(ModelLoggingVerbosity["VERBOSE"] = 1)] = "VERBOSE";
})(ModelLoggingVerbosity || (ModelLoggingVerbosity = {}));
/** How often to yield to the main thread when training (in ms). */
const DEFAULT_YIELD_EVERY_MS = 125;
/**
* Abstract base class used to build new callbacks.
*
* The `logs` dictionary that callback methods take as argument will contain
* keys for quantities relevant to the current batch or epoch.
*
* Currently, the `.fit()` method of the `Sequential` model class
* will include the following quantities in the `logs` that
* it passes to its callbacks:
*
* onEpochEnd: Logs include `acc` and `loss`, and optionally include `valLoss`
* (if validation is enabled in `fit`), and `valAcc` (if validation and
* accuracy monitoring are enabled).
* onBatchBegin: Logs include `size`, the number of samples in the current
* batch.
* onBatchEnd: Logs include `loss`, and optionally `acc` (if accuracy monitoring
* is enabled).
*/
class BaseCallback {
constructor() {
// TODO(michaelterry): This type is a best guess.
this.validationData = null;
}
setParams(params) {
this.params = params;
}
async onEpochBegin(epoch, logs) {}
async onEpochEnd(epoch, logs) {}
async onBatchBegin(batch, logs) {}
async onBatchEnd(batch, logs) {}
async onTrainBegin(logs) {}
async onTrainEnd(logs) {}
// LayersModel needs to call Callback.setModel(), but cannot actually depend
// on Callback because that creates a cyclic dependency. Providing this no-op
// method on BaseCallback breaks the cycle: this way LayersModel can depend on
// BaseCallback but not on Callback. The argument is typed as `Container`
// (the superclass of LayersModel) to avoid recapitulating the cycle. Callback
// overrides this method and enforces that the argument is really a
// LayersModel.
setModel(model) {
// Do nothing. Use Callback instead of BaseCallback to track the model.
}
}
/**
* Container abstracting a list of callbacks.
*/
class CallbackList {
// TODO(cais): When the need arises, uncomment the following lines and
// implement the queue for time values.
// private deltaTBatch: number;
// private deltaTsBatchBegin: Array<number>;
// private deltaTsBatchEnd: Array<number>;
/**
* Constructor of CallbackList.
* @param callbacks Array of `Callback` instances.
* @param queueLength Queue length for keeping running statistics over
* callback execution time.
*/
constructor(callbacks, queueLength = 10) {
// TODO(cais): Make use of queueLength when implementing the queue for time
// values.
if (callbacks == null) {
callbacks = [];
}
this.callbacks = callbacks;
this.queueLength = queueLength;
}
append(callback) {
this.callbacks.push(callback);
}
setParams(params) {
for (const callback of this.callbacks) {
callback.setParams(params);
}
}
setModel(model) {
for (const callback of this.callbacks) {
callback.setModel(model);
}
}
/**
* Called at the start of an epoch.
* @param epoch Index of epoch.
* @param logs Dictionary of logs.
*/
async onEpochBegin(epoch, logs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onEpochBegin(epoch, logs);
}
}
/**
* Called at the end of an epoch.
* @param epoch Index of epoch.
* @param logs Dictionary of logs.
*/
async onEpochEnd(epoch, logs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onEpochEnd(epoch, logs);
}
}
/**
* Called right before processing a batch.
* @param batch Index of batch within the current epoch.
* @param logs Dictionary of logs.
*/
async onBatchBegin(batch, logs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onBatchBegin(batch, logs);
}
}
/**
* Called at the end of a batch.
* @param batch Index of batch within the current epoch.
* @param logs Dictionary of logs.
*/
async onBatchEnd(batch, logs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onBatchEnd(batch, logs);
}
}
/**
* Called at the beginning of training.
* @param logs Dictionary of logs.
*/
async onTrainBegin(logs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onTrainBegin(logs);
}
}
/**
* Called at the end of training.
* @param logs Dictionary of logs.
*/
async onTrainEnd(logs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onTrainEnd(logs);
}
}
}
/**
* Callback that accumulates epoch averages of metrics.
*
* This callback is automatically applied to every LayersModel.
*/
class base_callbacks_BaseLogger extends BaseCallback {
constructor() {
super();
}
async onEpochBegin(epoch) {
this.seen = 0;
this.totals = {};
}
async onBatchEnd(batch, logs) {
if (logs == null) {
logs = {};
}
const batchSize = logs["size"] == null ? 0 : logs["size"];
this.seen += batchSize;
for (const key in logs) {
const value = logs[key];
if (typeof value === "number") {
if (!this.totals.hasOwnProperty(key)) {
this.totals[key] = 0;
}
this.totals[key] = this.totals[key] + value * batchSize;
} else {
let oldTotalsToDispose;
if (key in this.totals) {
oldTotalsToDispose = this.totals[key];
} else {
this.totals[key] = 0;
}
const total = Object(dist["tidy"])(() =>
Object(dist["add"])(this.totals[key], Object(dist["mul"])(value, batchSize))
);
this.totals[key] = total;
if (oldTotalsToDispose != null) {
oldTotalsToDispose.dispose();
}
}
}
}
async onEpochEnd(epoch, logs) {
if (logs != null) {
for (const key of this.params["metrics"]) {
if (this.totals[key] == null) {
continue;
}
if (typeof this.totals[key] === "number") {
logs[key] = this.totals[key] / this.seen;
} else {
Object(dist["tidy"])(() => {
const log = Object(dist["mul"])(
Object(dist["div"])(1, this.seen),
this.totals[key]
);
logs[key] = log;
this.totals[key].dispose();
Object(dist["keep"])(logs[key]);
});
}
}
}
}
}
/**
* Callback that records events into a `History` object. This callback is
* automatically applied to every TF.js Layers model. The `History` object
* gets returned by the `fit` method of models.
*/
class History extends BaseCallback {
async onTrainBegin(logs) {
this.epoch = [];
this.history = {};
}
async onEpochEnd(epoch, logs) {
if (logs == null) {
logs = {};
}
this.epoch.push(epoch);
for (const key in logs) {
if (this.history[key] == null) {
this.history[key] = [];
}
this.history[key].push(logs[key]);
}
}
/**
* Await the values of all losses and metrics.
*/
async syncData() {
const promises = [];
const keys = [];
const indices = [];
for (const key in this.history) {
const valueArray = this.history[key];
for (let i = 0; i < valueArray.length; ++i) {
if (typeof valueArray[i] !== "number") {
const valueScalar = valueArray[i];
promises.push(valueScalar.data());
keys.push(key);
indices.push(i);
}
}
}
const values = await Promise.all(promises);
for (let n = 0; n < values.length; ++n) {
const tensorToDispose = this.history[keys[n]][indices[n]];
tensorToDispose.dispose();
this.history[keys[n]][indices[n]] = values[n][0];
}
}
}
/**
* Custom callback for training.
*/
class base_callbacks_CustomCallback extends BaseCallback {
constructor(args, yieldEvery) {
super();
this.currentEpoch = 0;
this.yieldEvery = yieldEvery || "auto";
if (this.yieldEvery === "auto") {
this.yieldEvery = DEFAULT_YIELD_EVERY_MS;
}
if (this.yieldEvery === "never" && args.onYield != null) {
throw new Error(
"yieldEvery is `never` but you provided an `onYield` callback. " +
"Either change `yieldEvery` or remove the callback"
);
}
if (dist["util"].isNumber(this.yieldEvery)) {
// Decorate `maybeWait` so it will be called at most once every
// `yieldEvery` ms.
this.maybeWait = debounce(this.maybeWait.bind(this), this.yieldEvery);
}
this.trainBegin = args.onTrainBegin;
this.trainEnd = args.onTrainEnd;
this.epochBegin = args.onEpochBegin;
this.epochEnd = args.onEpochEnd;
this.batchBegin = args.onBatchBegin;
this.batchEnd = args.onBatchEnd;
this.yield = args.onYield;
}
async maybeWait(epoch, batch, logs) {
const ps = [];
if (this.yield != null) {
await resolveScalarsInLogs(logs);
ps.push(this.yield(epoch, batch, logs));
}
ps.push(Object(dist["nextFrame"])());
await Promise.all(ps);
}
async onEpochBegin(epoch, logs) {
this.currentEpoch = epoch;
if (this.epochBegin != null) {
await resolveScalarsInLogs(logs);
await this.epochBegin(epoch, logs);
}
}
async onEpochEnd(epoch, logs) {
const ps = [];
if (this.epochEnd != null) {
await resolveScalarsInLogs(logs);
ps.push(this.epochEnd(epoch, logs));
}
if (this.yieldEvery === "epoch") {
ps.push(Object(dist["nextFrame"])());
}
await Promise.all(ps);
}
async onBatchBegin(batch, logs) {
if (this.batchBegin != null) {
await resolveScalarsInLogs(logs);
await this.batchBegin(batch, logs);
}
}
async onBatchEnd(batch, logs) {
const ps = [];
if (this.batchEnd != null) {
await resolveScalarsInLogs(logs);
ps.push(this.batchEnd(batch, logs));
}
if (this.yieldEvery === "batch") {
ps.push(Object(dist["nextFrame"])());
} else if (dist["util"].isNumber(this.yieldEvery)) {
ps.push(this.maybeWait(this.currentEpoch, batch, logs));
}
await Promise.all(ps);
}
async onTrainBegin(logs) {
if (this.trainBegin != null) {
await resolveScalarsInLogs(logs);
await this.trainBegin(logs);
}
}
async onTrainEnd(logs) {
if (this.trainEnd != null) {
await resolveScalarsInLogs(logs);
await this.trainEnd(logs);
}
}
}
/**
* Standardize callbacks or configurations of them to an Array of callbacks.
*/
function standardizeCallbacks(callbacks, yieldEvery) {
if (callbacks == null) {
callbacks = {};
}
if (callbacks instanceof BaseCallback) {
return [callbacks];
}
if (Array.isArray(callbacks) && callbacks[0] instanceof BaseCallback) {
return callbacks;
}
// Convert custom callback configs to custom callback objects.
const callbackConfigs = toList(callbacks);
return callbackConfigs.map(
(callbackConfig) => new base_callbacks_CustomCallback(callbackConfig, yieldEvery)
);
}
/**
* A global registry for callback constructors to be used during
* LayersModel.fit().
*/
class base_callbacks_CallbackConstructorRegistry {
/**
* Blocks public access to constructor.
*/
constructor() {}
/**
* Register a tf.LayersModel.fit() callback constructor.
*
* The registered callback constructor will be used to instantiate
* callbacks for every tf.LayersModel.fit() call afterwards.
*
* @param verbosityLevel Level of verbosity at which the `callbackConstructor`
* is to be reigstered.
* @param callbackConstructor A no-arg constructor for `tf.Callback`.
* @throws Error, if the same callbackConstructor has been registered before,
* either at the same or a different `verbosityLevel`.
*/
static registerCallbackConstructor(verbosityLevel, callbackConstructor) {
dist["util"].assert(
verbosityLevel >= 0 && Number.isInteger(verbosityLevel),
() =>
`Verbosity level is expected to be an integer >= 0, ` + `but got ${verbosityLevel}`
);
base_callbacks_CallbackConstructorRegistry.checkForDuplicate(callbackConstructor);
if (base_callbacks_CallbackConstructorRegistry.constructors[verbosityLevel] == null) {
base_callbacks_CallbackConstructorRegistry.constructors[verbosityLevel] = [];
}
base_callbacks_CallbackConstructorRegistry.constructors[verbosityLevel].push(
callbackConstructor
);
}
static checkForDuplicate(callbackConstructor) {
for (const levelName in base_callbacks_CallbackConstructorRegistry.constructors) {
const constructors =
base_callbacks_CallbackConstructorRegistry.constructors[+levelName];
constructors.forEach((ctor) => {
if (ctor === callbackConstructor) {
throw new ValueError("Duplicate callback constructor.");
}
});
}
}
/**
* Clear all registered callback constructors.
*/
static clear() {
base_callbacks_CallbackConstructorRegistry.constructors = {};
}
/**
* Create callbacks using the registered callback constructors.
*
* Given `verbosityLevel`, all constructors registered at that level or above
* will be called and the instantiated callbacks will be used.
*
* @param verbosityLevel: Level of verbosity.
*/
static createCallbacks(verbosityLevel) {
const constructors = [];
for (const levelName in base_callbacks_CallbackConstructorRegistry.constructors) {
const level = +levelName;
if (verbosityLevel >= level) {
constructors.push(...base_callbacks_CallbackConstructorRegistry.constructors[level]);
}
}
return constructors.map((ctor) => new ctor());
}
}
base_callbacks_CallbackConstructorRegistry.constructors = {};
function configureCallbacks(
callbacks,
verbose,
epochs,
initialEpoch,
numTrainSamples,
stepsPerEpoch,
batchSize,
doValidation,
callbackMetrics
) {
const history = new History();
const actualCallbacks = [
new base_callbacks_BaseLogger(),
...base_callbacks_CallbackConstructorRegistry.createCallbacks(verbose),
];
if (callbacks != null) {
actualCallbacks.push(...callbacks);
}
actualCallbacks.push(history);
const callbackList = new CallbackList(actualCallbacks);
// TODO(cais): Figure out when this LayersModel instance can have a
// dynamically
// set property called 'callback_model' as in PyKeras.
callbackList.setParams({
epochs,
initialEpoch,
samples: numTrainSamples,
steps: stepsPerEpoch,
batchSize,
verbose,
doValidation,
metrics: callbackMetrics,
});
return { callbackList, history };
}
//# sourceMappingURL=base_callbacks.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/serialization.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original Source layers/__init__.py */
/**
* Instantiate a layer from a config dictionary.
* @param config dict of the form {class_name: str, config: dict}
* @param customObjects dict mapping class names (or function names)
* of custom (non-Keras) objects to class/functions
* @param fastWeightInit Optional flag to use fast weight initialization
* during deserialization. This is applicable to cases in which
* the initialization will be immediately overwritten by loaded weight
* values. Default: `false`.
* @returns Layer instance (may be LayersModel, Sequential, Layer...)
*/
function deserialize(config, customObjects = {}, fastWeightInit = false) {
return deserializeKerasObject(
config,
dist["serialization"].SerializationMap.getMap().classNameMap,
customObjects,
"layer",
fastWeightInit
);
}
//# sourceMappingURL=serialization.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/losses.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original Source: losses.py */
/**
* Normalizes a tensor wrt the L2 norm alongside the specified axis.
* @param x
* @param axis Axis along which to perform normalization.
*/
function l2Normalize(x, axis) {
return Object(dist["tidy"])(() => {
if (x.dtype !== "float32") {
x = x.asType("float32");
}
const squareSum = dist["sum"](square(x), axis, true);
const epsilonTensor = dist["fill"](squareSum.shape, common_epsilon());
const norm = dist["sqrt"](dist["maximum"](squareSum, epsilonTensor));
return dist["div"](x, norm);
});
}
function meanSquaredError(yTrue, yPred) {
return Object(dist["tidy"])(() => dist["mean"](square(dist["sub"](yPred, yTrue)), -1));
}
function meanAbsoluteError(yTrue, yPred) {
return Object(dist["tidy"])(() => dist["mean"](dist["abs"](dist["sub"](yPred, yTrue)), -1));
}
function meanAbsolutePercentageError(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const diff = dist["sub"](yTrue, yPred);
const clippedTrue = dist["clipByValue"](
dist["abs"](yTrue),
common_epsilon(),
Number.MAX_VALUE
);
const absResult = dist["abs"](dist["div"](diff, clippedTrue));
return dist["mul"](100, dist["mean"](absResult, -1));
});
}
function meanSquaredLogarithmicError(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const clippedPred = dist["clipByValue"](yPred, common_epsilon(), Number.MAX_VALUE);
const firstLog = dist["log"](dist["add"](1, clippedPred));
const clippedTrue = dist["clipByValue"](yTrue, common_epsilon(), Number.MAX_VALUE);
const secondLog = dist["log"](dist["add"](1, clippedTrue));
return dist["mean"](square(dist["sub"](firstLog, secondLog)), -1);
});
}
function squaredHinge(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const maxResult = dist["maximum"](0, dist["sub"](1, dist["mul"](yTrue, yPred)));
return dist["mean"](square(maxResult), -1);
});
}
function hinge(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const maxResult = dist["maximum"](0, dist["sub"](1, dist["mul"](yTrue, yPred)));
return dist["mean"](maxResult, -1);
});
}
function categoricalHinge(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const pos = dist["sum"](dist["mul"](yTrue, yPred), -1);
const neg = dist["max"](dist["mul"](dist["sub"](1, yTrue), yPred), -1);
return dist["maximum"](0, dist["add"](1, dist["sub"](neg, pos)));
});
}
/**
* Logarithm of the hyperbolic cosine of the prediction error.
*
* `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and
* to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly
* like the mean squared error, but will not be so strongly affected by the
* occasional wildly incorrect prediction.
*/
function logcosh(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const log2 = Math.log(2);
const predictionDiff = dist["sub"](yPred, yTrue);
const logcoshResult = dist["sub"](
dist["add"](predictionDiff, dist["softplus"](dist["mul"](-2, predictionDiff))),
log2
);
return dist["mean"](logcoshResult, -1);
});
}
function categoricalCrossentropy(target, output, fromLogits = false) {
return Object(dist["tidy"])(() => {
if (fromLogits) {
output = dist["softmax"](output);
} else {
// scale preds so that the class probabilities of each sample sum to 1.
const outputSum = dist["sum"](output, output.shape.length - 1, true);
output = dist["div"](output, outputSum);
}
output = dist["clipByValue"](output, common_epsilon(), 1 - common_epsilon());
return dist["neg"](
dist["sum"](dist["mul"](target.toFloat(), dist["log"](output)), output.shape.length - 1)
);
});
}
/**
* Categorical crossentropy with integer targets.
*
* @param target An integer tensor.
* @param output A tensor resulting from a softmax (unless `fromLogits` is
* `true`, in which case `output` is expected to be the logits).
* @param fromLogits Boolean, whether `output` is the result of a softmax, or is
* a tensor of logits.
*/
function sparseCategoricalCrossentropy(target, output, fromLogits = false) {
return Object(dist["tidy"])(() => {
const flatTarget = dist["floor"](flatten(target)).toInt();
output = dist["clipByValue"](output, common_epsilon(), 1 - common_epsilon());
const outputShape = output.shape;
const oneHotTarget = dist["oneHot"](
flatTarget,
outputShape[outputShape.length - 1]
).reshape(outputShape);
return categoricalCrossentropy(oneHotTarget, output, fromLogits);
});
}
/**
* From TensorFlow's implementation in nn_impl.py:
*
* For brevity, let `x = logits`, `z = labels`. The logistic loss is
* z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
* = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))
* = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
* = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
* = (1 - z) * x + log(1 + exp(-x))
* = x - x * z + log(1 + exp(-x))
* For x < 0, to avoid overflow in exp(-x), we reformulate the above
* x - x * z + log(1 + exp(-x))
* = log(exp(x)) - x * z + log(1 + exp(-x))
* = - x * z + log(1 + exp(x))
* Hence, to ensure stability and avoid overflow, the implementation uses this
* equivalent formulation
* max(x, 0) - x * z + log(1 + exp(-abs(x)))
*
* @param labels The labels.
* @param logits The logits.
*/
function sigmoidCrossEntropyWithLogits(labels, logits) {
if (!dist["util"].arraysEqual(labels.shape, logits.shape)) {
throw new ValueError(
`logits and labels must have the same shape, but got shapes ` +
`${JSON.stringify(labels.shape)} and ${JSON.stringify(logits.shape)}`
);
}
return Object(dist["tidy"])(() => {
// The logistic loss formula from above is
// x - x * z + log(1 + exp(-x))
// For x < 0, a more numerically stable formula is
// -x * z + log(1 + exp(x))
// Note that these two expressions can be combined into the following:
// max(x, 0) - x * z + log(1 + exp(-abs(x)))
const reluLogits = logits.relu();
const negAbsLogits = logits.abs().neg();
return reluLogits.sub(logits.mul(labels)).add(negAbsLogits.exp().log1p());
});
}
function binaryCrossentropy(yTrue, yPred) {
return Object(dist["tidy"])(() => {
let y;
y = dist["clipByValue"](yPred, common_epsilon(), 1 - common_epsilon());
y = dist["log"](dist["div"](y, dist["sub"](1, y)));
return dist["mean"](sigmoidCrossEntropyWithLogits(yTrue, y), -1);
});
}
function kullbackLeiblerDivergence(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const clippedTrue = dist["clipByValue"](yTrue, common_epsilon(), 1);
const clippedPred = dist["clipByValue"](yPred, common_epsilon(), 1);
return dist["sum"](
dist["mul"](yTrue, dist["log"](dist["div"](clippedTrue, clippedPred))),
-1
);
});
}
function poisson(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const logPred = dist["log"](dist["add"](common_epsilon(), yPred));
return dist["mean"](dist["sub"](yPred, dist["mul"](yTrue, logPred)), -1);
});
}
function cosineProximity(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const trueNormalized = l2Normalize(yTrue, -1);
const predNormalized = l2Normalize(yPred, -1);
const trueXPred = dist["mul"](trueNormalized, predNormalized);
return dist["neg"](dist["sum"](trueXPred, -1));
});
}
const mse = meanSquaredError;
const MSE = meanSquaredError;
const mae = meanAbsoluteError;
const MAE = meanAbsoluteError;
const mape = meanAbsolutePercentageError;
const MAPE = meanAbsolutePercentageError;
const msle = meanSquaredLogarithmicError;
const MSLE = meanSquaredLogarithmicError;
const kld = kullbackLeiblerDivergence;
const KLD = kullbackLeiblerDivergence;
const cosine = cosineProximity;
// TODO(michaelterry): Add deserialize() function.
const lossesMap = {
meanSquaredError,
meanAbsoluteError,
meanAbsolutePercentageError,
meanSquaredLogarithmicError,
squaredHinge,
hinge,
categoricalHinge,
logcosh,
categoricalCrossentropy,
sparseCategoricalCrossentropy,
binaryCrossentropy,
kullbackLeiblerDivergence,
poisson,
cosineProximity,
};
// Porting note: This diverges from the PyKeras implementation and may need to
// change based on (de)serialization requirements.
function get(identifierOrFn) {
if (typeof identifierOrFn === "string") {
if (identifierOrFn in lossesMap) {
return lossesMap[identifierOrFn];
}
let errMsg = `Unknown loss ${identifierOrFn}`;
if (identifierOrFn.toLowerCase().includes("softmaxcrossentropy")) {
errMsg =
`Unknown loss ${identifierOrFn}. ` +
'Use "categoricalCrossentropy" as the string name for ' +
"tf.losses.softmaxCrossEntropy";
}
throw new ValueError(errMsg);
} else {
return identifierOrFn;
}
}
//# sourceMappingURL=losses.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/metrics.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Built-in metrics.
*/
function binaryAccuracy(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const threshold = dist["mul"](0.5, dist["onesLike"](yPred));
const yPredThresholded = cast(dist["greater"](yPred, threshold), yTrue.dtype);
return dist["mean"](dist["equal"](yTrue, yPredThresholded), -1);
});
}
function categoricalAccuracy(yTrue, yPred) {
return Object(dist["tidy"])(() =>
cast(dist["equal"](dist["argMax"](yTrue, -1), dist["argMax"](yPred, -1)), "float32")
);
}
function truePositives(yTrue, yPred) {
return Object(dist["tidy"])(() => {
return dist["logicalAnd"](yTrue.equal(1), yPred.equal(1)).sum().cast("float32");
});
}
function falseNegatives(yTrue, yPred) {
return Object(dist["tidy"])(() => {
return dist["logicalAnd"](yTrue.equal(1), yPred.equal(0)).sum().cast("float32");
});
}
function falsePositives(yTrue, yPred) {
return Object(dist["tidy"])(() => {
return dist["logicalAnd"](yTrue.equal(0), yPred.equal(1)).sum().cast("float32");
});
}
function precision(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const tp = truePositives(yTrue, yPred);
const fp = falsePositives(yTrue, yPred);
const denominator = tp.add(fp);
return dist["where"](dist["greater"](denominator, 0), tp.div(denominator), 0).cast(
"float32"
);
});
}
function recall(yTrue, yPred) {
return Object(dist["tidy"])(() => {
const tp = truePositives(yTrue, yPred);
const fn = falseNegatives(yTrue, yPred);
const denominator = tp.add(fn);
return dist["where"](dist["greater"](denominator, 0), tp.div(denominator), 0).cast(
"float32"
);
});
}
function metrics_binaryCrossentropy(yTrue, yPred) {
return binaryCrossentropy(yTrue, yPred);
}
function sparseCategoricalAccuracy(yTrue, yPred) {
if (yTrue.rank === yPred.rank) {
yTrue = yTrue.squeeze([yTrue.rank - 1]);
}
yPred = yPred.argMax(-1);
if (yPred.dtype !== yTrue.dtype) {
yPred = yPred.asType(yTrue.dtype);
}
return dist["equal"](yTrue, yPred).asType("float32");
}
function topKCategoricalAccuracy(yTrue, yPred) {
throw new NotImplementedError();
}
function sparseTopKCategoricalAccuracy(yTrue, yPred) {
throw new NotImplementedError();
}
// Aliases.
const metrics_mse = meanSquaredError;
const metrics_MSE = meanSquaredError;
const metrics_mae = meanAbsoluteError;
const metrics_MAE = meanAbsoluteError;
const metrics_mape = meanAbsolutePercentageError;
const metrics_MAPE = meanAbsolutePercentageError;
const metrics_categoricalCrossentropy = categoricalCrossentropy;
const metrics_cosine = cosineProximity;
const metrics_sparseCategoricalCrossentropy = sparseCategoricalCrossentropy;
// TODO(cais, nielsene): Add serialize().
const metricsMap = {
binaryAccuracy,
categoricalAccuracy,
precision,
categoricalCrossentropy: metrics_categoricalCrossentropy,
sparseCategoricalCrossentropy: metrics_sparseCategoricalCrossentropy,
mse: metrics_mse,
MSE: metrics_MSE,
mae: metrics_mae,
MAE: metrics_MAE,
mape: metrics_mape,
MAPE: metrics_MAPE,
cosine: metrics_cosine,
};
function metrics_get(identifier) {
if (typeof identifier === "string" && identifier in metricsMap) {
return metricsMap[identifier];
} else if (typeof identifier !== "string" && identifier != null) {
return identifier;
} else {
throw new ValueError(`Unknown metric ${identifier}`);
}
}
/**
* Get the shortcut function name.
*
* If the fn name is a string,
* directly return the string name.
* If the function is included in metricsMap or lossesMap,
* return key of the map.
* - If the function relative to multiple keys,
* return the first found key as the function name.
* - If the function exists in both lossesMap and metricsMap,
* search lossesMap first.
* If the function is not included in metricsMap or lossesMap,
* return the function name.
*
* @param fn loss function, metric function, or short cut name.
* @returns Loss or Metric name in string.
*/
function getLossOrMetricName(fn) {
assert(fn !== null, `Unknown LossOrMetricFn ${fn}`);
if (typeof fn === "string") {
return fn;
} else {
let fnName;
for (const key of Object.keys(lossesMap)) {
if (lossesMap[key] === fn) {
fnName = key;
break;
}
}
if (fnName !== undefined) {
return fnName;
}
for (const key of Object.keys(metricsMap)) {
if (metricsMap[key] === fn) {
fnName = key;
break;
}
}
if (fnName !== undefined) {
return fnName;
}
return fn.name;
}
}
//# sourceMappingURL=metrics.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/optimizers.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Optimizers.
*/
// Add (de)serialize()
// Porting note: This diverges from the PyKeras implementation and may need to
// change based on (de)serialization requirements.
function getOptimizer(identifier) {
const optimizerMap = {
Adagrad: () => dist["train"].adagrad(0.01),
Adadelta: () => dist["train"].adadelta(1, 0.95, common_epsilon()),
Adam: () => dist["train"].adam(0.001, 0.9, 0.999, common_epsilon()),
Adamax: () => dist["train"].adamax(0.002, 0.9, 0.999, common_epsilon(), 0),
RMSProp: () => dist["train"].rmsprop(0.001, 0.9, 0, common_epsilon()),
SGD: () => dist["train"].sgd(0.01),
};
optimizerMap["adagrad"] = optimizerMap["Adagrad"];
optimizerMap["adadelta"] = optimizerMap["Adadelta"];
optimizerMap["adam"] = optimizerMap["Adam"];
optimizerMap["adamax"] = optimizerMap["Adamax"];
optimizerMap["rmsprop"] = optimizerMap["RMSProp"];
optimizerMap["sgd"] = optimizerMap["SGD"];
if (identifier in optimizerMap) {
return optimizerMap[identifier]();
}
throw new ValueError(`Unknown Optimizer ${identifier}`);
}
//# sourceMappingURL=optimizers.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/user_defined_metadata.js
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/** Utility functions related to user-defined metadata. */
// Maximum recommended serialized size for user-defined metadata.
// Beyond this limit, a warning message will be printed during model loading and
// saving.
const MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH = 1 * 1024 * 1024;
/**
* Check validity of user-defined metadata.
*
* @param userDefinedMetadata
* @param modelName Name of the model that the user-defined metadata belongs to.
* Used during construction of error messages.
* @param checkSize Whether to check the size of the metadata is under
* recommended limit. Default: `false`. If `true`, will try stringify the
* JSON object and print a console warning if the serialzied size is above the
* limit.
* @throws Error if `userDefinedMetadata` is not a plain JSON object.
*/
function checkUserDefinedMetadata(userDefinedMetadata, modelName, checkSize = false) {
if (
userDefinedMetadata == null ||
typeof userDefinedMetadata !== "object" ||
Object.getPrototypeOf(userDefinedMetadata) !== Object.prototype ||
!plainObjectCheck(userDefinedMetadata)
) {
throw new Error("User-defined metadata is expected to be a JSON object, but is not.");
}
if (checkSize) {
const out = JSON.stringify(userDefinedMetadata);
if (out.length > MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH) {
console.warn(
`User-defined metadata of model "${modelName}" is too large in ` +
`size (length=${out.length} when serialized). It is not ` +
`recommended to store such large objects in user-defined metadata. ` +
`Please make sure its serialized length is <= ` +
`${MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH}.`
);
}
}
}
/**
* Check if an input is plain JSON object or any valid subfield of it.
*
* @param x The input to be checked.
* @param assertObject Whether to assert `x` is a JSON object, i.e., reject
* cases of arrays and primitives.
* @return Returns `true` if and only if `x` is a plain JSON object,
* a JSON-valid primitive including string, number, boolean and null,
* or an array of the said types.
*/
// tslint:disable-next-line:no-any
function plainObjectCheck(x) {
if (x === null) {
// Note: typeof `null` is 'object', and `null` is valid in JSON.
return true;
} else if (typeof x === "object") {
if (Object.getPrototypeOf(x) === Object.prototype) {
// `x` is a JavaScript object and its prototype is Object.
const keys = Object.keys(x);
for (const key of keys) {
if (typeof key !== "string") {
// JSON keys must be strings.
return false;
}
if (!plainObjectCheck(x[key])) {
// Recursive call.
return false;
}
}
return true;
} else {
// `x` is a JavaScript object but its prototype is not Object.
if (Array.isArray(x)) {
// `x` is a JavaScript array.
for (const item of x) {
if (!plainObjectCheck(item)) {
// Recursive call.
return false;
}
}
return true;
} else {
// `x` is a JavaScript object and its prototype is not Object,
// and it's not an Array. I.e., it's a complex object such as
// `Error` and `Date`.
return false;
}
}
} else {
// `x` is not a JavaScript object or `null`.
const xType = typeof x;
return xType === "string" || xType === "number" || xType === "boolean";
}
}
//# sourceMappingURL=user_defined_metadata.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/utils/layer_utils.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Print the summary of a LayersModel object.
*
* @param model tf.LayersModel instance.
* @param lineLength Total length of printed lines. Set this to adapt to the
* display to different terminal or console sizes.
* @param positions Relative or absolute positions of log elements in each
* line. Each number corresponds to right-most (i.e., ending) position of a
* column.
* If not provided, defaults to `[0.45, 0.85, 1]` for sequential-like
* models and `[0.33, 0.55, 0.67, 1]` for non-sequential like models.
* @param printFn Print function to use.
* It will be called on each line of the summary. You can provide a custom
* function in order to capture the string summary. Defaults to `console.log`.
*/
function printSummary(
model,
lineLength,
positions,
// tslint:disable-next-line:no-any
printFn = console.log
) {
const sequentialLike = isModelSequentialLike(model);
// Header names for different log elements.
const toDisplay = ["Layer (type)", "Output shape", "Param #"];
if (sequentialLike) {
lineLength = lineLength || 65;
positions = positions || [0.45, 0.85, 1];
} else {
lineLength = lineLength || 98;
positions = positions || [0.33, 0.55, 0.67, 1];
// Header names for different log elements.
}
if (positions[positions.length - 1] <= 1) {
// `positions` is relative. Convert it to absolute positioning.
positions = positions.map((p) => Math.floor(lineLength * p));
}
let relevantNodes;
if (!sequentialLike) {
toDisplay.push("Receives inputs");
relevantNodes = [];
for (const depth in model.nodesByDepth) {
relevantNodes.push(...model.nodesByDepth[depth]);
}
}
printFn("_".repeat(lineLength));
printRow(toDisplay, positions, printFn);
printFn("=".repeat(lineLength));
const layers = model.layers;
for (let i = 0; i < layers.length; ++i) {
if (sequentialLike) {
printLayerSummary(layers[i], positions, printFn);
} else {
printLayerSummaryWithConnections(layers[i], positions, relevantNodes, printFn);
}
printFn((i === layers.length - 1 ? "=" : "_").repeat(lineLength));
}
// tslint:disable-next-line:no-any
model.checkTrainableWeightsConsistency();
const trainableCount = countTrainableParams(model);
const nonTrainableCount = countParamsInWeights(model.nonTrainableWeights);
printFn(`Total params: ${trainableCount + nonTrainableCount}`);
printFn(`Trainable params: ${trainableCount}`);
printFn(`Non-trainable params: ${nonTrainableCount}`);
printFn("_".repeat(lineLength));
}
function countTrainableParams(model) {
let trainableCount;
// tslint:disable:no-any
if (model.collectedTrainableWeights != null) {
trainableCount = countParamsInWeights(model.collectedTrainableWeights);
} else {
trainableCount = countParamsInWeights(model.trainableWeights);
}
// tslint:enable:no-any
return trainableCount;
}
function isModelSequentialLike(model) {
let sequentialLike = true;
const nodesByDepth = [];
const nodes = [];
for (const depth in model.nodesByDepth) {
nodesByDepth.push(model.nodesByDepth[depth]);
}
for (const depthNodes of nodesByDepth) {
if (
depthNodes.length > 1 ||
(depthNodes.length === 1 && depthNodes[0].inboundLayers.length > 1)
) {
sequentialLike = false;
break;
}
nodes.push(...depthNodes);
}
if (sequentialLike) {
// Search for shared layers.
for (const layer of model.layers) {
let flag = false;
for (const node of layer.inboundNodes) {
if (nodes.indexOf(node) !== -1) {
if (flag) {
sequentialLike = false;
break;
} else {
flag = true;
}
}
}
if (!sequentialLike) {
break;
}
}
}
return sequentialLike;
}
function printRow(
fields,
positions,
// tslint:disable-next-line:no-any
printFn = console.log
) {
let line = "";
for (let i = 0; i < fields.length; ++i) {
if (i > 0) {
line = line.slice(0, line.length - 1) + " ";
}
line += fields[i];
line = line.slice(0, positions[i]);
line += " ".repeat(positions[i] - line.length);
}
printFn(line);
}
/**
* Prints a summary for a single Layer, without connectivity information.
*
* @param layer: Layer instance to print.
*/
function printLayerSummary(
layer,
positions,
// tslint:disable-next-line:no-any
printFn
) {
let outputShape;
try {
outputShape = JSON.stringify(layer.outputShape);
} catch (err) {
outputShape = "multiple";
}
const name = layer.name;
const className = layer.getClassName();
const fields = [`${name} (${className})`, outputShape, layer.countParams().toString()];
printRow(fields, positions, printFn);
}
/**
* Prints a summary for a single Layer, with connectivity information.
*/
function printLayerSummaryWithConnections(
layer,
positions,
relevantNodes,
// tslint:disable-next-line:no-any
printFn
) {
let outputShape;
try {
outputShape = JSON.stringify(layer.outputShape);
} catch (err) {
outputShape = "multiple";
}
const connections = [];
for (const node of layer.inboundNodes) {
if (
relevantNodes != null &&
relevantNodes.length > 0 &&
relevantNodes.indexOf(node) === -1
) {
continue;
}
for (let i = 0; i < node.inboundLayers.length; ++i) {
const inboundLayer = node.inboundLayers[i].name;
const inboundLayerIndex = node.nodeIndices[i];
const inboundTensorIndex = node.tensorIndices[i];
connections.push(`${inboundLayer}[${inboundLayerIndex}][${inboundTensorIndex}]`);
}
}
const name = layer.name;
const className = layer.getClassName();
const firstConnection = connections.length === 0 ? "" : connections[0];
const fields = [
`${name} (${className})`,
outputShape,
layer.countParams().toString(),
firstConnection,
];
printRow(fields, positions, printFn);
for (let i = 1; i < connections.length; ++i) {
printRow(["", "", "", connections[i]], positions, printFn);
}
}
//# sourceMappingURL=layer_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/utils/serialization_utils.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// tslint:enable
/**
* Test whether a value in an array is the name of a LayersModel or Layer.
* @param key The key name that the value is found under. Note that the key
* may not be at the level immediately above the value, if the value is in a
* nested array.
* @param index Index of the value in the Array that it is found in.
* @param value The value object.
* @returns A boolean indicating whether value is a name.
*/
function isArrayItemInputOrOutputName(key, index, value) {
return (
(key === "inboundNodes" || key === "outputLayers" || key === "inputLayers") &&
index === 0 &&
typeof value === "string"
);
}
/**
* Convert a Pythonic config object to TypeScript config object.
* @param pythonicConfig The config object to convert.
* @param key Optional key name of the object being converted.
* @returns Result of the conversion.
*/
function convertPythonicToTs(pythonicConfig, key) {
if (pythonicConfig === null) {
return null;
} else if (typeof pythonicConfig === "string") {
return toCamelCase(pythonicConfig);
} else if (typeof pythonicConfig === "number" || typeof pythonicConfig === "boolean") {
return pythonicConfig;
} else if (pythonicConfig instanceof Array) {
const tsArray = [];
const arrayLength = pythonicConfig.length;
for (let i = 0; i < arrayLength; ++i) {
const item = pythonicConfig[i];
if (isArrayItemInputOrOutputName(key, i, item)) {
tsArray.push(item);
} else {
tsArray.push(convertPythonicToTs(item, key));
}
}
return tsArray;
} else {
const tsDict = {};
for (const pythonicKey of Object.keys(pythonicConfig)) {
const pythonicValue = pythonicConfig[pythonicKey];
if (pythonicKey === "name" && typeof pythonicValue === "string") {
// Special case the 'name' key with a string value. Name values, such as
// the names of LayersModel and Layer instances, should not undergo the
// camel-case conversion.
tsDict[pythonicKey] = pythonicValue;
} else {
const tsKey = toCamelCase(pythonicKey);
tsDict[tsKey] = convertPythonicToTs(pythonicValue, tsKey);
}
}
return tsDict;
}
}
/**
* Convert a TypeScript config object to Python config object.
* @param tsConfig The config object to convert.
* @param key Optional key name of the object being converted.
* @returns Result of the conversion.
*/
function convertTsToPythonic(tsConfig, key) {
if (tsConfig === null || tsConfig === undefined) {
return null;
} else if (typeof tsConfig === "string") {
return toSnakeCase(tsConfig);
} else if (typeof tsConfig === "number" || typeof tsConfig === "boolean") {
return tsConfig;
} else if (tsConfig instanceof Array) {
const pyArray = [];
const arrayLength = tsConfig.length;
for (let i = 0; i < arrayLength; ++i) {
const item = tsConfig[i];
if (isArrayItemInputOrOutputName(key, i, item)) {
pyArray.push(item);
} else {
pyArray.push(convertTsToPythonic(item, key));
}
}
return pyArray;
} else {
const pyDict = {};
for (const tsKey of Object.keys(tsConfig)) {
const tsValue = tsConfig[tsKey];
const pyKey = toSnakeCase(tsKey);
if ((tsKey === "name" || tsKey === "className") && typeof tsValue === "string") {
// Special case the 'name' key with a string value. Name values, such as
// the names of LayersModel and Layer instances, should not undergo the
// snake-case conversion.
pyDict[pyKey] = tsValue;
} else {
pyDict[pyKey] = convertTsToPythonic(tsValue, tsKey);
}
}
return pyDict;
}
}
//# sourceMappingURL=serialization_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/version.js
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
const version = "2.0.1";
//# sourceMappingURL=version.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/engine/executor.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Executor: Evaluates SymbolicTensor based on feeds.
*/
/**
* Helper function to check the dtype and shape compatibility of a feed value.
*/
function assertFeedCompatibility(key, val) {
// Check dtype compatibility.
if (key.dtype == null || key.dtype === val.dtype) {
// a. If types match, return val tensor as is.
return val;
}
try {
// b. Attempt to convert to expected type.
return Object(dist["cast"])(val, key.dtype);
} catch (err) {
// c. If conversion fails, return helpful error.
throw new ValueError(
`The dtype of the feed (${val.dtype}) can not be cast to the dtype ` +
`of the key '${key.name}' (${key.dtype}).`
);
}
}
/**
* FeedDict: A mapping from unique SymbolicTensors to feed values for them.
* A feed value is a concrete value represented as an `Tensor`.
*/
class executor_FeedDict {
/**
* Constructor, optionally does copy-construction.
* @param feeds An Array of `Feed`s, or another `FeedDict`, in which case
* copy-construction will be performed.
*/
constructor(feeds) {
this.id2Value = {};
this.id2Mask = {};
this.name2Id = {};
if (feeds instanceof executor_FeedDict) {
for (const id in feeds.id2Value) {
this.id2Value[id] = feeds.id2Value[id];
if (id in feeds.id2Mask) {
this.id2Mask[id] = feeds.id2Mask[id];
}
}
} else {
if (feeds == null) {
return;
}
for (const feed of feeds) {
this.add(feed.key, feed.value);
}
}
}
/**
* Add a key-value pair to the FeedDict.
*
* @param key The key of the feed.
* @param value The value of the tensor feed.
* @param mask The value of the mask feed (optional).
* @returns This `FeedDict`.
* @throws ValueError: If the key `SymbolicTensor` already exists in the
* `FeedDict`.
*/
add(key, value, mask) {
if (this.id2Value[key.id] == null) {
this.id2Value[key.id] = assertFeedCompatibility(key, value);
this.name2Id[key.name] = key.id;
if (mask != null) {
this.id2Mask[key.id] = mask;
}
} else {
throw new ValueError(`Duplicate key: name=${key.name}, id=${key.id}`);
}
return this;
}
/**
* Add a Feed to the FeedDict.
* @param feed The new `Feed` to add.
* @returns This `FeedDict`.
*/
addFeed(feed) {
this.add(feed.key, feed.value);
}
/**
* Probe whether a key already exists in the FeedDict.
* @param key
*/
hasKey(key) {
return this.id2Value[key.id] != null;
}
/**
* Get all the SymbolicTensor available in this FeedDict.
*/
names() {
return Object.keys(this.name2Id);
}
/**
* Get the feed value for given key.
* @param key The SymbolicTensor, or its name (as a string), of which the
* value is sought.
* @returns If `key` exists, the corresponding feed value.
* @throws ValueError: If `key` does not exist in this `FeedDict`.
*/
getValue(key) {
if (key instanceof topology_SymbolicTensor) {
if (this.id2Value[key.id] == null) {
throw new ValueError(`Nonexistent key: ${key.name}`);
} else {
return this.id2Value[key.id];
}
} else {
const id = this.name2Id[key];
if (id == null) {
throw new ValueError(`Feed dict has no SymbolicTensor name: ${key}`);
}
return this.id2Value[id];
}
}
/**
* Get the feed mask for given key.
* @param key The SymbolicTensor, or its name (as a string), of which the
* value is sought.
* @returns If `key` exists, the corresponding feed mask.
* @throws ValueError: If `key` does not exist in this `FeedDict`.
*/
getMask(key) {
if (key instanceof topology_SymbolicTensor) {
if (this.id2Value[key.id] == null) {
throw new ValueError(`Nonexistent key: ${key.name}`);
} else {
return this.id2Mask[key.id];
}
} else {
const id = this.name2Id[key];
if (id == null) {
throw new ValueError(`Feed dict has no SymbolicTensor name: ${key}`);
}
return this.id2Mask[id];
}
}
/** Dispose all mask Tensors held by this object. */
disposeMasks() {
if (this.id2Mask != null) {
Object(dist["dispose"])(this.id2Mask);
}
}
}
// Cache for topologically sorted SymbolicTensors for given execution
// targets (i.e., fetches).
const cachedSorted = {};
// Cache for recipient count maps for given execution targets (i.e., fetches).
const cachedRecipientCounts = {};
/**
* Execute a SymbolicTensor by using concrete feed values.
*
* A `SymbolicTensor` object is a node in a computation graph of TF.js
* Layers. The object is backed by a source layer and input
* `SymbolicTensor`s to the source layer. This method evaluates
* the `call()` method of the source layer, using concrete values of the
* inputs obtained from either
* * `feedDict`, if the input key exists in `feedDict`, or else,
* * a recursive call to `execute()` itself.
*
* @param x: The `SymbolicTensor` to execute.
* @param feedDict: The feed values, as base condition of the recursion.
* execution.
* @param kwargs: Optional keyword arguments.
* @param probe: A probe object (of interface `ExecutionProbe`) used for
* testing memory footprint of `execute` calls.
* @returns Result of the execution.
* @throws ValueError: If any `SymbolicTensor`s from `InputLayer`s
* encountered during the execution lacks a feed value in `feedDict`.
*/
function execute(fetches, feedDict, kwargs, probe) {
const training = kwargs == null ? false : kwargs["training"];
const arrayFetches = Array.isArray(fetches);
const fetchArray = arrayFetches ? fetches : [fetches];
const outputNames = fetchArray.map((t) => t.name);
const finalOutputs = [];
const feedNames = feedDict.names();
for (const outputName of outputNames) {
if (feedNames.indexOf(outputName) !== -1) {
finalOutputs.push(feedDict.getValue(outputName));
} else {
finalOutputs.push(null);
}
}
if (probe != null) {
// For optional probing of memory footprint during execution.
probe.maxNumTensors = -Infinity;
probe.minNumTensors = Infinity;
}
// Check cache.
const fetchAndFeedKey = outputNames.join(",") + "|" + feedDict.names().join(",");
let sorted;
let recipientCounts;
if (cachedSorted[fetchAndFeedKey] == null) {
// Cache doesn't contain the desired combination of fetches. Compute
// topological sort for the combination for the first time.
const out = getTopologicalSortAndRecipientCounts(fetchArray, feedDict);
sorted = out.sorted;
recipientCounts = out.recipientCounts;
// Store results in cache for future use.
cachedSorted[fetchAndFeedKey] = sorted;
cachedRecipientCounts[fetchAndFeedKey] = recipientCounts;
}
sorted = cachedSorted[fetchAndFeedKey];
recipientCounts = {};
if (!training) {
Object.assign(recipientCounts, cachedRecipientCounts[fetchAndFeedKey]);
}
const internalFeedDict = new executor_FeedDict(feedDict);
// Start iterative execution on the topologically-sorted SymbolicTensors.
for (let i = 0; i < sorted.length; ++i) {
if (probe != null) {
// For optional probing of memory usage during execution.
const numTensors = Object(dist["memory"])().numTensors;
if (numTensors > probe.maxNumTensors) {
probe.maxNumTensors = numTensors;
}
if (numTensors < probe.minNumTensors) {
probe.minNumTensors = numTensors;
}
}
const symbolic = sorted[i];
const srcLayer = symbolic.sourceLayer;
if (srcLayer instanceof input_layer_InputLayer) {
continue;
}
const inputValues = [];
const inputMasks = [];
const tensorsToDispose = [];
let maskExists = false;
for (const input of symbolic.inputs) {
const value = internalFeedDict.getValue(input);
const mask = internalFeedDict.getMask(input);
inputValues.push(value);
inputMasks.push(mask);
if (mask != null) {
maskExists = true;
}
if (!training) {
recipientCounts[input.name]--;
if (
recipientCounts[input.name] === 0 &&
!feedDict.hasKey(input) &&
outputNames.indexOf(input.name) === -1 &&
!value.isDisposed &&
input.sourceLayer.stateful !== true
) {
tensorsToDispose.push(value);
}
}
}
if (maskExists) {
kwargs = kwargs || {};
kwargs["mask"] = inputMasks[0];
}
const outputTensors = toList(srcLayer.apply(inputValues, kwargs));
let outputMask = null;
if (srcLayer.supportsMasking) {
outputMask = srcLayer.computeMask(inputValues, inputMasks);
}
const layerOutputs = getNodeOutputs(symbolic);
const outputSymbolicTensors = Array.isArray(layerOutputs) ? layerOutputs : [layerOutputs];
for (let i = 0; i < outputSymbolicTensors.length; ++i) {
if (!internalFeedDict.hasKey(outputSymbolicTensors[i])) {
internalFeedDict.add(
outputSymbolicTensors[i],
outputTensors[i],
Array.isArray(outputMask) ? outputMask[0] : outputMask
);
}
const index = outputNames.indexOf(outputSymbolicTensors[i].name);
if (index !== -1) {
finalOutputs[index] = outputTensors[i];
}
}
if (!training) {
// Clean up Tensors that are no longer needed.
Object(dist["dispose"])(tensorsToDispose);
}
}
// NOTE(cais): Unlike intermediate tensors, we don't discard mask
// tensors as we go, because these tensors are sometimes passed over a
// series of mutliple layers, i.e., not obeying the immediate input
// relations in the graph. If this becomes a memory-usage concern,
// we can improve this in the future.
internalFeedDict.disposeMasks();
return arrayFetches ? finalOutputs : finalOutputs[0];
}
/**
* Sort the `SymbolicTensor`s topologically, for an array of fetches.
*
* This function calls getTopologicalSortAndRecipientCountsForOneFetch and
* merges their results.
*
* @param fetch The array of fetches requested. Must be a non-empty array.
* @param feedDict The dictionary of fed values.
* @returns sorted: Topologically-sorted array of SymbolicTensors.
* recipientCounts: Recipient counts for all SymbolicTensors in `sorted`.
*/
function getTopologicalSortAndRecipientCounts(fetches, feedDict) {
dist["util"].assert(
fetches != null && fetches.length > 0,
() => `Expected at least one fetch, got none`
);
let finalSorted = [];
let finalRecipientMap = {};
if (fetches.length === 1) {
// Special-casing 1 fetch for efficiency.
const out = getTopologicalSortAndRecipientCountsForOneFetch(fetches[0], feedDict);
finalSorted = out.sorted;
finalRecipientMap = out.recipientMap;
} else {
const visited = new Set();
for (const fetch of fetches) {
const { sorted, recipientMap } = getTopologicalSortAndRecipientCountsForOneFetch(
fetch,
feedDict
);
// Merge sorted SymbolicTensor Arrays.
for (const symbolicTensor of sorted) {
if (!visited.has(symbolicTensor.name)) {
finalSorted.push(symbolicTensor);
visited.add(symbolicTensor.name);
}
}
// Merge recipient maps.
for (const name in recipientMap) {
if (finalRecipientMap[name] == null) {
finalRecipientMap[name] = new Set();
}
recipientMap[name].forEach((recipient) => finalRecipientMap[name].add(recipient));
}
}
}
return {
sorted: finalSorted,
recipientCounts: recipientMap2Counts(finalRecipientMap),
};
}
function recipientMap2Counts(recipientMap) {
const recipientCounts = {};
for (const name in recipientMap) {
recipientCounts[name] = recipientMap[name].size;
}
return recipientCounts;
}
/**
* Sort the `SymbolicTensor`s topologically, for a single fetch.
*
* This helper function processes the upstream SymbolicTensors of a single
* fetch.
*
* @param fetch The single fetch requested.
* @param feedDict The dictionary of fed values.
* @returns sorted: Topologically-sorted array of SymbolicTensors.
* recipientMap: Recipient names for all SymbolicTensors in `sorted`.
*/
function getTopologicalSortAndRecipientCountsForOneFetch(fetch, feedDict) {
const visited = new Set();
const sorted = [];
const recipientMap = {};
// Put keys of the feedDict into visited first, so they don't have to be
// walked. This is needed in case where there are feeds for intermediate
// SymbolicTensors of the graph.
for (const key of feedDict.names()) {
visited.add(key);
}
const stack = [];
const marks = [];
// Initial population of stack and marks.
stack.push(fetch);
while (stack.length > 0) {
const top = stack[stack.length - 1];
if (visited.has(top.name)) {
stack.pop();
continue;
}
const topIsMarked = marks[marks.length - 1] === stack.length - 1;
if (top.inputs.length === 0 || topIsMarked) {
// Input SymbolicTensor or all children have been visited.
stack.pop();
sorted.push(top);
visited.add(top.name);
if (topIsMarked) {
marks.pop();
}
} else {
// A non-input SymbolicTensor whose upstream SymbolicTensors haven't
// been visited yet. Push them onto the stack.
marks.push(stack.length - 1);
for (const input of top.inputs) {
// Increment the recipient count. Note that this needs to happen
// regardless of whether the SymbolicTensor has been visited before.
if (recipientMap[input.name] == null) {
recipientMap[input.name] = new Set();
}
recipientMap[input.name].add(top.name);
if (visited.has(input.name)) {
continue; // Avoid repeated visits to the same SymbolicTensor.
}
stack.push(input);
}
}
}
return { sorted, recipientMap };
}
/**
* Get the symbolic output tensors of the node to which a given fetch belongs.
* @param fetch The fetched symbolic tensor.
* @returns The Array of symbolic tensors output by the node to which `fetch`
* belongs.
*/
function getNodeOutputs(fetch) {
let layerOutputs;
if (fetch.sourceLayer.inboundNodes.length === 1) {
layerOutputs = fetch.sourceLayer.output;
} else {
let nodeIndex = null;
for (let i = 0; i < fetch.sourceLayer.inboundNodes.length; ++i) {
for (const outputTensor of fetch.sourceLayer.inboundNodes[i].outputTensors) {
if (outputTensor.id === fetch.id) {
nodeIndex = i;
break;
}
}
}
layerOutputs = fetch.sourceLayer.getOutputAt(nodeIndex);
}
return layerOutputs;
}
//# sourceMappingURL=executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/engine/container.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original source: keras/engine/topology.py */
/**
* A Container is a directed acyclic graph of layers.
*
* It is the topological form of a "model". A LayersModel
* is simply a Container with added training routines.
*
*/
class container_Container extends topology_Layer {
constructor(args) {
// No args passed to super's constructor.
super({});
this.containerNodes = new Set();
this.name = args.name;
if (this.name == null) {
const prefix = this.getClassName().toLowerCase();
this.name = getUid(prefix);
}
this.supportsMasking = false;
this.trainable_ = true;
// TODO(michaelterry): Initialize perInputLosses/Updates here.
// Container-specific properties.
if (Array.isArray(args.inputs)) {
this.inputs = args.inputs.slice();
} else {
this.inputs = [args.inputs];
}
if (Array.isArray(args.outputs)) {
this.outputs = args.outputs.slice();
} else {
this.outputs = [args.outputs];
}
// Check for redundancy in inputs.
if (unique(this.inputs).length !== this.inputs.length) {
throw new ValueError(
"The list of inputs passed to the model is " +
"redundant. All inputs should only appear once. Found: " +
`${this.inputs.map((x) => x.name)}`
);
}
// Check for redundancy in outputs.
if (unique(this.outputs).length !== this.outputs.length) {
console.warn(
"The list of outputs passed to the model is redundant. " +
"All outputs should only appear once. Found: " +
`${this.outputs.map((x) => x.name)}`
);
}
/*
List of initial layers (1 to 1 mapping with this.inputs, hence the same
layer might appear twice)
*/
this.inputLayers = [];
this.inputLayersNodeIndices = [];
this.inputLayersTensorIndices = [];
/*
List of layers (1 to 1 mapping with this.outputs, hence the same layer
might appear twice)
*/
this.outputLayers = [];
this.outputLayersNodeIndices = [];
this.outputLayersTensorIndices = [];
/*
All layers in order of horizontal graph traversal. Entries are unique.
Includes input and output layers.
*/
this.layers = [];
/*
References to container layers that were constructed internally. We need
these to properly dispose of tensors from nested containers.
*/
this.internalContainerRefs = [];
// TODO(michaelterry): Determine if caching still needed with eager
// backend.
/*
This is for performance optimization when calling the Container on new
inputs. Every time the Container is called on a set on input tensors,
we compute the output tensors, output masks and output shapes in one pass,
then cache them here. When one of these outputs is queried later,
we retrieve it from there instead of recomputing it.
*/
// this.outputTensorCache = {};
// this.outputShapeCache = {};
// Build this.outputLayers:
for (const x of this.outputs) {
const layer = x.sourceLayer;
const nodeIndex = x.nodeIndex;
const tensorIndex = x.tensorIndex;
this.outputLayers.push(layer);
this.outputLayersNodeIndices.push(nodeIndex);
this.outputLayersTensorIndices.push(tensorIndex);
}
// TODO(michaelterry): Add output mask cache code.
// Build this.inputLayers:
for (const x of this.inputs) {
const layer = x.sourceLayer;
const nodeIndex = x.nodeIndex;
const tensorIndex = x.tensorIndex;
/*
It's supposed to be an input layer, so only one node
and one tensor output.
*/
assert(nodeIndex === 0, "input layer has >1 nodes");
assert(tensorIndex === 0, "input layer has >1 tensors");
this.inputLayers.push(layer);
this.inputLayersNodeIndices.push(nodeIndex);
this.inputLayersTensorIndices.push(tensorIndex);
}
// Build this.inputNames and this.outputNames.
this.inputNames = [];
this.outputNames = [];
this.feedInputShapes = [];
this.feedInputNames = [];
this.feedOutputNames = [];
for (let i = 0; i < this.inputLayers.length; i++) {
const layer = this.inputLayers[i];
// Check that layer is an InputLayer.
if (!(layer instanceof input_layer_InputLayer)) {
throw new TypeError(
"Input layers to a LayersModel must be InputLayer objects. " +
`Received inputs: ${args.inputs}. ` +
`Input ${i} (0-based) originates ` +
`from layer type ${layer.getClassName()}.`
);
}
this.inputNames.push(layer.name);
this.feedInputShapes.push(layer.batchInputShape);
this.feedInputNames.push(layer.name);
}
for (const layer of this.outputLayers) {
this.outputNames.push(layer.name);
}
this.internalInputShapes = this.inputs.map((x) => x.shape);
this.internalOutputShapes = this.outputs.map((x) => x.shape);
/*
Container_nodes: set of nodes included in the graph (not all nodes
included in the layers are relevant to the current graph).
*/
// ids of all nodes relevant to the Container:
const nodesDepths = {};
// To recover nodes from their ID.
const nodeIDToNode = {};
const layersDepths = {};
// To layers from their ID.
const layerIDToLayer = {};
const layerIndices = {};
const nodesInDecreasingDepth = [];
/**
* Builds a map of the graph of layers.
*
* This recursively updates the map `layerIndices`,
* the list `nodesInDecreasingDepth` and the set `containerNodes`.
*
* @param tensor Some tensor in a graph.
* @param finishedNodes Set of nodes whose subgraphs have been traversed
* completely. Useful to prevent duplicated work.
* @param nodesInProgress Set of nodes that are currently active on the
* recursion stack. Useful to detect cycles.
* @param layer Layer from which `tensor` comes from. If not provided,
* will be obtained from tensor.sourceLayer.
* @param nodeIndex Node index from which `tensor` comes from.
* @param tensorIndex TensorIndex from which `tensor` comes from.
*
* @exception RuntimeError if a cycle is detected.
*/
const buildMapOfGraph = (
tensor,
finishedNodes,
nodesInProgress,
layer,
nodeIndex,
tensorIndex
) => {
if (layer == null || nodeIndex == null || tensorIndex == null) {
layer = tensor.sourceLayer;
nodeIndex = tensor.nodeIndex;
tensorIndex = tensor.tensorIndex;
}
const node = layer.inboundNodes[nodeIndex];
// Prevent cycles.
if (nodesInProgress.indexOf(node) !== -1) {
throw new RuntimeError(
`The tensor ${tensor.name} at layer "${layer.name}" ` + "is part of a cycle."
);
}
// Don't repeat work for shared subgraphs
if (finishedNodes.indexOf(node) !== -1) {
return;
}
// Update containerNodes.
this.containerNodes.add(container_Container.nodeKey(layer, nodeIndex));
// Store the traversal order for layer sorting.
if (!(layer.id in layerIndices)) {
layerIndices[layer.id] = Object.keys(layerIndices).length;
}
if (nodesInProgress.indexOf(node) === -1) {
nodesInProgress.push(node);
}
// Propagate to all previous tensors connected to this node.
const numInboundLayers = node.inboundLayers.length;
for (let i = 0; i < numInboundLayers; i++) {
const x = node.inputTensors[i];
const layer = node.inboundLayers[i];
const nodeIndex = node.nodeIndices[i];
const tensorIndex = node.tensorIndices[i];
buildMapOfGraph(x, finishedNodes, nodesInProgress, layer, nodeIndex, tensorIndex);
}
finishedNodes.push(node);
while (nodesInProgress.indexOf(node) >= 0) {
nodesInProgress.splice(nodesInProgress.indexOf(node), 1);
}
nodesInDecreasingDepth.push(node);
};
const finishedNodes = [];
const nodesInProgress = [];
for (const x of this.outputs) {
buildMapOfGraph(x, finishedNodes, nodesInProgress);
}
const reversedNodesInDecreasingDepth = nodesInDecreasingDepth.slice().reverse();
for (const node of reversedNodesInDecreasingDepth) {
nodeIDToNode[node.id] = node;
// If the depth is not set, the node has no outbound nodes (depth 0).
if (!(node.id in nodesDepths)) {
nodesDepths[node.id] = 0;
}
let depth = nodesDepths[node.id];
// Update the depth of the corresponding layer
const previousDepth =
layersDepths[node.outboundLayer.id] == null ? 0 : layersDepths[node.outboundLayer.id];
/*
If we've seen this layer before at a higher depth, we should use that
depth instead of the node depth. This is necessary for shared layers
that have inputs at different depth levels in the graph.
*/
depth = Math.max(depth, previousDepth);
layersDepths[node.outboundLayer.id] = depth;
layerIDToLayer[node.outboundLayer.id] = node.outboundLayer;
nodesDepths[node.id] = depth;
// Update the depth of inbound nodes.
for (let i = 0; i < node.inboundLayers.length; i++) {
const inboundLayer = node.inboundLayers[i];
const nodeIndex = node.nodeIndices[i];
const inboundNode = inboundLayer.inboundNodes[nodeIndex];
const previousDepth =
nodesDepths[inboundNode.id] == null ? 0 : nodesDepths[inboundNode.id];
nodesDepths[inboundNode.id] = Math.max(depth + 1, previousDepth);
nodeIDToNode[inboundNode.id] = inboundNode;
}
}
// Build a dict {depth: list of nodes with this depth}
const nodesByDepth = {};
for (const nodeID in nodesDepths) {
const depth = nodesDepths[nodeID];
if (!(depth in nodesByDepth)) {
nodesByDepth[depth] = [];
}
nodesByDepth[depth].push(nodeIDToNode[nodeID]);
}
// Build a dict {depth: list of layers with this depth}
const layersByDepth = {};
for (const layerID in layersDepths) {
const depth = layersDepths[layerID];
if (!(depth in layersByDepth)) {
layersByDepth[depth] = [];
}
layersByDepth[depth].push(layerIDToLayer[layerID]);
}
// Get sorted list of layer depths.
let depthKeys = Object.keys(layersByDepth)
.map((x) => parseInt(x, 10))
.sort(reverseNumberCompare);
// Set this.layers and this.layersByDepth.
this.layers = [];
for (const depth of depthKeys) {
const layersForDepth = layersByDepth[depth];
// Container.layers needs to have a deterministic order:
// here we order them by traversal order.
layersForDepth.sort((a, b) => {
const aIndex = layerIndices[a.id];
const bIndex = layerIndices[b.id];
if (aIndex < bIndex) {
return -1;
}
if (aIndex > bIndex) {
return 1;
}
return 0;
});
for (const layer of layersForDepth) {
if (layer instanceof container_Container) {
this.internalContainerRefs.push(layer);
}
this.layers.push(layer);
}
}
this.layersByDepth = layersByDepth;
// Get sorted list of node depths;
depthKeys = Object.keys(nodesByDepth)
.map((x) => parseInt(x, 10))
.sort(reverseNumberCompare);
// Check that all tensors required are computable.
// computable_tensors: all tensors in the graph
// that can be computed from the inputs provided.
const computableTensors = this.inputs.slice();
// To provide a better error msg.
const layersWithCompleteInput = [];
for (const depth of depthKeys) {
for (const node of nodesByDepth[depth]) {
const layer = node.outboundLayer;
if (layer != null) {
for (const x of node.inputTensors) {
if (computableTensors.indexOf(x) === -1) {
throw new RuntimeError(
`Graph disconnected: cannot obtain value for tensor ${x}` +
` at layer "${layer.name}". ` +
"The following previous layers were accessed without " +
`issue: ${layersWithCompleteInput}`
);
}
}
for (const x of node.outputTensors) {
computableTensors.push(x);
}
layersWithCompleteInput.push(layer.name);
}
}
}
// Set this.containerNodes and this.nodesByDepth.
this.nodesByDepth = nodesByDepth;
// Ensure name unicity, which will be crucial for serialization
// (since serialized nodes refer to layers by their name).
const allNames = this.layers.map((x) => x.name);
for (const name of allNames) {
const numOccurrences = allNames.filter((x) => x === name).length;
if (numOccurrences !== 1) {
throw new RuntimeError(
`The name "${name}" is used ${numOccurrences} times ` +
"in the model. All layer names should be unique. Layer names: " +
JSON.stringify(allNames)
);
}
}
// Layer parameters.
// The new container starts with a single inbound node
// for its inputs, and no outbound nodes.
// Will be appended to by future calls to apply().
this.outboundNodes = [];
// Will be appended to below, and by future calls to apply().
this.inboundNodes = [];
// Create the node linking internal inputs to internal outputs.
// (This call has side effects.)
// tslint:disable-next-line:no-unused-expression
new Node({
outboundLayer: this,
inboundLayers: [],
nodeIndices: [],
tensorIndices: [],
inputTensors: this.inputs,
outputTensors: this.outputs,
inputMasks: this.inputs.map((x) => null),
outputMasks: this.outputs.map((x) => null),
inputShapes: this.inputs.map((x) => x.shape),
outputShapes: this.outputs.map((x) => x.shape),
});
this.built = true;
this._refCount = 1; // The ref count of a container always start at 1.
}
assertNotDisposed() {
if (this._refCount === 0) {
throw new Error(`Container '${this.name}' is already disposed.`);
}
}
/**
* Attempt to dispose a LayersModel's weights.
*
* This method decrease the reference count of the LayersModel object by 1.
*
* A LayersModel is reference-counted. Its reference count is incremented by 1
* when it is first constructed and when it is used as a Layer of another
* LayersModel.
*
* If the reference count of a LayersModel becomes 0, the `dispose` method of
* all its constituent `Layer`s will be called.
*
* Note: If the reference count is greater than 0 after the decrement, the
* `dispose` method of its constituent `Layer`s will *not* be called.
*
* After a LayersModel is disposed, it cannot be used in calls such as
* 'predict`, `evaluate` or `fit` anymore.
*
* @returns A DisposeResult Object with the following fields:
* - refCountAfterDispose: The reference count of the LayersModel after this
* `dispose()` call.
* - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed
* during this `dispose()` call.
* @throws {Error} If the layer is not built yet, or if the LayersModel has
* already been disposed.
*/
dispose() {
this.assertNotDisposed();
const result = { refCountAfterDispose: null, numDisposedVariables: 0 };
if (--this._refCount === 0) {
for (const layer of this.layers) {
result.numDisposedVariables += layer.dispose().numDisposedVariables;
}
// Call dispose on each internally created container layer again to ensure
// their refCounts hit zero and their tensors are subsequently deleted.
for (const container of this.internalContainerRefs) {
result.numDisposedVariables += container.dispose().numDisposedVariables;
}
}
result.refCountAfterDispose = this._refCount;
return result;
}
get trainable() {
return this.trainable_;
}
set trainable(trainable) {
this.layers.forEach((layer) => {
// tslint:disable-next-line:no-any
layer._trainableWeights.forEach((w) => (w.trainable = trainable));
});
this.trainable_ = trainable;
}
get trainableWeights() {
// Porting Note: This check below is to prevent errors where the
// _trainableWeights inherited from the parent class (Layer) gets
// inadvertently used.
if (this._trainableWeights.length > 0) {
throw new ValueError(
"Container instance unexpectedly contains _trainableWeights." +
"The trainable weights of a Container are a union of the " +
"trainable weights of its consituent Layers. Its own " +
"_trainableWeights must remain an empty Array."
);
}
if (!this.trainable) {
return [];
}
let weights = [];
for (const layer of this.layers) {
weights = weights.concat(layer.trainableWeights);
}
return weights;
}
get nonTrainableWeights() {
const weights = [];
for (const layer of this.layers) {
weights.push(...layer.nonTrainableWeights);
}
if (!this.trainable) {
const trainableWeights = [];
for (const layer of this.layers) {
trainableWeights.push(...layer.trainableWeights);
}
return trainableWeights.concat(weights);
}
return weights;
}
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
/**
* Loads all layer weights from a JSON object.
*
* Porting Note: HDF5 weight files cannot be directly loaded in JavaScript /
* TypeScript. The utility script at `scripts/pykeras.py` offers means
* to convert them into JSON strings compatible with this method.
* Porting Note: TensorFlow.js Layers supports only loading by name currently.
*
* @param weights A JSON mapping weight names to weight values as nested
* arrays of numbers, or a `NamedTensorMap`, i.e., a JSON mapping weight
* names to `tf.Tensor` objects.
* @param strict Require that the provided weights exactly match those
* required by the container. Default: `true`. Passing `false` means that
* extra weights and missing weights will be silently ignored.
*/
loadWeights(weights, strict = true) {
const nameToWeight = {};
let totalWeightsCount = 0;
for (const layer of this.layers) {
for (const weight of layer.weights) {
if (nameToWeight[weight.originalName] != null) {
throw new ValueError(`Duplicate weight name: ${weight.originalName}`);
}
nameToWeight[weight.originalName] = weight;
totalWeightsCount++;
}
}
const weightValueTuples = [];
for (const name in weights) {
// TF 2.2.0 added cell name to the weight name in the format of
// layer_name/cell_name/weight_name, we need to remove
// the inner cell name.
let validatedName = name;
if (nameToWeight[name] == null) {
const tokens = name.split("/");
const shortenNameArray = tokens.slice(0, -2).concat([tokens[tokens.length - 1]]);
validatedName = shortenNameArray.join("/");
}
if (nameToWeight[validatedName] != null) {
weightValueTuples.push([nameToWeight[validatedName], weights[name]]);
} else if (strict) {
throw new ValueError(`Provided weight data has no target variable: ${name}`);
}
delete nameToWeight[validatedName];
}
if (strict) {
// Check that all weights are set.
const unsetNames = [];
for (const name in nameToWeight) {
unsetNames.push(name);
}
if (unsetNames.length > 0) {
throw new ValueError(
`${unsetNames.length} of ${totalWeightsCount} weights are not set: ` +
`${unsetNames}`
);
}
}
batchSetValue(weightValueTuples);
}
/**
* Util shared between different serialization methods.
* @returns LayersModel config with Keras version information added.
*/
updatedConfig() {
const theConfig = this.getConfig();
const modelConfig = {};
modelConfig["className"] = this.getClassName();
modelConfig["config"] = theConfig;
modelConfig["kerasVersion"] = `tfjs-layers ${version}`;
// TODO(nielsene): Replace something like K.backend() once
// possible.
modelConfig["backend"] = "TensorFlow.js";
return modelConfig;
}
/**
* Returns a JSON string containing the network configuration.
*
* To load a network from a JSON save file, use
* models.modelFromJSON(jsonString);
* @param extraJsonArgs Unused in tfjs-layers, maintained for PyKeras
* @param returnString Whether the return value should be stringified
* (default: `true`).
* @returns a JSON string if `returnString` (default), or a JSON object if
* `!returnString`.
*/
// tslint:disable-next-line:no-any
toJSON(unused, returnString = true) {
const modelConfig = convertTsToPythonic(this.updatedConfig());
return returnString ? JSON.stringify(modelConfig) : modelConfig;
}
/**
* Call the model on new inputs.
*
* In this case `call` just reapplies all ops in the graph to the new inputs
* (e.g. build a new computational graph from the provided inputs).
*
* @param inputs A tensor or list of tensors.
* @param mask A mask or list of masks. A mask can be either a tensor or null
* (no mask).
*
* @return A tensor if there is a single output, or a list of tensors if there
* are more than one outputs.
*/
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = toList(inputs);
const feedDict = new executor_FeedDict();
for (let i = 0; i < this.inputs.length; ++i) {
feedDict.add(this.inputs[i], inputs[i]);
}
return execute(this.outputs, feedDict, kwargs);
});
}
/**
* Computes an output mask tensor.
*
* @param inputs Tensor or list of tensors.
* @param mask Tensor or list of tensors.
*
* @return null or a tensor (or list of tensors, one per output tensor of the
* layer).
*/
computeMask(inputs, mask) {
return Object(dist["tidy"])(() => {
inputs = toList(inputs);
let masks;
if (mask == null) {
masks = pyListRepeat(null, inputs.length);
} else {
masks = toList(mask);
}
// TODO(michaelterry): Add support for mask caching.
return this.runInternalGraph(inputs, masks)[1];
});
}
/**
* Computes the output shape of the layer.
*
* Assumes that the layer will be built to match that input shape provided.
*
* @param inputShape A shape (tuple of integers) or a list of shape tuples
* (one per output tensor of the layer). Shape tuples can include null for
* free dimensions, instead of an integer.
*/
computeOutputShape(inputShape) {
const inputShapes = normalizeShapeList(inputShape);
if (inputShapes.length !== this.inputLayers.length) {
throw new ValueError(
`Invalid inputShape argument ${inputShape}: ` +
`model has ${this.inputLayers.length} tensor inputs.`
);
}
// TODO(michaelterry): Add caching
const layersToOutputShapes = {};
for (let i = 0; i < inputShapes.length; i++) {
const layer = this.inputLayers[i];
const inputShape = inputShapes[i];
// It's an input layer: computeOutputShape is identity,
// and there is only one node and one tensor output.
const shapeKey = layer.name + "_0_0";
layersToOutputShapes[shapeKey] = inputShape;
}
const depthKeys = Object.keys(this.nodesByDepth)
.map((x) => parseInt(x, 10))
.sort(reverseNumberCompare);
// Iterate over nodes, by depth level.
if (depthKeys.length > 1) {
for (const depth of depthKeys) {
const nodes = this.nodesByDepth[depth];
for (const node of nodes) {
// This is always a single layer, never a list.
const layer = node.outboundLayer;
if (this.inputLayers.map((x) => x.id).indexOf(layer.id) !== -1) {
// We've already covered the input layers a few lines above.
continue;
}
// Potentially redundant list, same size of node.inputTensors.
const inputShapes = [];
for (let j = 0; j < node.inboundLayers.length; j++) {
const inboundLayer = node.inboundLayers[j];
const nodeIndex = node.nodeIndices[j];
const tensorIndex = node.tensorIndices[j];
const shapeKey = `${inboundLayer.name}_${nodeIndex}_${tensorIndex}`;
const inputShape = layersToOutputShapes[shapeKey];
inputShapes.push(inputShape);
}
const outputShape = layer.computeOutputShape(singletonOrArray(inputShapes));
const outputShapes = normalizeShapeList(outputShape);
const nodeIndex = layer.inboundNodes.indexOf(node);
for (let j = 0; j < outputShapes.length; j++) {
const shapeKey = `${layer.name}_${nodeIndex}_${j}`;
layersToOutputShapes[shapeKey] = outputShapes[j];
}
}
}
}
// Read final output shapes from layersToOutputShapes.
const outputShapes = [];
const outputShapeKeys = [];
for (let i = 0; i < this.outputLayers.length; i++) {
const layer = this.outputLayers[i];
const nodeIndex = this.outputLayersNodeIndices[i];
const tensorIndex = this.outputLayersTensorIndices[i];
const shapeKey = `${layer.name}_${nodeIndex}_${tensorIndex}`;
outputShapeKeys.push(shapeKey);
}
for (let i = 0; i < outputShapeKeys.length; i++) {
const key = outputShapeKeys[i];
assert(key in layersToOutputShapes);
outputShapes.push(layersToOutputShapes[key]);
}
// TODO(michaelterry): Update cache
return singletonOrArray(outputShapes);
}
/**
* Computes output tensors for new inputs.
*
* Note:
* - Expects `inputs` to be a list (potentially with 1 element).
*
* @param inputs List of tensors
* @param masks List of masks (tensors or null).
* @return Three lists: outputTensors, outputMasks, outputShapes
*/
runInternalGraph(inputs, masks) {
if (masks == null) {
masks = pyListRepeat(null, inputs.length);
}
// Dictionary mapping reference tensors to tuples
// (computed tensor, compute mask)
// we assume a 1:1 mapping from tensor to mask
// TODO: raise exception when a `.computeMask()` call
// does not return a list the same size as `call`
const tensorMap = {};
for (let i = 0; i < this.inputs.length; ++i) {
const x = this.inputs[i];
const y = inputs[i];
const mask = masks[i];
tensorMap[x.id] = [y, mask];
}
const depthKeys = Object.keys(this.nodesByDepth)
.map((x) => parseInt(x, 10))
.sort(reverseNumberCompare);
for (const depth of depthKeys) {
const nodes = this.nodesByDepth[depth];
for (const node of nodes) {
// This is always a single layer, never a list.
const layer = node.outboundLayer;
const referenceInputTensors = node.inputTensors;
const referenceOutputTensors = node.outputTensors;
// If all previous input tensors are available in tensorMap,
// then call node.inboundLayer on them.
// List of tuples [input, mask]:
const computedData = new Array();
for (const x of referenceInputTensors) {
if (x.id in tensorMap) {
computedData.push(tensorMap[x.id]);
}
}
if (computedData.length === referenceInputTensors.length) {
// TODO(michaelterry): Add K.name_scope here, if we need it.
let kwargs = {};
let computedTensors;
let computedMasks;
let outputTensors;
let outputMasks;
// call layer
if (node.callArgs != null) {
kwargs = node.callArgs;
}
if (computedData.length === 1) {
const [computedTensor, computedMask] = computedData[0];
if (kwargs["mask"] == null) {
kwargs["mask"] = computedMask;
}
outputTensors = toList(layer.call(computedTensor, kwargs));
outputMasks = toList(layer.computeMask(computedTensor, computedMask));
computedTensors = [computedTensor];
computedMasks = [computedMask];
} else {
computedTensors = computedData.map((x) => x[0]);
computedMasks = computedData.map((x) => x[1]);
if (kwargs["mask"] == null) {
kwargs["mask"] = computedMasks;
}
outputTensors = toList(layer.call(computedTensors, kwargs));
outputMasks = toList(layer.computeMask(computedTensors, computedMasks));
}
if (layer.activityRegularizer) {
throw new NotImplementedError(
"LayersModel invocation with concrete Tensor value(s) in the " +
"presence of activity regularizer(s) is not supported yet."
);
}
// TODO(michaelterry): Add model updates and losses
// Update tensor map.
for (let i = 0; i < referenceOutputTensors.length; ++i) {
const x = referenceOutputTensors[i];
const y = outputTensors[i];
const mask = outputMasks[i];
tensorMap[x.id] = [y, mask];
}
}
}
}
const outputTensors = [];
const outputMasks = [];
const outputShapes = [];
for (const x of this.outputs) {
assert(x.id in tensorMap, `Could not compute output ${x.name} : ${x.id}`);
const [tensor, mask] = tensorMap[x.id];
outputShapes.push(tensor.shape);
outputTensors.push(tensor);
outputMasks.push(mask);
}
// TODO(michaelterry): Add support for caches.
return [outputTensors, outputMasks, outputShapes];
}
/**
* Builds a map of internal node keys to node ordering.
* Used in serializaion a node orderings may change as unused nodes are
* dropped. Porting Note: This helper method was pulled out of getConfig to
* improve readability.
* @param layers An array of Layers in the model.
* @returns Map of Node Keys to index order within the layer.
*/
buildNodeConversionMap(layers) {
const nodeConversionMap = {};
let keptNodes;
for (const layer of this.layers) {
keptNodes = layer instanceof container_Container ? 1 : 0;
for (
let originalNodeIndex = 0;
originalNodeIndex < layer.inboundNodes.length;
originalNodeIndex++
) {
const nodeKey = container_Container.nodeKey(layer, originalNodeIndex);
if (this.containerNodes.has(nodeKey)) {
// i.e. we mark it to be saved
nodeConversionMap[nodeKey] = keptNodes;
keptNodes += 1;
}
}
}
return nodeConversionMap;
}
/**
* Retrieves a layer based on either its name (unique) or index.
*
* Indices are based on order of horizontal graph traversal (bottom-up).
*
* If both `name` and `index` are specified, `index` takes precedence.
*
* @param name Name of layer.
* @param index Index of layer.
* @returns A Layer instance.
* @throws ValueError: In case of invalid layer name or index.
*/
/**
* @doc {
* heading: 'Layers',
* subheading: 'Classes',
* namespace: 'layers',
* subclasses: ['LayersModel']
* }
*/
getLayer(name, index) {
if (index != null) {
if (this.layers.length <= index) {
throw new ValueError(
`Was asked to retrieve layer at index ${index}, but model only ` +
`has ${this.layers.length} layer(s).`
);
} else {
return this.layers[index];
}
} else {
if (name == null) {
throw new ValueError("Provide either a layer name or layer index");
}
}
for (const layer of this.layers) {
if (layer.name === name) {
return layer;
}
}
throw new ValueError(`No such layer: ${name}`);
}
/**
* Retrieves the Container's current loss values.
*
* Used for regularizers during training.
*/
calculateLosses() {
// Porting Node: This is an augmentation to Container.loss in PyKeras.
// In PyKeras, Container.loss returns symbolic tensors. Here a concrete
// Tensor (specifically Scalar) values are returned. This is due to the
// imperative backend.
return Object(dist["tidy"])(() => {
const losses = [];
for (const layer of this.layers) {
for (let nodeIndex = 0; nodeIndex < layer.inboundNodes.length; ++nodeIndex) {
const nodeKey = container_Container.nodeKey(layer, nodeIndex);
if (this.containerNodes.has(nodeKey)) {
losses.push(...layer.calculateLosses());
}
}
}
// TODO(cais): Add any unconditional model-level losses?
return losses;
});
}
getConfig() {
const config = { name: this.name };
// Build a map from layer unique name (self._node_key)
// to the index of the nodes that are saved in the config.
// Only nodes in container_nodes are saved.
const nodeConversionMap = this.buildNodeConversionMap(this.layers);
// Serialize and save the layers in layerConfigs
const layerConfigs = [];
for (const layer of this.layers) {
const layerClassName = layer.getClassName();
const layerConfig = layer.getConfig();
const filteredInboundNodes = [];
for (
let originalNodeIndex = 0;
originalNodeIndex < layer.inboundNodes.length;
originalNodeIndex++
) {
const node = layer.inboundNodes[originalNodeIndex];
const nodeKey = container_Container.nodeKey(layer, originalNodeIndex);
let kwargs = {};
if (this.containerNodes.has(nodeKey)) {
// The node is relevant to the model:
// add to filteredInboundNodes.
if (node.callArgs) {
try {
JSON.stringify(node.callArgs);
kwargs = node.callArgs;
} catch (err) {
console.warn(
`Layer ${layer.name} was passed ` +
`non-serializable keyword arguments: ` +
`${node.callArgs}. They will not be included ` +
`in the serialized model (and thus will be ` +
`missing at deserialization time).`
);
kwargs = {};
}
}
if (node.inboundLayers.length > 0) {
const nodeData = [];
for (let i = 0; i < node.inboundLayers.length; i++) {
const inboundLayer = node.inboundLayers[i];
const nodeIndex = node.nodeIndices[i];
const tensorIndex = node.tensorIndices[i];
const nodeKey = container_Container.nodeKey(inboundLayer, nodeIndex);
let newNodeIndex = nodeConversionMap[nodeKey];
if (newNodeIndex == null) {
newNodeIndex = 0;
}
nodeData.push([inboundLayer.name, newNodeIndex, tensorIndex, kwargs]);
}
filteredInboundNodes.push(nodeData);
}
}
}
const dict = {};
dict["name"] = layer.name;
dict["className"] = layerClassName;
dict["config"] = layerConfig;
dict["inboundNodes"] = filteredInboundNodes;
layerConfigs.push(dict);
}
config["layers"] = layerConfigs;
// Gather info about inputs and outputs
const modelInputs = [];
for (let i = 0; i < this.inputLayers.length; i++) {
const layer = this.inputLayers[i];
const nodeIndex = this.inputLayersNodeIndices[i];
const nodeKey = container_Container.nodeKey(layer, nodeIndex);
if (!this.containerNodes.has(nodeKey)) {
continue;
}
let newNodeIndex = nodeConversionMap[nodeKey];
if (newNodeIndex === null || newNodeIndex === undefined) {
newNodeIndex = 0;
}
const tensorIndex = this.inputLayersTensorIndices[i];
modelInputs.push([layer.name, newNodeIndex, tensorIndex]);
}
config["inputLayers"] = modelInputs;
const modelOutputs = [];
for (let i = 0; i < this.outputLayers.length; i++) {
const layer = this.outputLayers[i];
const nodeIndex = this.outputLayersNodeIndices[i];
const nodeKey = container_Container.nodeKey(layer, nodeIndex);
if (!this.containerNodes.has(nodeKey)) {
continue;
}
let newNodeIndex = nodeConversionMap[nodeKey];
if (newNodeIndex === null || newNodeIndex === undefined) {
newNodeIndex = 0;
}
const tensorIndex = this.outputLayersTensorIndices[i];
modelOutputs.push([layer.name, newNodeIndex, tensorIndex]);
}
config["outputLayers"] = modelOutputs;
return config;
}
/**
* Instantiates a LayersModel from its config (output of `get_config()`).
* @param cls the class to create
* @param config LayersModel config dictionary.
* @param customObjects An optional dictionary of custom objects.
* @param fastWeightInit Optional flag to use fast weight initialization
* during deserialization. This is applicable to cases in which
* the initialization will be immediately overwritten by loaded weight
* values. Default: `false`.
* @returns A LayersModel instance.
* @throws ValueError: In case of improperly formatted config dict.
*/
/** @nocollapse */
static fromConfig(cls, config, customObjects = {}, fastWeightInit = false) {
// Layer instances created during
// the graph reconstruction process
const createdLayers = {};
// Dictionary mapping layer instances to
// node data that specifies a layer call.
// It acts as a queue that maintains any unprocessed
// layer call until it becomes possible to process it
// (i.e. until the input tensors to the call all exist).
const unprocessedNodes = {};
function addUnprocessedNode(layer, nodeData) {
if (!(layer.name in unprocessedNodes)) {
unprocessedNodes[layer.name] = [nodeData];
} else {
unprocessedNodes[layer.name].push(nodeData);
}
}
function processNode(layer, nodeData) {
const inputTensors = [];
let kwargs;
for (const inputData of nodeData) {
const inboundLayerName = inputData[0];
const inboundNodeIndex = inputData[1];
const inboundTensorIndex = inputData[2];
kwargs = inputData[3] == null ? {} : inputData[3];
if (!(inboundLayerName in createdLayers)) {
addUnprocessedNode(layer, nodeData);
return;
}
const inboundLayer = createdLayers[inboundLayerName];
if (inboundLayer.inboundNodes.length <= inboundNodeIndex) {
addUnprocessedNode(layer, nodeData);
return;
}
const inboundNode = inboundLayer.inboundNodes[inboundNodeIndex];
inputTensors.push(inboundNode.outputTensors[inboundTensorIndex]);
}
// Call layer on its inputs, thus creating the node
// and building the layer if needed.
// Note: This has Eager vs Graph Implications.
if (inputTensors.length > 0) {
layer.apply(singletonOrArray(inputTensors), kwargs); // was ** kwargs
}
}
/**
* Deserialize a layer, then call it on appropriate inputs.
* @param layerData: layer config dict.
* @throws ValueError: In case of improperly formatted `layer_data`
* dict.
*/
function processLayer(layerData) {
const layerName = layerData["name"];
// Instantiate layer.
const layer = deserialize(
layerData,
config["customObjects"] != null ? config["customObjects"] : {}
);
layer.setFastWeightInitDuringBuild(fastWeightInit);
createdLayers[layerName] = layer;
// Gather layer inputs.
const inboundNodesData = layerData["inboundNodes"];
inboundNodesData.forEach((nodeData) => {
if (!(nodeData instanceof Array)) {
throw new ValueError(
`Corrupted configuration, expected array for nodeData: ${nodeData}`
);
}
// We don't process nodes (i.e. make layer calls)
// on the fly because the inbound node may not yet exist,
// in case of layer shared at different topological depths
// (e.g.a model such as A(B(A(B(x)))))
addUnprocessedNode(layer, nodeData);
});
}
// First, we create all layers and enqueue nodes to be processed.
const name = config["name"];
const layersFromConfig = config["layers"];
for (const layerData of layersFromConfig) {
processLayer(layerData);
}
// Then we process nodes in order of layer depth.
// Nodes that cannot yet be processed(if the inbound node
// does not yet exist) are re - enqueued, and the process
// is repeated until all nodes are processed.
while (!isObjectEmpty(unprocessedNodes)) {
for (const layerData of layersFromConfig) {
const layer = createdLayers[layerData["name"]];
if (layer.name in unprocessedNodes) {
const currentUnprocessedNodesForLayer = unprocessedNodes[layer.name];
delete unprocessedNodes[layer.name];
for (const nodeData of currentUnprocessedNodesForLayer) {
processNode(layer, nodeData);
}
}
}
}
const inputTensors = [];
const outputTensors = [];
const inputLayersFromConfig = config["inputLayers"];
for (const layerData of inputLayersFromConfig) {
const layerName = layerData[0];
const nodeIndex = layerData[1];
const tensorIndex = layerData[2];
assert(layerName in createdLayers);
const layer = createdLayers[layerName];
const layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;
inputTensors.push(layerOutputTensors[tensorIndex]);
}
const outputLayersFromConfig = config["outputLayers"];
for (const layerData of outputLayersFromConfig) {
const layerName = layerData[0];
const nodeIndex = layerData[1];
const tensorIndex = layerData[2];
assert(layerName in createdLayers);
const layer = createdLayers[layerName];
const layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;
outputTensors.push(layerOutputTensors[tensorIndex]);
}
return new cls({ inputs: inputTensors, outputs: outputTensors, name });
}
/**
* Determine whether the container is stateful.
*
* Porting Note: this is the equivalent of the stateful @property of
* the Container class in PyKeras.
*/
get stateful() {
// Porting Note: This check is to prevent inadvertent setting of the
// _stateful property of the Container instance.
if (this._stateful) {
throw new ValueError(
"Container instance unexpectedly has _stateful = true. The " +
"statefulness of a Container is determined by the Layers it " +
"contains. Its _stateful property must remain the default false."
);
}
for (const layer of this.layers) {
if (layer.stateful) {
return true;
}
}
return false;
}
/**
* Reset the state of all stateful constituent layers (if any).
*
* Examples of stateful layers include RNN layers whose `stateful` property
* is set as `true`.
*/
resetStates() {
Object(dist["tidy"])(() => {
this.layers.forEach((layer) => {
// tslint:disable:no-any
if (layer.stateful) {
layer.resetStates();
}
// tslint:enable:no-any
});
});
}
}
//# sourceMappingURL=container.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/engine/training_utils.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function standardizeSampleOrClassWeights(xWeight, outputNames, weightType) {
const numOutputs = outputNames.length;
if (xWeight == null || (Array.isArray(xWeight) && xWeight.length === 0)) {
return outputNames.map((name) => null);
}
if (numOutputs === 1) {
if (Array.isArray(xWeight) && xWeight.length === 1) {
return xWeight;
} else if (typeof xWeight === "object" && outputNames[0] in xWeight) {
return [xWeight[outputNames[0]]];
} else {
return [xWeight];
}
}
if (Array.isArray(xWeight)) {
if (xWeight.length !== numOutputs) {
throw new Error(
`Provided ${weightType} is an array of ${xWeight.length} ` +
`element(s), but the model has ${numOutputs} outputs. ` +
`Make sure a set of weights is provided for each model output.`
);
}
return xWeight;
} else if (
typeof xWeight === "object" &&
Object.keys(xWeight).length > 0 &&
typeof xWeight[Object.keys(xWeight)[0]] === "object"
) {
const output = [];
outputNames.forEach((outputName) => {
if (outputName in xWeight) {
output.push(xWeight[outputName]);
} else {
output.push(null);
}
});
return output;
} else {
throw new Error(
`The model has multiple (${numOutputs}) outputs, ` +
`so ${weightType} must be either an array with ` +
`${numOutputs} elements or an object with ${outputNames} keys. ` +
`Provided ${weightType} not understood: ${JSON.stringify(xWeight)}`
);
}
}
/**
* Standardize class weighting objects.
*
* This function takes a single class-weighting object, an array of them,
* or a map from output name to class-weighting object. It compares it to the
* output name(s) of the model, base on which it outputs an array of
* class-weighting objects of which the length matches the number of outputs.
*
* @param classWeight Input class-weighting object(s).
* @param outputNames All output name(s) of the model.
* @return An array of class-weighting objects. The length of the array matches
* the model's number of outputs.
*/
function standardizeClassWeights(classWeight, outputNames) {
return standardizeSampleOrClassWeights(classWeight, outputNames, "classWeight");
}
function standardizeSampleWeights(classWeight, outputNames) {
return standardizeSampleOrClassWeights(classWeight, outputNames, "sampleWeight");
}
/**
* Standardize by-sample and/or by-class weights for training.
*
* Note that this function operates on one model output at a time. For a model
* with multiple outputs, you must call this function multiple times.
*
* @param y The target tensor that the by-sample and/or by-class weight is for.
* The values of y are assumed to encode the classes, either directly
* as an integer index, or as one-hot encoding.
* @param sampleWeight By-sample weights.
* @param classWeight By-class weights: an object mapping class indices
* (integers) to a weight (float) to apply to the model's loss for the
* samples from this class during training. This can be useful to tell the
* model to "pay more attention" to samples from an under-represented class.
* @param sampleWeightMode The mode for the sample weights.
* @return A Promise of weight tensor, of which the size of the first dimension
* matches that of `y`.
*/
async function standardizeWeights(y, sampleWeight, classWeight, sampleWeightMode) {
if (sampleWeight != null || sampleWeightMode != null) {
// TODO(cais): Once 'temporal' mode is implemented, document it in the doc
// string.
throw new Error("Support sampleWeight is not implemented yet");
}
if (classWeight != null) {
// Apply class weights per sample.
const yClasses = Object(dist["tidy"])(() => {
if (y.shape.length === 1) {
// Assume class indices.
return y.clone();
} else if (y.shape.length === 2) {
if (y.shape[1] > 1) {
// Assume one-hot encoding of classes.
const axis = 1;
return y.argMax(axis);
} else if (y.shape[1] === 1) {
// Class index.
return y.reshape([y.shape[0]]);
} else {
throw new Error(
`Encountered unexpected last-dimension size (${y.shape[1]}) ` +
`during handling of class weights. The size is expected to be ` +
`>= 1.`
);
}
} else {
throw new Error(
`Unexpected rank of target (y) tensor (${y.rank}) during ` +
`handling of class weights. The rank is expected to be 1 or 2.`
);
}
});
const yClassIndices = Array.from(await yClasses.data());
Object(dist["dispose"])(yClasses);
const classSampleWeight = [];
yClassIndices.forEach((classIndex) => {
if (classWeight[classIndex] == null) {
throw new Error(
`classWeight must contain all classes in the training data. ` +
`The class ${classIndex} exists in the data but not in ` +
`classWeight`
);
} else {
classSampleWeight.push(classWeight[classIndex]);
}
});
return Object(dist["tensor1d"])(classSampleWeight, "float32");
} else {
return null;
}
}
/**
* Apply per-sample weights on the loss values from a number of samples.
*
* @param losses Loss tensor of shape `[batchSize]`.
* @param sampleWeights Per-sample weight tensor of shape `[batchSize]`.
* @returns Tensor of the same shape as`losses`.
*/
function computeWeightedLoss(losses, sampleWeights) {
return Object(dist["mul"])(losses, sampleWeights);
}
//# sourceMappingURL=training_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/engine/training_dataset.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Interfaces and methods for training models using TensorFlow.js datasets.
*/
// Default batch size used during tensor-based validation.
const DEFAULT_VALIDATION_BATCH_SIZE = 32;
/**
* Standardize the output of a dataset iterator for use by
* LayersModel.fitDataset().
*
* @param model: A `tf.LayersModel` object.
* @param iteratorOut The output of a dataset iterator. It is required to be
* an object of the form `{xs: TensorOrArrayOrMap, ys:
* TensorOrArrayOrMap}`, where `TensorOrArrayOrMap` is a single `tf.Tensor`,
* a `tf.Tensor[]`, or a flat map from string names to `tf.Tensor`s.
* @returns A flat array of `tf.Tensor` objects: the input `tf.Tensor`s
* followed by the target `tf.Tensor`s. When `tf.Tensor`s are provided
* as a map, the order in the resulting array is taken from the `inputNames`
* and `outputNames` of the model.
*/
function standardizeDataIteratorOutput(
// Type `model` as `any` here to avoid circular dependency w/
// training.ts.
// tslint:disable-next-line:no-any
model,
iteratorOut
) {
let xs;
let ys;
const iteratorOutObj = iteratorOut;
xs = iteratorOutObj["xs"];
ys = iteratorOutObj["ys"];
dist["util"].assert(
xs != null && ys != null,
() =>
"A Dataset iterator for fitDataset() is expected to generate " +
"objects of the form `{xs: xVal, ys: yVal}`, where the two " +
"values may be `tf.Tensor`, an array of Tensors, or a map of " +
"string to Tensor. The provided Dataset instead generates " +
`${iteratorOut}`
);
const flattenedXs = flattenTensorOrArrayOrMap("input", model.inputNames, xs);
const flattenedYs = flattenTensorOrArrayOrMap("output", model.outputNames, ys);
const batchSize = flattenedXs[0].shape[0];
dist["util"].assert(
flattenedXs.length === model.inputs.length,
() =>
`LayersModel has ${model.inputs.length} inputs, but the dataset ` +
`provides ${flattenedXs.length} inputs. (Expected input keys: ` +
`${JSON.stringify(model.inputNames)})`
);
dist["util"].assert(
flattenedYs.length === model.outputs.length,
() =>
`LayersModel has ${model.outputs.length} outputs, but the dataset ` +
`provides ${flattenedYs.length} outputs. (Expected output keys: ` +
`${JSON.stringify(model.outputNames)})`
);
for (let xIndex = 0; xIndex < flattenedXs.length; xIndex++) {
dist["util"].assert(
flattenedXs[xIndex].shape[0] === batchSize,
() =>
`Batch size mismatch: input ` +
`${model.inputNames[xIndex]} has ${flattenedXs[xIndex].shape[0]}; ` +
`expected ${batchSize} based on input ${model.inputNames[0]}.`
);
}
for (let yIndex = 0; yIndex < flattenedYs.length; yIndex++) {
dist["util"].assert(
flattenedYs[yIndex].shape[0] === batchSize,
() =>
`Batch size mismatch: output ` +
`${model.outputNames[yIndex]} has ${flattenedYs[yIndex].shape[0]}; ` +
`expected ${batchSize} based on input ${model.inputNames[0]}.`
);
}
return { xs: flattenedXs, ys: flattenedYs };
}
function flattenTensorOrArrayOrMap(inputOrOutput, names, values) {
if (values instanceof dist["Tensor"]) {
return [values];
} else if (Array.isArray(values)) {
dist["util"].assert(
values.length === names.length,
() =>
`Received an array of ${values.length} Tensors, but expected ${names.length} to match the ${inputOrOutput} keys ${names}.`
);
return values;
} else {
const result = [];
// Check that all the required keys are available.
for (const name of names) {
if (values[name] == null) {
throw new ValueError(
`The feature data generated by the dataset lacks the required ` +
`${inputOrOutput} key '${name}'.`
);
}
result.push(values[name]);
}
return result;
}
}
function standardizeTensorValidationData(data) {
if (data.length === 3) {
throw new NotImplementedError("Validation with sample weights is not implemented yet.");
}
return { xs: data[0], ys: data[1] };
}
async function fitDataset(
// Type `model` as `any` here to avoid circular dependency w/
// training.ts.
// tslint:disable-next-line:no-any
model,
dataset,
args
) {
const hasBatchesPerEpoch = args.batchesPerEpoch != null;
dist["util"].assert(
model.optimizer != null,
() =>
"You must compile a model before training/testing. Use " +
"LayersModel.compile(modelCompileConfig)."
);
dist["util"].assert(
args != null,
() =>
`For fitDataset(), the 2nd argument (config) is required, ` +
`but it is not provided in this call.`
);
dist["util"].assert(
args.epochs != null && args.epochs > 0 && Number.isInteger(args.epochs),
() =>
`For fitDataset(), config.epochs is expected to be a positive ` +
`integer, but got ${args.epochs}`
);
dist["util"].assert(
!hasBatchesPerEpoch ||
(args.batchesPerEpoch > 0 && Number.isInteger(args.batchesPerEpoch)),
() =>
`For fitDataset(), config.batchesPerEpoch is expected to be a ` +
`positive integer if specified, but got ${args.batchesPerEpoch}`
);
dist["util"].assert(
// tslint:disable-next-line:no-any
args["validationSplit"] == null,
() =>
"`validationSplit` is not supported by `fitDataset()`. " + "Use validationData instead."
);
if (model.isTraining) {
throw new Error("Cannot start training because another fit() call is ongoing.");
}
model.isTraining = true;
try {
const doValidation = args.validationData != null;
let valXs;
let valYs;
if (doValidation) {
if (isDatasetObject(args.validationData)) {
dist["util"].assert(
args.validationBatches == null ||
(args.validationBatches > 0 && Number.isInteger(args.validationBatches)),
() =>
`For fitDataset() with dataset-based validation, ` +
`config.validationBatches is expected not to be provided, ` +
`or to be a positive integer, ` +
`but got ${args.validationBatches}`
);
} else {
const validationData = standardizeTensorValidationData(args.validationData);
valXs = validationData.xs;
valYs = validationData.ys;
}
}
const trainFunction = model.makeTrainFunction();
const outLabels = model.getDedupedMetricsNames();
let callbackMetrics;
if (doValidation) {
callbackMetrics = outLabels.slice().concat(outLabels.map((n) => "val_" + n));
} else {
callbackMetrics = outLabels.slice();
}
const callbacks = standardizeCallbacks(args.callbacks, args.yieldEvery);
const verbose = args.verbose == null ? 1 : args.verbose;
const { callbackList, history } = configureCallbacks(
callbacks,
verbose,
args.epochs,
null,
null,
getStepsPerEpoch(dataset, args),
null, // Batch size determined by the dataset itself.
doValidation,
callbackMetrics
);
callbackList.setModel(model);
model.history = history;
await callbackList.onTrainBegin();
model.stopTraining_ = false;
let epoch = args.initialEpoch == null ? 0 : args.initialEpoch;
let dataIterator = await dataset.iterator();
while (epoch < args.epochs) {
const epochLogs = {};
await callbackList.onEpochBegin(epoch);
let stepsDone = 0;
let batchIndex = 0;
if (!hasBatchesPerEpoch) {
dataIterator = await dataset.iterator();
}
while (hasBatchesPerEpoch ? stepsDone < args.batchesPerEpoch : true) {
const iteratorOut = await dataIterator.next();
// If `batchesPerEpoch` is specified, the dataset should not be
// exhausted until all epoches are done.
if (hasBatchesPerEpoch && iteratorOut.done) {
console.warn(
"You provided `batchesPerEpoch` as " +
`${args.batchesPerEpoch}, ` +
"but your dataset iterator ran out of data after " +
`${stepsDone} batches; ` +
"interrupting training. Make sure that your " +
"dataset can generate at least `batchesPerEpoch * epochs` " +
"batches (in this case, " +
`${args.batchesPerEpoch * args.epochs} batches). ` +
"You may need to use the repeat() function when building " +
"your dataset."
);
break;
}
if (iteratorOut.value != null) {
const { xs, ys } = standardizeDataIteratorOutput(model, iteratorOut.value);
const batchLogs = {};
batchLogs["batch"] = batchIndex;
batchLogs["size"] = xs[0].shape[0];
await callbackList.onBatchBegin(batchIndex, batchLogs);
const sampleWeights = [];
if (args.classWeight != null) {
const standardClassWeights = standardizeClassWeights(
args.classWeight,
model.outputNames
);
for (let i = 0; i < standardClassWeights.length; ++i) {
sampleWeights.push(
await standardizeWeights(ys[i], null, standardClassWeights[i])
);
}
}
// Train on batch.
const ins = xs.concat(ys).concat(sampleWeights);
const outs = trainFunction(ins);
dist["dispose"](ins);
for (let i = 0; i < outLabels.length; ++i) {
const label = outLabels[i];
const out = outs[i];
batchLogs[label] = out;
dist["keep"](out);
}
await callbackList.onBatchEnd(batchIndex, batchLogs);
disposeTensorsInLogs(batchLogs);
batchIndex++;
stepsDone++;
}
if (hasBatchesPerEpoch ? stepsDone >= args.batchesPerEpoch : iteratorOut.done) {
// Epoch finished. Perform validation.
if (doValidation) {
let valOuts;
if (isDatasetObject(args.validationData)) {
valOuts = toList(
await model.evaluateDataset(args.validationData, {
batches: args.validationBatches,
})
);
} else {
valOuts = toList(
model.evaluate(valXs, valYs, {
batchSize:
args.validationBatchSize == null
? DEFAULT_VALIDATION_BATCH_SIZE
: args.validationBatchSize,
verbose: 0,
})
);
}
for (let i = 0; i < model.metricsNames.length; ++i) {
epochLogs[`val_${model.metricsNames[i]}`] = valOuts[i];
}
}
// Call `break` to exit one epoch lopp after validation is done. If
// config.batchesPerEpoch is specified, an epoch while loop will
// stop when `stepsDone >= config.batchesPerEpoch`. When
// config.batchesPerEpoch is not provided, the following `break` is
// required to exit the while lopp after dataset is exhausted.
break;
}
if (model.stopTraining_) {
break;
}
}
await callbackList.onEpochEnd(epoch, epochLogs);
epoch++;
if (model.stopTraining_) {
break;
}
}
await callbackList.onTrainEnd();
await model.history.syncData();
return model.history;
} finally {
model.isTraining = false;
}
}
/** Helper function that determines number of steps (batches) per epoch. */
function getStepsPerEpoch(dataset, args) {
// Attempt to determine # of batches in an epoch.
let stepsPerEpoch = null;
if (args.batchesPerEpoch != null) {
stepsPerEpoch = args.batchesPerEpoch;
} else if (Number.isFinite(dataset.size)) {
stepsPerEpoch = dataset.size;
}
return stepsPerEpoch;
}
// Check if provided object is a Dataset object by checking its .iterator
// element.
function isDatasetObject(dataset) {
return typeof dataset.iterator === "function";
}
// Check if provided object is a LazyIterator object by checking it's .next
// element.
function isLazyIteratorObject(iterator) {
return typeof iterator.next === "function";
}
async function evaluateDataset(
// Type `model` as `any` here to avoid circular dependency w/
// training.ts.
// tslint:disable-next-line:no-any
model,
dataset,
args
) {
args = args || {};
const hasBatches = args.batches != null;
const f = model.testFunction;
let outs = [];
if (args.verbose > 0) {
throw new NotImplementedError("Verbose mode is not implemented yet.");
}
dist["util"].assert(
!hasBatches || (args.batches > 0 && Number.isInteger(args.batches)),
() =>
"Test loop expects `batches` to be a positive integer, but " +
`received ${JSON.stringify(args.batches)}`
);
const dataIterator = isLazyIteratorObject(dataset) ? dataset : await dataset.iterator();
// Keeps track of number of examples used in this evaluation.
let numExamples = 0;
let batch = 0;
while (hasBatches ? batch < args.batches : true) {
const iteratorOut = await dataIterator.next();
outs = dist["tidy"](() => {
if (iteratorOut.value) {
// TODO(cais): Once real dataset is available, use
// `map(x => standardizeDataIteratorOutput(model, x).map(f)`.
const { xs, ys } = standardizeDataIteratorOutput(model, iteratorOut.value);
const xsAndYs = xs.concat(ys);
const batchOuts = dist["tidy"](() => f(xsAndYs));
dist["dispose"](xsAndYs);
if (batch === 0) {
for (let i = 0; i < batchOuts.length; ++i) {
outs.push(Object(dist["scalar"])(0));
}
}
const batchSize = xsAndYs[0].shape[0];
for (let i = 0; i < batchOuts.length; ++i) {
const batchOut = batchOuts[i];
const oldScalar = outs[i];
outs[i] = dist["tidy"](() =>
dist["add"](outs[i], dist["mul"](batchSize, batchOut))
);
if (batch > 0) {
dist["dispose"](oldScalar);
}
}
dist["dispose"](batchOuts);
numExamples += batchSize;
++batch;
}
return outs;
});
if (iteratorOut.done) {
if (hasBatches) {
console.warn(
"Your dataset iterator ran out of data during evaluateDataset(). " +
"Interrupting evalution. Make sure that your " +
"dataset can generate at least `batches` " +
`batches (in this case, ${args.batches} batches). ` +
"You may need to use the repeat() function when building " +
"your dataset."
);
}
break;
}
}
for (let i = 0; i < outs.length; ++i) {
const oldScalar = outs[i];
outs[i] = dist["div"](outs[i], numExamples);
dist["dispose"](oldScalar);
}
return singletonOrArray(outs);
}
//# sourceMappingURL=training_dataset.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/engine/training_tensors.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Interfaces and methods for training models using tf.Tensor objects.
*/
function checkBatchSize(batchSize) {
dist["util"].assert(
batchSize > 0 && Number.isInteger(batchSize),
() => `batchSize is required to be a positive integer, but got ${batchSize}`
);
}
/**
* Slice a Tensor or an Array of Tensors, by start and stop indices.
*
* Porting Note: The `_slice_arrays` function in PyKeras is covered by this
* function and `sliceArraysByIndices()` together.
*
* @param arrays: the input.
* @param start: the starting index (inclusive).
* @param stop: the stopping index (exclusive).
* @returns The result of the slicing. If `arrays` is an `Array` of
* `tf.Tensor`s, the slicing will be applied to all elements of the `Array`
* in the same way.
*/
function sliceArrays(arrays, start, stop) {
if (arrays == null) {
return [null];
} else if (Array.isArray(arrays)) {
return arrays.map((array) => sliceAlongFirstAxis(array, start, stop - start));
} else {
// Tensor.
return sliceAlongFirstAxis(arrays, start, stop - start);
}
}
/**
* Slice a Tensor or an Array of Tensors, by random-order indices.
*
* Porting Note: The `_slice_arrays` function in PyKeras is covered by this
* function and `sliceArrays()` together.
*
* @param arrays The input `tf.Tensor` or `Array` of `tf.Tensor`s to slice.
* If an `Array` of `tf.Tensor`s, all `tf.Tensor`s will be sliced in the
* same fashion.
* @param indices The indices to use for slicing along the first (batch)
* dimension.
* @returns Result(s) of the slicing.
*/
function sliceArraysByIndices(arrays, indices) {
return dist["tidy"](() => {
if (arrays == null) {
return null;
} else if (Array.isArray(arrays)) {
return arrays.map((array) => sliceArraysByIndices(array, indices));
} else {
// TODO(cais): indices should be a pre-constructed Tensor1D to avoid
// tensor1d() calls.
return gather(arrays, indices.dtype === "int32" ? indices : indices.toInt());
}
});
}
/**
* Returns a list of batch indices (tuples of indices).
* @param size: Integer, total size of the data to slice into batches.
* @param batchSize: Integer, batch size.
* @returns An Array of [batchStart, batchEnd] tuples. batchStart is
* inclusive; batchEnd is exclusive. I.e., each batch consists of indices x
* that satisfy batchStart <= x < batchEnd.
*/
function makeBatches(size, batchSize) {
const output = [];
let batchStart = 0;
let batchEnd = null;
while (batchStart < size) {
batchEnd = batchStart + batchSize;
if (batchEnd >= size) {
batchEnd = size;
}
output.push([batchStart, batchEnd]);
batchStart = batchEnd;
}
return output;
}
/**
* Abstract fit function for `f(ins)`.
* @param f A Function returning a list of tensors. For training, this
* function is expected to perform the updates to the variables.
* @param ins List of tensors to be fed to `f`.
* @param outLabels List of strings, display names of the outputs of `f`.
* @param batchSize Integer batch size or `== null` if unknown. Default : 32.
* @param epochs Number of times to iterate over the data. Default : 1.
* @param verbose Verbosity mode: 0, 1, or 2. Default: 1.
* @param callbacks List of callbacks to be called during training.
* @param valF Function to call for validation.
* @param valIns List of tensors to be fed to `valF`.
* @param shuffle Whether to shuffle the data at the beginning of every
* epoch. Default : true.
* @param callbackMetrics List of strings, the display names of the metrics
* passed to the callbacks. They should be the concatenation of the
* display names of the outputs of `f` and the list of display names
* of the outputs of `valF`.
* @param initialEpoch Epoch at which to start training (useful for
* resuming a previous training run). Default : 0.
* @param stepsPerEpoch Total number of steps (batches on samples) before
* declaring one epoch finished and starting the next epoch. Ignored with
* the default value of `undefined` or `null`.
* @param validationSteps Number of steps to run validation for (only if
* doing validation from data tensors). Not applicable for tfjs-layers.
* @returns A `History` object.
*/
async function fitLoop(
// Type `model` as `any` here to avoid circular dependency w/ training.ts.
// tslint:disable-next-line:no-any
model,
f,
ins,
outLabels,
batchSize,
epochs,
verbose,
callbacks,
valF,
valIns,
shuffle,
callbackMetrics,
initialEpoch,
stepsPerEpoch,
validationSteps
) {
if (batchSize == null) {
batchSize = 32;
}
if (epochs == null) {
epochs = 1;
}
if (shuffle == null) {
shuffle = true;
}
if (initialEpoch == null) {
initialEpoch = 0;
}
// TODO(cais): Change const to let below when implementing validation.
let doValidation = false;
if (valF != null && valIns != null) {
doValidation = true;
// TODO(cais): verbose message.
}
if (validationSteps != null) {
doValidation = true;
if (stepsPerEpoch == null) {
throw new ValueError(
"Can only use `validationSteps` when doing step-wise training, " +
"i.e., `stepsPerEpoch` must be set."
);
}
}
const numTrainSamples = model.checkNumSamples(
ins,
batchSize,
stepsPerEpoch,
"steps_per_epoch"
);
let indexArray;
if (numTrainSamples != null) {
indexArray = range(0, numTrainSamples);
}
if (verbose == null) {
verbose = 1;
}
const { callbackList, history } = configureCallbacks(
callbacks,
verbose,
epochs,
initialEpoch,
numTrainSamples,
stepsPerEpoch,
batchSize,
doValidation,
callbackMetrics
);
callbackList.setModel(model);
model.history = history;
await callbackList.onTrainBegin();
model.stopTraining_ = false;
// TODO(cais): Take care of callbacks.validation_data as in PyKeras.
// TODO(cais): Pre-convert feeds for performance as in PyKeras.
for (let epoch = initialEpoch; epoch < epochs; ++epoch) {
await callbackList.onEpochBegin(epoch);
const epochLogs = {};
if (stepsPerEpoch != null) {
throw new NotImplementedError("stepsPerEpoch mode is not implemented yet.");
} else {
if (shuffle === "batch") {
throw new NotImplementedError("batch shuffling is not implemneted yet");
} else if (shuffle) {
dist["util"].shuffle(indexArray);
}
// Convert the potentially shuffled indices to Tensor1D, to avoid the
// cost of repeated creation of Array1Ds later on.
const epochIndexArray1D = Object(dist["tensor1d"])(indexArray);
const batches = makeBatches(numTrainSamples, batchSize);
for (let batchIndex = 0; batchIndex < batches.length; ++batchIndex) {
const batchLogs = {};
await callbackList.onBatchBegin(batchIndex, batchLogs);
dist["tidy"](() => {
const batchStart = batches[batchIndex][0];
const batchEnd = batches[batchIndex][1];
const batchIds = sliceAlongFirstAxis(
epochIndexArray1D,
batchStart,
batchEnd - batchStart
);
batchLogs["batch"] = batchIndex;
batchLogs["size"] = batchEnd - batchStart;
// TODO(cais): In ins, train flag can be a number, instead of an
// Tensor? Do we need to handle this in tfjs-layers?
const insBatch = sliceArraysByIndices(ins, batchIds);
const outs = f(insBatch);
for (let i = 0; i < outLabels.length; ++i) {
const label = outLabels[i];
const out = outs[i];
batchLogs[label] = out;
dist["keep"](out);
// TODO(cais): Use scope() to avoid ownership.
}
if (batchIndex === batches.length - 1) {
// Last batch.
if (doValidation) {
const valOuts = model.testLoop(valF, valIns, batchSize);
// Porting Notes: In tfjs-layers, valOuts is always an Array.
for (let i = 0; i < outLabels.length; ++i) {
const label = outLabels[i];
const out = valOuts[i];
dist["keep"](out);
// TODO(cais): Use scope() to avoid ownership.
epochLogs["val_" + label] = out;
}
}
}
});
await callbackList.onBatchEnd(batchIndex, batchLogs);
disposeTensorsInLogs(batchLogs);
if (model.stopTraining_) {
break;
}
// TODO(cais): return outs as list of Tensor.
}
epochIndexArray1D.dispose();
}
// TODO(cais): Run validation at the end of the epoch.
await callbackList.onEpochEnd(epoch, epochLogs);
if (model.stopTraining_) {
break;
}
}
await callbackList.onTrainEnd();
await model.history.syncData();
return model.history;
}
async function fitTensors(
// Type `model` as `any` here to avoid circular dependency w/ training.ts.
// tslint:disable-next-line:no-any
model,
x,
y,
args = {}
) {
if (model.isTraining) {
throw new Error("Cannot start training because another fit() call is ongoing.");
}
model.isTraining = true;
let inputs;
let targets;
let inputValX;
let inputValY;
let valX;
let valY;
let sampleWeights;
try {
const batchSize = args.batchSize == null ? 32 : args.batchSize;
checkBatchSize(batchSize);
// Validate user data.
// TODO(cais): Support sampleWeight.
const checkBatchAxis = false;
const standardizedOuts = await model.standardizeUserData(
x,
y,
args.sampleWeight,
args.classWeight,
checkBatchAxis,
batchSize
);
inputs = standardizedOuts[0];
targets = standardizedOuts[1];
sampleWeights = standardizedOuts[2];
// Prepare validation data.
let doValidation = false;
let valIns;
if (args.validationData != null && args.validationData.length > 0) {
doValidation = true;
if (args.validationData.length === 2) {
// config.validationData consists of valX and valY.
inputValX = args.validationData[0];
inputValY = args.validationData[1];
} else if (args.validationData.length === 3) {
throw new NotImplementedError(
"validationData including sample weights is not supported yet."
);
} else {
throw new ValueError(
`When passing validation data, it must contain 2 (valX, valY) ` +
`or 3 (valX, valY, valSampleWeight) items; ` +
`${args.validationData} is invalid.`
);
}
const checkBatchAxis = true;
const valStandardized = await model.standardizeUserData(
inputValX,
inputValY,
null,
/** Unused sample weights. */ null,
/** Unused class weights. */ checkBatchAxis,
batchSize
);
valX = valStandardized[0];
valY = valStandardized[1];
valIns = valX.concat(valY);
// TODO(cais): Add useLearningPhase data properly.
} else if (
args.validationSplit != null &&
args.validationSplit > 0 &&
args.validationSplit < 1
) {
doValidation = true;
// Porting Note: In tfjs-layers, inputs[0] is always a Tensor.
const splitAt = Math.floor(inputs[0].shape[0] * (1 - args.validationSplit));
const originalBatchSize = inputs[0].shape[0];
valX = sliceArrays(inputs, splitAt, originalBatchSize);
inputs = sliceArrays(inputs, 0, splitAt);
valY = sliceArrays(targets, splitAt, originalBatchSize);
targets = sliceArrays(targets, 0, splitAt);
// TODO(cais): Once sampleWeights becomes available, slice it to get
// valSampleWeights.
valIns = valX.concat(valY);
// TODO(cais): Add useLearningPhase data properly.
} else if (args.validationSteps != null) {
doValidation = true;
// TODO(cais): Add useLearningPhase.
}
const ins = inputs.concat(targets).concat(sampleWeights);
model.checkTrainableWeightsConsistency();
// TODO(cais): Handle use_learning_phase and learning_phase?
// Porting Note: Here we see a key deviation of tfjs-layers from
// Keras.
// Due to the imperative nature of tfjs-layers' backend (tfjs-core),
// we do not construct symbolic computation graphs to embody the
// training process. Instead, we define a function that performs the
// training action. In PyKeras, the data (inputs and targets) are fed
// through graph placeholders. In tfjs-layers, the data are fed as
// function arguments. Since the function are defined below in the
// scope, we don't have equivalents of PyKeras's
// `_make_train_funciton`.
const trainFunction = model.makeTrainFunction();
const outLabels = model.getDedupedMetricsNames();
let valFunction;
let callbackMetrics;
if (doValidation) {
model.makeTestFunction();
valFunction = model.testFunction;
callbackMetrics = outLabels.slice().concat(outLabels.map((n) => "val_" + n));
} else {
valFunction = null;
valIns = [];
callbackMetrics = outLabels.slice();
}
const callbacks = standardizeCallbacks(args.callbacks, args.yieldEvery);
const out = await fitLoop(
model,
trainFunction,
ins,
outLabels,
batchSize,
args.epochs,
args.verbose,
callbacks,
valFunction,
valIns,
args.shuffle,
callbackMetrics,
args.initialEpoch,
null,
null
);
return out;
} finally {
model.isTraining = false;
// Memory clean up.
disposeNewTensors(inputs, x);
disposeNewTensors(targets, y);
disposeNewTensors(valX, inputValX);
disposeNewTensors(valY, inputValY);
if (sampleWeights != null) {
dist["dispose"](sampleWeights);
}
}
// TODO(cais): Add value to outLabels.
}
/**
* Ensure tensors all have a rank of at least 2.
*
* If a tensor has a rank of 1, it is dimension-expanded to rank 2.
* If any tensor has a rank of 0 (i.e., is a scalar), an error will be thrown.
*/
function ensureTensorsRank2OrHigher(tensors) {
const outs = [];
if (tensors instanceof dist["Tensor"]) {
tensors = [tensors];
}
// Make Tensors at least 2D.
for (let i = 0; i < tensors.length; ++i) {
const tensor = tensors[i];
if (tensor.rank === 1) {
outs.push(expandDims(tensor, 1));
} else if (tensor.rank === 0) {
throw new Error(
"Expected tensor to be at least 1D, but received a 0D tensor " + "(scalar)."
);
} else {
outs.push(tensor);
}
}
return outs;
}
/**
* Compare a set of tensors with a reference (old) set, discard the ones
* in the new set that are not present in the reference set.
*
* This method is used for memory clenaup during calls such as
* LayersModel.fit().
*
* @param tensors New set which may contain Tensors not present in
* `refTensors`.
* @param refTensors Reference Tensor set.
*/
// TODO(cais, kangyizhang): Deduplicate with tfjs-data.
function disposeNewTensors(tensors, refTensors) {
if (tensors == null) {
return;
}
const oldTensorIds = [];
if (refTensors instanceof dist["Tensor"]) {
oldTensorIds.push(refTensors.id);
} else if (Array.isArray(refTensors)) {
refTensors.forEach((t) => oldTensorIds.push(t.id));
} else if (refTensors != null) {
// `oldTensors` is a map from string name to Tensor.
for (const name in refTensors) {
const oldTensor = refTensors[name];
oldTensorIds.push(oldTensor.id);
}
}
const tensorsToDispose = [];
if (tensors instanceof dist["Tensor"]) {
if (oldTensorIds.indexOf(tensors.id) === -1) {
tensorsToDispose.push(tensors);
}
} else if (Array.isArray(tensors)) {
tensors.forEach((t) => {
if (oldTensorIds.indexOf(t.id) === -1) {
tensorsToDispose.push(t);
}
});
} else if (tensors != null) {
// `oldTensors` is a map from string name to Tensor.
for (const name in tensors) {
const tensor = tensors[name];
if (oldTensorIds.indexOf(tensor.id) === -1) {
tensorsToDispose.push(tensor);
}
}
}
tensorsToDispose.forEach((t) => {
if (!t.isDisposed) {
t.dispose();
}
});
}
//# sourceMappingURL=training_tensors.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/engine/training.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original Source: engine/training.py */
/**
* Helper function for polymorphic input data: 1. singleton Tensor.
*/
function isDataTensor(x) {
return x instanceof dist["Tensor"];
}
/**
* Helper function for polymorphic input data: 2. Array of Tensor.
*/
function isDataArray(x) {
return Array.isArray(x);
}
/**
* Helper function for polymorphic input data: 3. "dict" of Tensor.
*/
function isDataDict(x) {
return !isDataTensor(x) && !isDataArray(x);
}
/**
* Normalizes inputs and targets provided by users.
* @param data User-provided input data (polymorphic).
* @param names An Array of expected Tensor names.
* @param shapes Optional Array of expected Tensor shapes.
* @param checkBatchAxis Whether to check that the batch axis of the arrays
* match the expected value found in `shapes`.
* @param exceptionPrefix String prefix used for exception formatting.
* @returns List of standardized input Tensors (one Tensor per model input).
* @throws ValueError: in case of improperly formatted user data.
*/
function standardizeInputData(
data,
names,
shapes,
checkBatchAxis = true,
exceptionPrefix = ""
) {
if (names == null || names.length === 0) {
// Check for the case where the model expected no data, but some data got
// sent.
if (data != null) {
let gotUnexpectedData = false;
if (isDataArray(data) && data.length > 0) {
gotUnexpectedData = true;
} else if (isDataDict(data)) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
gotUnexpectedData = true;
break;
}
}
} else {
// `data` is a singleton Tensor in this case.
gotUnexpectedData = true;
}
if (gotUnexpectedData) {
throw new ValueError(
`Error when checking model ${exceptionPrefix} expected no data, ` +
`but got ${data}`
);
}
}
return [];
}
if (data == null) {
return names.map((name) => null);
}
let arrays;
if (isDataDict(data)) {
data = data;
arrays = [];
for (const name of names) {
if (data[name] == null) {
throw new ValueError(
`No data provided for "${name}". Need data for each key in: ` + `${names}`
);
}
arrays.push(data[name]);
}
} else if (isDataArray(data)) {
data = data;
if (data.length !== names.length) {
throw new ValueError(
`Error when checking model ${exceptionPrefix}: the Array of ` +
`Tensors that you are passing to your model is not the size the ` +
`model expected. Expected to see ${names.length} Tensor(s), but ` +
`instead got the following list of Tensor(s): ${data}`
);
}
arrays = data;
} else {
data = data;
if (names.length > 1) {
throw new ValueError(
`The model ${exceptionPrefix} expects ${names.length} Tensor(s), ` +
`but only received one Tensor. Found: Tensor with shape ${data.shape}`
);
}
arrays = [data];
}
arrays = ensureTensorsRank2OrHigher(arrays);
// Check shape compatibility.
if (shapes != null) {
for (let i = 0; i < names.length; ++i) {
if (shapes[i] == null) {
continue;
}
const array = arrays[i];
if (array.shape.length !== shapes[i].length) {
throw new ValueError(
`Error when checking ${exceptionPrefix}: expected ${names[i]} ` +
`to have ${shapes[i].length} dimension(s). but got array with ` +
`shape ${array.shape}`
);
}
for (let j = 0; j < shapes[i].length; ++j) {
if (j === 0 && !checkBatchAxis) {
// Skip the first (batch) axis.
continue;
}
const dim = array.shape[j];
const refDim = shapes[i][j];
if (refDim != null && refDim >= 0 && dim !== refDim) {
throw new ValueError(
`Error when checking ${exceptionPrefix}: expected ${names[i]} ` +
`to have shape [${shapes[i]}], but got array with shape ` +
`[${array.shape}].`
);
}
}
}
}
return arrays;
}
/**
* User input validation for Tensors.
* @param inputs `Array` of `tf.Tensor`s for inputs.
* @param targets `Array` of `tf.Tensor`s for targets.
* @param weights Optional `Array` of `tf.Tensor`s for sample weights.
* @throws ValueError: in case of incorrectly formatted data.
*/
function checkArrayLengths(inputs, targets, weights) {
const setX = unique(inputs.map((input) => input.shape[0]));
setX.sort();
const setY = unique(targets.map((target) => target.shape[0]));
setY.sort();
// TODO(cais): Check `weights` as well.
if (setX.length > 1) {
throw new ValueError(
`All input Tensors (x) should have the same number of samples. ` +
`Got array shapes: ` +
`${JSON.stringify(inputs.map((input) => input.shape))}`
);
}
if (setY.length > 1) {
throw new ValueError(
`All target Tensors (y) should have the same number of samples. ` +
`Got array shapes: ` +
`${JSON.stringify(targets.map((target) => target.shape))}`
);
}
if (setX.length > 0 && setY.length > 0 && !dist["util"].arraysEqual(setX, setY)) {
throw new ValueError(
`Input Tensors should have the same number of samples as target ` +
`Tensors. Found ${setX[0]} input sample(s) and ${setY[0]} target ` +
`sample(s).`
);
}
}
/**
* Validation on the compatibility of targes and loss functions.
*
* This helps prevent users from using loss functions incorrectly.
*
* @param targets `Array` of `tf.Tensor`s of targets.
* @param lossFns `Array` of loss functions.
* @param outputShapes `Array` of shapes of model outputs.
*/
function checkLossAndTargetCompatibility(targets, lossFns, outputShapes) {
// TODO(cais): Dedicated test coverage?
const keyLosses = [meanSquaredError, binaryCrossentropy, categoricalCrossentropy];
for (let i = 0; i < targets.length; ++i) {
const y = targets[i];
const loss = lossFns[i];
const shape = outputShapes[i];
if (loss == null) {
continue;
}
if (loss === categoricalCrossentropy) {
if (y.shape[y.shape.length - 1] === 1) {
throw new ValueError(
`You are passing a target array of shape ${y.shape} while using ` +
`a loss 'categorical_crossentropy'. 'categorical_crossentropy'` +
`expects targets to be binary matrices (1s and 0s) of shape ` +
`[samples, classes].`
);
// TODO(cais): Example code in error message.
}
}
if (keyLosses.indexOf(loss) !== -1) {
const slicedYShape = y.shape.slice(1);
const slicedShape = shape.slice(1);
for (let j = 0; j < slicedYShape.length; ++j) {
const targetDim = slicedYShape[j];
const outDim = slicedShape[j];
if (outDim != null && targetDim !== outDim) {
throw new ValueError(
`A target Tensor with shape ${y.shape} was passed for an ` +
`output of shape ${shape}, while using a loss function that ` +
`expects targets to have the same shape as the output.`
);
}
}
}
}
}
/**
* Check inputs provided by the user.
*
* Porting Note: This corresponds to _standardize_input_data() in Python
* Keras. Because of the strong typing in TF.js, we do not need to convert
* the data. Specifically:
* 1) in PyKeras, `data` can be `DataFrame` instances from pandas, for
* example. We don't need to worry about that here because there is no
* widely popular javascript/typesdcript equivalent of pandas (so far).
* If one becomes available in the future, we can add support.
* 2) in PyKeras, inputs can be Python dict. But here we are stipulating
* that the data is either a single `tf.Tensor` or an Array of `tf.Tensor`s. We
* may add support for `Object` data inputs in the future when the need
* arises.
*
* Instead, we perform basic checks for number of parameters and shapes.
*
* @param data: The input data.
* @param names: Name for the inputs, from the model.
* @param shapes: Expected shapes for the input data, from the model.
* @param checkBatchAxis: Whether the size along the batch axis (i.e., the
* first dimension) will be checked for matching.
* @param exceptionPrefix: Execption prefix message, used in generating error
* messages.
* @throws ValueError: on incorrect number of inputs or mismatches in shapes.
*/
function checkInputData(data, names, shapes, checkBatchAxis = true, exceptionPrefix = "") {
let arrays;
if (Array.isArray(data)) {
if (data.length !== names.length) {
throw new ValueError(
`Error when checking model ${exceptionPrefix}: the Array of ` +
`Tensors that you are passing to your model is not the size the ` +
`the model expected. Expected to see ${names.length} Tensor(s),` +
` but instead got ${data.length} Tensors(s).`
);
}
arrays = data;
} else {
if (names.length > 1) {
throw new ValueError(
`The model expects ${names.length} ${exceptionPrefix} Tensors, ` +
`but only received one Tensor. Found: array with shape ` +
`${JSON.stringify(data.shape)}.`
);
}
arrays = [data];
}
if (shapes != null) {
for (let i = 0; i < names.length; ++i) {
if (shapes[i] == null) {
continue;
}
const array = arrays[i];
if (array.shape.length !== shapes[i].length) {
throw new ValueError(
`Error when checking ${exceptionPrefix}: expected ${names[i]} ` +
`to have ${shapes[i].length} dimension(s), but got array with ` +
`shape ${JSON.stringify(array.shape)}`
);
}
for (let j = 0; j < shapes[i].length; ++j) {
if (j === 0 && !checkBatchAxis) {
continue;
}
const dim = array.shape[j];
const refDim = shapes[i][j];
if (refDim != null) {
if (refDim !== dim) {
throw new ValueError(
`Error when checking ${exceptionPrefix}: expected ` +
`${names[i]} to have shape ${JSON.stringify(shapes[i])} but ` +
`got array with shape ${JSON.stringify(array.shape)}.`
);
}
}
}
}
}
}
/**
* Maps metric functions to model outputs.
* @param metrics An shortcut strings name, metric function, `Array` or dict
* (`Object`) of metric functions.
* @param outputNames An `Array` of the names of model outputs.
* @returns An `Array` (one entry per model output) of `Array` of metric
* functions. For instance, if the model has 2 outputs, and for the first
* output we want to compute `binaryAccuracy` and `binaryCrossentropy`,
* and just `binaryAccuracy` for the second output, the `Array` would look
* like:
* `[[binaryAccuracy, binaryCrossentropy], [binaryAccuracy]]`
* @throws TypeError: incompatible metrics format.
*/
function collectMetrics(metrics, outputNames) {
if (metrics == null || (Array.isArray(metrics) && metrics.length === 0)) {
return outputNames.map((name) => []);
}
let wrappedMetrics;
if (typeof metrics === "string" || typeof metrics === "function") {
wrappedMetrics = [metrics];
} else if (Array.isArray(metrics) || typeof metrics === "object") {
wrappedMetrics = metrics;
} else {
throw new TypeError(
"Type of metrics argument not understood. Expected an string," +
`function, Array, or Object, found: ${metrics}`
);
}
if (Array.isArray(wrappedMetrics)) {
// We then apply all metrics to all outputs.
return outputNames.map((name) => wrappedMetrics);
} else {
// In this case, metrics is a dict.
const nestedMetrics = [];
for (const name of outputNames) {
let outputMetrics = wrappedMetrics.hasOwnProperty(name) ? wrappedMetrics[name] : [];
if (!Array.isArray(outputMetrics)) {
outputMetrics = [outputMetrics];
}
nestedMetrics.push(outputMetrics);
}
return nestedMetrics;
}
}
const LAYERS_MODEL_FORMAT_NAME = "layers-model";
/**
* A `tf.LayersModel` is a directed, acyclic graph of `tf.Layer`s plus methods
* for training, evaluation, prediction and saving.
*
* `tf.LayersModel` is the basic unit of training, inference and evaluation in
* TensorFlow.js. To create a `tf.LayersModel`, use `tf.LayersModel`.
*
* See also:
* `tf.Sequential`, `tf.loadLayersModel`.
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
class training_LayersModel extends container_Container {
constructor(args) {
super(args);
this.isTraining = false;
}
/**
* Print a text summary of the model's layers.
*
* The summary includes
* - Name and type of all layers that comprise the model.
* - Output shape(s) of the layers
* - Number of weight parameters of each layer
* - If the model has non-sequential-like topology, the inputs each layer
* receives
* - The total number of trainable and non-trainable parameters of the model.
*
* ```js
* const input1 = tf.input({shape: [10]});
* const input2 = tf.input({shape: [20]});
* const dense1 = tf.layers.dense({units: 4}).apply(input1);
* const dense2 = tf.layers.dense({units: 8}).apply(input2);
* const concat = tf.layers.concatenate().apply([dense1, dense2]);
* const output =
* tf.layers.dense({units: 3, activation: 'softmax'}).apply(concat);
*
* const model = tf.model({inputs: [input1, input2], outputs: output});
* model.summary();
* ```
*
* @param lineLength Custom line length, in number of characters.
* @param positions Custom widths of each of the columns, as either
* fractions of `lineLength` (e.g., `[0.5, 0.75, 1]`) or absolute number
* of characters (e.g., `[30, 50, 65]`). Each number corresponds to
* right-most (i.e., ending) position of a column.
* @param printFn Custom print function. Can be used to replace the default
* `console.log`. For example, you can use `x => {}` to mute the printed
* messages in the console.
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
summary(lineLength, positions, printFn = console.log) {
if (!this.built) {
throw new ValueError(
`This model has never been called, thus its weights have not been ` +
`created yet. So no summary can be displayed. Build the model ` +
`first (e.g., by calling it on some test data).`
);
}
printSummary(this, lineLength, positions, printFn);
}
/**
* Configures and prepares the model for training and evaluation. Compiling
* outfits the model with an optimizer, loss, and/or metrics. Calling `fit`
* or `evaluate` on an un-compiled model will throw an error.
*
* @param args a `ModelCompileArgs` specifying the loss, optimizer, and
* metrics to be used for fitting and evaluating this model.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
compile(args) {
if (args.loss == null) {
args.loss = [];
}
this.loss = args.loss;
if (typeof args.optimizer === "string") {
this.optimizer_ = getOptimizer(args.optimizer);
this.isOptimizerOwned = true;
} else {
if (!(args.optimizer instanceof dist["Optimizer"])) {
throw new ValueError(`User-defined optimizer must be an instance of tf.Optimizer.`);
}
this.optimizer_ = args.optimizer;
this.isOptimizerOwned = false;
}
// TODO(cais): Add lossWeights.
// TODO(cais): Add sampleWeightMode.
// Prepare loss functions.
let lossFunctions = [];
if (
!Array.isArray(args.loss) &&
typeof args.loss !== "string" &&
typeof args.loss !== "function"
) {
args.loss = args.loss;
for (const name in args.loss) {
if (this.outputNames.indexOf(name) === -1) {
throw new ValueError(
`Unknown entry in loss dictionary: "${name}". ` +
`Only expected the following keys: ${this.outputNames}`
);
}
}
for (const name of this.outputNames) {
if (args.loss[name] == null) {
console.warn(
`Output "${name}" is missing from loss dictionary. We assume ` +
`this was done on purpose, and we will not be expecting data ` +
`to be passed to ${name} during training`
);
}
lossFunctions.push(get(args.loss[name]));
}
} else if (Array.isArray(args.loss)) {
if (args.loss.length !== this.outputs.length) {
throw new ValueError(
`When passing an Array as loss, it should have one entry per ` +
`model output. The model has ${this.outputs.length} output(s), ` +
`but you passed loss=${args.loss}.`
);
}
const theLosses = args.loss;
lossFunctions = theLosses.map((l) => get(l));
} else {
const lossFunction = get(args.loss);
this.outputs.forEach((_) => {
lossFunctions.push(lossFunction);
});
}
this.lossFunctions = lossFunctions;
this.feedOutputNames = [];
this.feedOutputShapes = [];
this.feedLossFns = [];
for (let i = 0; i < this.outputs.length; ++i) {
// TODO(cais): Logic for skipping target(s).
const shape = this.internalOutputShapes[i];
const name = this.outputNames[i];
this.feedOutputNames.push(name);
this.feedOutputShapes.push(shape);
this.feedLossFns.push(this.lossFunctions[i]);
}
// TODO(cais): Add logic for output masks.
// TODO(cais): Add logic for sample weights.
const skipTargetIndices = [];
// Prepare metrics.
this.metrics = args.metrics;
// TODO(cais): Add weightedMetrics.
this.metricsNames = ["loss"];
this.metricsTensors = [];
// Compute total loss.
// Porting Note: In PyKeras, metrics_tensors are symbolic tensor objects.
// Here, metricsTensors are TypeScript functions. This difference is due
// to the difference in symbolic/imperative property of the backends.
nameScope("loss", () => {
for (let i = 0; i < this.outputs.length; ++i) {
if (skipTargetIndices.indexOf(i) !== -1) {
continue;
}
// TODO(cais): Add weightedLoss, sampleWeight and mask.
// The following line should be weightedLoss
const weightedLoss = this.lossFunctions[i];
if (this.outputs.length > 1) {
this.metricsTensors.push([weightedLoss, i]);
this.metricsNames.push(this.outputNames[i] + "_loss");
}
}
// Porting Note: Due to the imperative nature of the backend, we calculate
// the regularizer penalties in the totalLossFunction, instead of here.
});
const nestedMetrics = collectMetrics(args.metrics, this.outputNames);
// TODO(cais): Add nestedWeightedMetrics.
/**
* Helper function used in loop below.
*/
const appendMetric = (outputIndex, metricName, metricTensor) => {
if (this.outputNames.length > 1) {
metricName = this.outputNames[outputIndex] + "_" + metricName;
}
this.metricsNames.push(metricName);
this.metricsTensors.push([metricTensor, outputIndex]);
};
nameScope("metric", () => {
for (let i = 0; i < this.outputs.length; ++i) {
if (skipTargetIndices.indexOf(i) !== -1) {
continue;
}
const outputMetrics = nestedMetrics[i];
// TODO(cais): Add weights and outputWeightedMetrics.
// TODO(cais): Add optional arg `weights` to the following function.
const handleMetrics = (metrics) => {
const metricNamePrefix = "";
let metricName;
let accFn;
let weightedMetricFn;
// TODO(cais): Use 'weights_' for weighted metrics.
for (const metric of metrics) {
if (
typeof metric === "string" &&
["accuracy", "acc", "crossentropy", "ce"].indexOf(metric) !== -1
) {
const outputShape = this.internalOutputShapes[i];
if (
outputShape[outputShape.length - 1] === 1 ||
this.lossFunctions[i] === binaryCrossentropy
) {
// case: binary accuracy/crossentropy.
if (["accuracy", "acc"].indexOf(metric) !== -1) {
accFn = binaryAccuracy;
} else if (["crossentropy", "ce"].indexOf(metric) !== -1) {
accFn = metrics_binaryCrossentropy;
}
} else if (this.lossFunctions[i] === sparseCategoricalCrossentropy) {
// case: categorical accuracy / crossentropy with sparse
// targets.
if (["accuracy", "acc"].indexOf(metric) !== -1) {
accFn = sparseCategoricalAccuracy;
} else if (["crossentropy", "ce"].indexOf(metric) !== -1) {
accFn = metrics_sparseCategoricalCrossentropy;
}
} else {
// case: categorical accuracy / crossentropy.
if (["accuracy", "acc"].indexOf(metric) !== -1) {
accFn = categoricalAccuracy;
} else if (["crossentropy", "ce"].indexOf(metric) !== -1) {
accFn = metrics_categoricalCrossentropy;
}
}
let suffix;
if (["accuracy", "acc"].indexOf(metric) !== -1) {
suffix = "acc";
} else if (["crossentropy", "ce"].indexOf(metric) !== -1) {
suffix = "ce";
}
// TODO(cais): Add weighting actually.
weightedMetricFn = accFn;
metricName = metricNamePrefix + suffix;
} else {
const metricFn = metrics_get(metric);
// TODO(cais): Add weighting actually.
weightedMetricFn = metricFn;
metricName = metricNamePrefix + getLossOrMetricName(metric);
}
// TODO(cais): Add weighting and masking to metricResult.
let metricResult;
nameScope(metricName, () => {
metricResult = weightedMetricFn;
});
appendMetric(i, metricName, metricResult);
}
};
handleMetrics(outputMetrics);
// TODO(cais): Call handleMetrics with weights.
}
});
// Porting Notes: Given the imperative backend of tfjs-core,
// there is no need for constructing the symbolic graph and placeholders.
this.collectedTrainableWeights = this.trainableWeights;
}
/**
* Check trainable weights count consistency.
*
* This will raise a warning if `this.trainableWeights` and
* `this.collectedTrainableWeights` are inconsistent (i.e., have different
* numbers of parameters).
* Inconsistency will typically arise when one modifies `model.trainable`
* without calling `model.compile()` again.
*/
checkTrainableWeightsConsistency() {
if (this.collectedTrainableWeights == null) {
return;
}
if (this.trainableWeights.length !== this.collectedTrainableWeights.length) {
console.warn(
"Discrepancy between trainableweights and collected trainable " +
"weights. Did you set `model.trainable` without calling " +
"`model.compile()` afterwards?"
);
}
}
/**
* Returns the loss value & metrics values for the model in test mode.
*
* Loss and metrics are specified during `compile()`, which needs to happen
* before calls to `evaluate()`.
*
* Computation is done in batches.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* const result = model.evaluate(
* tf.ones([8, 10]), tf.ones([8, 1]), {batchSize: 4});
* result.print();
* ```
*
* @param x `tf.Tensor` of test data, or an `Array` of `tf.Tensor`s if the
* model has multiple inputs.
* @param y `tf.Tensor` of target data, or an `Array` of `tf.Tensor`s if the
* model has multiple outputs.
* @param args A `ModelEvaluateArgs`, containing optional fields.
*
* @return `Scalar` test loss (if the model has a single output and no
* metrics) or `Array` of `Scalar`s (if the model has multiple outputs
* and/or metrics). The attribute `model.metricsNames`
* will give you the display labels for the scalar outputs.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
evaluate(x, y, args = {}) {
const batchSize = args.batchSize == null ? 32 : args.batchSize;
checkBatchSize(batchSize);
// TODO(cais): Standardize `config.sampleWeights` as well.
// Validate user data.
const checkBatchAxis = true;
const standardizedOuts = this.standardizeUserDataXY(x, y, checkBatchAxis, batchSize);
try {
// TODO(cais): If uses `useLearningPhase`, set the corresponding element
// of the input to 0.
const ins = standardizedOuts[0].concat(standardizedOuts[1]);
this.makeTestFunction();
const f = this.testFunction;
const testOuts = this.testLoop(f, ins, batchSize, args.verbose, args.steps);
return singletonOrArray(testOuts);
} finally {
disposeNewTensors(standardizedOuts[0], x);
disposeNewTensors(standardizedOuts[1], y);
}
}
// TODO(cais): Add code snippet below once real dataset objects are
// available.
/**
* Evaluate model using a dataset object.
*
* Note: Unlike `evaluate()`, this method is asynchronous (`async`);
*
* @param dataset A dataset object. Its `iterator()` method is expected
* to generate a dataset iterator object, the `next()` method of which
* is expected to produce data batches for evaluation. The return value
* of the `next()` call ought to contain a boolean `done` field and a
* `value` field. The `value` field is expected to be an array of two
* `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former
* case is for models with exactly one input and one output (e.g..
* a sequential model). The latter case is for models with multiple
* inputs and/or multiple outputs. Of the two items in the array, the
* first is the input feature(s) and the second is the output target(s).
* @param args A configuration object for the dataset-based evaluation.
* @returns Loss and metric values as an Array of `Scalar` objects.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async evaluateDataset(dataset, args) {
this.makeTestFunction();
return evaluateDataset(this, dataset, args);
}
/**
* Get number of samples provided for training, evaluation or prediction.
*
* @param ins Input `tf.Tensor`.
* @param batchSize Integer batch size, optional.
* @param steps Total number of steps (batches of samples) before
* declaring loop finished. Optional.
* @param stepsName The public API's parameter name for `steps`.
* @returns Number of samples provided.
*/
checkNumSamples(ins, batchSize, steps, stepsName = "steps") {
let numSamples;
if (steps != null) {
numSamples = null;
if (batchSize != null) {
throw new ValueError(
`If ${stepsName} is set, batchSize must be null or undefined.` +
`Got batchSize = ${batchSize}`
);
}
} else if (ins != null) {
if (Array.isArray(ins)) {
numSamples = ins[0].shape[0];
} else {
numSamples = ins.shape[0];
}
} else {
throw new ValueError(
`Either the input data should have a defined shape, or ` +
`${stepsName} shoud be specified.`
);
}
return numSamples;
}
/**
* Execute internal tensors of the model with input data feed.
* @param inputs Input data feed. Must match the inputs of the model.
* @param outputs Names of the output tensors to be fetched. Must match
* names of the SymbolicTensors that belong to the graph.
* @returns Fetched values for `outputs`.
*/
execute(inputs, outputs) {
if (Array.isArray(outputs) && outputs.length === 0) {
throw new ValueError("`outputs` is an empty Array, which is not allowed.");
}
const outputsIsArray = Array.isArray(outputs);
const outputNames = outputsIsArray ? outputs : [outputs];
const outputSymbolicTensors = this.retrieveSymbolicTensors(outputNames);
// Format the input into a FeedDict.
const feedDict = new executor_FeedDict();
if (inputs instanceof dist["Tensor"]) {
inputs = [inputs];
}
if (Array.isArray(inputs)) {
if (inputs.length !== this.inputs.length) {
throw new ValueError(
`The number of inputs provided (${inputs.length}) ` +
`does not match the number of inputs of this model ` +
`(${this.inputs.length}).`
);
}
for (let i = 0; i < this.inputs.length; ++i) {
feedDict.add(this.inputs[i], inputs[i]);
}
} else {
for (const input of this.inputs) {
const tensorValue = inputs[input.name];
if (tensorValue == null) {
throw new ValueError(`No value is provided for the model's input ${input.name}`);
}
feedDict.add(input, tensorValue);
}
}
// Run execution.
const executeOutputs = execute(outputSymbolicTensors, feedDict);
return outputsIsArray ? executeOutputs : executeOutputs[0];
}
/**
* Retrieve the model's internal symbolic tensors from symbolic-tensor names.
*/
retrieveSymbolicTensors(symbolicTensorNames) {
const outputSymbolicTensors = pyListRepeat(null, symbolicTensorNames.length);
let outputsRemaining = symbolicTensorNames.length;
for (const layer of this.layers) {
const layerOutputs = Array.isArray(layer.output) ? layer.output : [layer.output];
const layerOutputNames = layerOutputs.map((output) => output.name);
for (let i = 0; i < symbolicTensorNames.length; ++i) {
const index = layerOutputNames.indexOf(symbolicTensorNames[i]);
if (index !== -1) {
outputSymbolicTensors[i] = layerOutputs[index];
outputsRemaining--;
}
if (outputsRemaining === 0) {
break;
}
}
if (outputsRemaining === 0) {
break;
}
}
if (outputsRemaining > 0) {
const remainingNames = [];
outputSymbolicTensors.forEach((tensor, i) => {
if (tensor == null) {
remainingNames.push(symbolicTensorNames[i]);
}
});
throw new ValueError(
`Cannot find SymbolicTensors for output name(s): ` +
`${JSON.stringify(remainingNames)}`
);
}
return outputSymbolicTensors;
}
/**
* Helper method to loop over some data in batches.
*
* Porting Note: Not using the functional approach in the Python equivalent
* due to the imperative backend.
* Porting Note: Does not support step mode currently.
*
* @param ins: input data
* @param batchSize: integer batch size.
* @param verbose: verbosity model
* @returns: Predictions as `tf.Tensor` (if a single output) or an `Array` of
* `tf.Tensor` (if multipe outputs).
*/
predictLoop(ins, batchSize = 32, verbose = false) {
return dist["tidy"](() => {
const numSamples = this.checkNumSamples(ins);
if (verbose) {
throw new NotImplementedError("Verbose predictLoop() is not implemented yet.");
}
// Sample-based predictions.
// Porting Note: Tensor currently does not support sliced assignments as
// in numpy, e.g., x[1:3] = y. Therefore we use concatenation while
// iterating over the batches.
const batches = makeBatches(numSamples, batchSize);
const outsBatches = this.outputs.map((output) => []);
// TODO(cais): Can the scope() be pushed down inside the for loop?
for (let batchIndex = 0; batchIndex < batches.length; ++batchIndex) {
const batchOuts = dist["tidy"](() => {
const batchStart = batches[batchIndex][0];
const batchEnd = batches[batchIndex][1];
// TODO(cais): Take care of the case of the last element is a flag for
// training/test.
const insBatch = sliceArrays(ins, batchStart, batchEnd);
// Construct the feeds for execute();
const feeds = [];
if (Array.isArray(insBatch)) {
for (let i = 0; i < insBatch.length; ++i) {
feeds.push({ key: this.inputs[i], value: insBatch[i] });
}
} else {
feeds.push({ key: this.inputs[0], value: insBatch });
}
const feedDict = new executor_FeedDict(feeds);
return execute(this.outputs, feedDict);
});
batchOuts.forEach((batchOut, i) => outsBatches[i].push(batchOut));
}
return singletonOrArray(outsBatches.map((batches) => dist["concat"](batches, 0)));
});
}
/**
* Generates output predictions for the input samples.
*
* Computation is done in batches.
*
* Note: the "step" mode of predict() is currently not supported.
* This is because the TensorFlow.js core backend is imperative only.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.predict(tf.ones([8, 10]), {batchSize: 4}).print();
* ```
*
* @param x The input data, as a Tensor, or an `Array` of `tf.Tensor`s if
* the model has multiple inputs.
* @param args A `ModelPredictArgs` object containing optional fields.
*
* @return Prediction results as a `tf.Tensor`(s).
*
* @exception ValueError In case of mismatch between the provided input data
* and the model's expectations, or in case a stateful model receives a
* number of samples that is not a multiple of the batch size.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
predict(x, args = {}) {
const xsRank2OrHigher = ensureTensorsRank2OrHigher(x);
checkInputData(xsRank2OrHigher, this.inputNames, this.feedInputShapes, false);
try {
// TODO(cais): Take care of stateful models.
// if (this.stateful) ...
// TODO(cais): Take care of the learning_phase boolean flag.
// if (this.useLearningPhase) ...
const batchSize = args.batchSize == null ? 32 : args.batchSize;
checkBatchSize(batchSize);
return this.predictLoop(xsRank2OrHigher, batchSize);
} finally {
disposeNewTensors(xsRank2OrHigher, x);
}
}
/**
* Returns predictions for a single batch of samples.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.predictOnBatch(tf.ones([8, 10])).print();
* ```
* @param x: Input samples, as a Tensor (for models with exactly one
* input) or an array of Tensors (for models with more than one input).
* @return Tensor(s) of predictions
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
predictOnBatch(x) {
checkInputData(x, this.inputNames, this.feedInputShapes, true);
// TODO(cais): Take care of the learning_phase boolean flag.
// if (this.useLearningPhase) ...
const batchSize = (Array.isArray(x) ? x[0] : x).shape[0];
return this.predictLoop(x, batchSize);
}
standardizeUserDataXY(x, y, checkBatchAxis = true, batchSize) {
// TODO(cais): Add sampleWeight, classWeight
if (this.optimizer_ == null) {
throw new RuntimeError(
"You must compile a model before training/testing. Use " +
"LayersModel.compile(modelCompileArgs)."
);
}
const outputShapes = [];
for (let i = 0; i < this.feedOutputShapes.length; ++i) {
const outputShape = this.feedOutputShapes[i];
const lossFn = this.feedLossFns[i];
if (lossFn === sparseCategoricalCrossentropy) {
outputShapes.push(outputShape.slice(0, outputShape.length - 1).concat([1]));
} else {
// Porting Note: Because of strong typing `lossFn` must be a function.
outputShapes.push(outputShape);
}
}
x = standardizeInputData(x, this.feedInputNames, this.feedInputShapes, false, "input");
y = standardizeInputData(y, this.feedOutputNames, outputShapes, false, "target");
// TODO(cais): Standardize sampleWeights & classWeights.
checkArrayLengths(x, y, null);
// TODO(cais): Check sampleWeights as well.
checkLossAndTargetCompatibility(y, this.feedLossFns, this.feedOutputShapes);
if (this.stateful && batchSize != null && batchSize > 0) {
if (x[0].shape[0] % batchSize !== 0) {
throw new ValueError(
`In a stateful network, you should only pass inputs with a ` +
`number of samples that is divisible by the batch size ` +
`${batchSize}. Found: ${x[0].shape[0]} sample(s).`
);
}
}
return [x, y];
}
async standardizeUserData(
x,
y,
sampleWeight,
classWeight,
checkBatchAxis = true,
batchSize
) {
const [standardXs, standardYs] = this.standardizeUserDataXY(
x,
y,
checkBatchAxis,
batchSize
);
// TODO(cais): Handle sampleWeights.
if (sampleWeight != null) {
throw new Error("sample weight is not supported yet.");
}
let standardSampleWeights = null;
if (classWeight != null) {
const classWeights = standardizeClassWeights(classWeight, this.outputNames);
standardSampleWeights = [];
for (let i = 0; i < classWeights.length; ++i) {
standardSampleWeights.push(
await standardizeWeights(standardYs[i], null, classWeights[i])
);
}
}
// TODO(cais): Deal with the case of model.stateful == true.
return [standardXs, standardYs, standardSampleWeights];
}
/**
* Loop over some test data in batches.
* @param f A Function returning a list of tensors.
* @param ins Array of tensors to be fed to `f`.
* @param batchSize Integer batch size or `null` / `undefined`.
* @param verbose verbosity mode.
* @param steps Total number of steps (batches of samples) before
* declaring test finished. Ignored with the default value of `null` /
* `undefined`.
* @returns Array of Scalars.
*/
testLoop(f, ins, batchSize, verbose = 0, steps) {
return dist["tidy"](() => {
const numSamples = this.checkNumSamples(ins, batchSize, steps, "steps");
const outs = [];
if (verbose > 0) {
throw new NotImplementedError("Verbose mode is not implemented yet.");
}
// TODO(cais): Use `indicesForConversionToDense' to prevent slow down.
if (steps != null) {
throw new NotImplementedError("steps mode in testLoop() is not implemented yet");
} else {
const batches = makeBatches(numSamples, batchSize);
const indexArray = Object(dist["tensor1d"])(range(0, numSamples));
for (let batchIndex = 0; batchIndex < batches.length; ++batchIndex) {
const batchStart = batches[batchIndex][0];
const batchEnd = batches[batchIndex][1];
const batchIds = sliceAlongFirstAxis(indexArray, batchStart, batchEnd - batchStart);
// TODO(cais): In ins, train flag can be a number, instead of an
// Tensor? Do we need to handle this in tfjs-layers?
const insBatch = sliceArraysByIndices(ins, batchIds);
const batchOuts = f(insBatch);
if (batchIndex === 0) {
for (let i = 0; i < batchOuts.length; ++i) {
outs.push(Object(dist["scalar"])(0));
}
}
for (let i = 0; i < batchOuts.length; ++i) {
const batchOut = batchOuts[i];
outs[i] = dist["add"](outs[i], dist["mul"](batchEnd - batchStart, batchOut));
}
}
for (let i = 0; i < outs.length; ++i) {
outs[i] = dist["div"](outs[i], numSamples);
}
}
return outs;
});
}
getDedupedMetricsNames() {
const outLabels = this.metricsNames;
// Rename duplicated metrics names (can happen with an output layer
// shared among multiple dataflows).
const dedupedOutLabels = [];
for (let i = 0; i < outLabels.length; ++i) {
const label = outLabels[i];
let newLabel = label;
if (generic_utils_count(outLabels, label) > 1) {
const dupIndex = generic_utils_count(outLabels.slice(0, i), label);
newLabel += `_${dupIndex}`;
}
dedupedOutLabels.push(newLabel);
}
return dedupedOutLabels;
}
/**
* Creates a function that performs the following actions:
*
* 1. computes the losses
* 2. sums them to get the total loss
* 3. call the optimizer computes the gradients of the LayersModel's
* trainable weights w.r.t. the total loss and update the variables
* 4. calculates the metrics
* 5. returns the values of the losses and metrics.
*/
makeTrainFunction() {
return (data) => {
const lossValues = [];
const inputs = data.slice(0, this.inputs.length);
const targets = data.slice(
this.inputs.length,
this.inputs.length + this.outputs.length
);
const sampleWeights = data.slice(
this.inputs.length + this.outputs.length,
this.inputs.length + this.outputs.length * 2
);
const metricsValues = [];
// Create a function that computes the total loss based on the
// inputs. This function is used for obtaining gradients through
// backprop.
const totalLossFunction = () => {
const feeds = [];
for (let i = 0; i < this.inputs.length; ++i) {
feeds.push({ key: this.inputs[i], value: inputs[i] });
}
const feedDict = new executor_FeedDict(feeds);
const outputs = execute(this.outputs, feedDict, { training: true });
// TODO(cais): Take care of the case of multiple outputs from a
// single layer?
let totalLoss;
for (let i = 0; i < this.lossFunctions.length; ++i) {
const lossFunction = this.lossFunctions[i];
let loss = lossFunction(targets[i], outputs[i]);
if (sampleWeights[i] != null) {
loss = computeWeightedLoss(loss, sampleWeights[i]);
}
// TODO(cais): push Scalar instead.
const meanLoss = dist["mean"](loss);
// TODO(cais): Use a scope() instead, to avoid ownership.
lossValues.push(meanLoss);
if (i === 0) {
totalLoss = loss;
} else {
totalLoss = dist["add"](totalLoss, loss);
}
}
// Compute the metrics.
// TODO(cais): These should probably be calculated outside
// totalLossFunction to benefit speed?
for (let i = 0; i < this.metricsTensors.length; ++i) {
let weightedMetric;
if (this.outputs.length > 1 && i < this.outputs.length) {
weightedMetric = lossValues[i];
} else {
const metric = this.metricsTensors[i][0];
const outputIndex = this.metricsTensors[i][1];
weightedMetric = dist["mean"](metric(targets[outputIndex], outputs[outputIndex]));
}
dist["keep"](weightedMetric);
// TODO(cais): Use a scope() instead, to avoid ownership.
metricsValues.push(weightedMetric);
}
totalLoss = dist["mean"](totalLoss);
// Add regularizer penalties.
this.calculateLosses().forEach((regularizerLoss) => {
totalLoss = dist["add"](totalLoss, regularizerLoss);
});
return totalLoss;
};
const variables = this.collectedTrainableWeights.map((param) => param.read());
const returnCost = true;
const totalLossValue = this.optimizer_.minimize(
totalLossFunction,
returnCost,
variables
);
return [totalLossValue].concat(metricsValues);
};
}
/**
* Create a function which, when invoked with an array of `tf.Tensor`s as a
* batch of inputs, returns the prespecified loss and metrics of the model
* under the batch of input data.
*/
makeTestFunction() {
this.testFunction = (data) => {
return dist["tidy"](() => {
const valOutputs = [];
let totalLoss;
const inputs = data.slice(0, this.inputs.length);
const targets = data.slice(
this.inputs.length,
this.inputs.length + this.outputs.length
);
const feeds = [];
for (let i = 0; i < this.inputs.length; ++i) {
feeds.push({ key: this.inputs[i], value: inputs[i] });
}
const feedDict = new executor_FeedDict(feeds);
const outputs = execute(this.outputs, feedDict);
// Compute total loss.
for (let i = 0; i < this.lossFunctions.length; ++i) {
const lossFunction = this.lossFunctions[i];
// TODO(cais): Add sample weighting and replace the simple
// averaging.
const loss = dist["mean"](lossFunction(targets[i], outputs[i]));
if (i === 0) {
totalLoss = loss;
} else {
totalLoss = dist["add"](totalLoss, loss);
}
valOutputs.push(totalLoss);
}
// Compute the metrics.
for (let i = 0; i < this.metricsTensors.length; ++i) {
const metric = this.metricsTensors[i][0];
const outputIndex = this.metricsTensors[i][1];
// TODO(cais): Replace K.mean() with a proper weighting function.
const meanMetric = dist["mean"](metric(targets[outputIndex], outputs[outputIndex]));
valOutputs.push(meanMetric);
}
return valOutputs;
});
};
}
/**
* Trains the model for a fixed number of epochs (iterations on a
* dataset).
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* for (let i = 1; i < 5 ; ++i) {
* const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
* batchSize: 4,
* epochs: 3
* });
* console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
* }
* ```
*
* @param x `tf.Tensor` of training data, or an array of `tf.Tensor`s if the
* model has multiple inputs. If all inputs in the model are named, you
* can also pass a dictionary mapping input names to `tf.Tensor`s.
* @param y `tf.Tensor` of target (label) data, or an array of `tf.Tensor`s if
* the model has multiple outputs. If all outputs in the model are named,
* you can also pass a dictionary mapping output names to `tf.Tensor`s.
* @param args A `ModelFitArgs`, containing optional fields.
*
* @return A `History` instance. Its `history` attribute contains all
* information collected during training.
*
* @exception ValueError In case of mismatch between the provided input
* data and what the model expects.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async fit(x, y, args = {}) {
return fitTensors(this, x, y, args);
}
// TODO(cais): Add code snippet below when it's possible to instantiate
// actual dataset objects.
/**
* Trains the model using a dataset object.
*
* @param dataset A dataset object. Its `iterator()` method is expected
* to generate a dataset iterator object, the `next()` method of which
* is expected to produce data batches for training. The return value
* of the `next()` call ought to contain a boolean `done` field and a
* `value` field. The `value` field is expected to be an array of two
* `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former
* case is for models with exactly one input and one output (e.g..
* a sequential model). The latter case is for models with multiple
* inputs and/or multiple outputs.
* Of the two items in the array, the first is the input feature(s) and
* the second is the output target(s).
* @param args A `ModelFitDatasetArgs`, containing optional fields.
*
* @return A `History` instance. Its `history` attribute contains all
* information collected during training.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async fitDataset(dataset, args) {
return fitDataset(this, dataset, args);
}
/**
* Runs a single gradient update on a single batch of data.
*
* This method differs from `fit()` and `fitDataset()` in the following
* regards:
* - It operates on exactly one batch of data.
* - It returns only the loss and matric values, instead of
* returning the batch-by-batch loss and metric values.
* - It doesn't support fine-grained options such as verbosity and
* callbacks.
*
* @param x Input data. It could be one of the following:
* - A `tf.Tensor`, or an Array of `tf.Tensor`s (in case the model has
* multiple inputs).
* - An Object mapping input names to corresponding `tf.Tensor` (if the
* model has named inputs).
* @param y Target darta. It could be either a `tf.Tensor` a multiple
* `tf.Tensor`s. It should be consistent with `x`.
* @returns Training loss or losses (in case the model has
* multiple outputs), along with metrics (if any), as numbers.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async trainOnBatch(x, y) {
// TODO(cais): Support sampleWeight and classWeight.
// TODO(cais): Support Dataset objects.
const standardizeOut = await this.standardizeUserData(x, y);
const inputs = standardizeOut[0];
const targets = standardizeOut[1];
const trainFunction = this.makeTrainFunction();
const losses = trainFunction(inputs.concat(targets));
const lossValues = [];
for (const loss of losses) {
const v = await loss.data();
lossValues.push(v[0]);
}
dist["dispose"](losses);
return singletonOrArray(lossValues);
}
/**
* Extract weight values of the model.
*
* @param config: An instance of `io.SaveConfig`, which specifies
* model-saving options such as whether only trainable weights are to be
* saved.
* @returns A `NamedTensorMap` mapping original weight names (i.e.,
* non-uniqueified weight names) to their values.
*/
getNamedWeights(config) {
const namedWeights = [];
const trainableOnly = config != null && config.trainableOnly;
const weights = trainableOnly ? this.trainableWeights : this.weights;
const weightValues = this.getWeights(trainableOnly);
for (let i = 0; i < weights.length; ++i) {
if (trainableOnly && !weights[i].trainable) {
// Optionally skip non-trainable weights.
continue;
}
namedWeights.push({ name: weights[i].originalName, tensor: weightValues[i] });
}
return namedWeights;
}
/**
* Setter used for force stopping of LayersModel.fit() (i.e., training).
*
* Example:
*
* ```js
* const input = tf.input({shape: [10]});
* const output = tf.layers.dense({units: 1}).apply(input);
* const model = tf.model({inputs: [input], outputs: [output]});
* model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
* const xs = tf.ones([8, 10]);
* const ys = tf.zeros([8, 1]);
*
* const history = await model.fit(xs, ys, {
* epochs: 10,
* callbacks: {
* onEpochEnd: async (epoch, logs) => {
* if (epoch === 2) {
* model.stopTraining = true;
* }
* }
* }
* });
*
* // There should be only 3 values in the loss array, instead of 10
* values,
* // due to the stopping after 3 epochs.
* console.log(history.history.loss);
* ```
*/
set stopTraining(stop) {
this.stopTraining_ = stop;
}
get stopTraining() {
return this.stopTraining_;
}
get optimizer() {
return this.optimizer_;
}
set optimizer(optimizer) {
if (this.optimizer_ !== optimizer) {
this.optimizer_ = optimizer;
this.isOptimizerOwned = false;
}
}
dispose() {
const result = super.dispose();
if (
result.refCountAfterDispose === 0 &&
this.optimizer != null &&
this.isOptimizerOwned
) {
const numTensorsBeforeOptmizerDisposal = dist["memory"]().numTensors;
this.optimizer_.dispose();
result.numDisposedVariables +=
numTensorsBeforeOptmizerDisposal - dist["memory"]().numTensors;
}
return result;
}
getLossIdentifiers() {
let lossNames;
if (typeof this.loss === "string") {
lossNames = toSnakeCase(this.loss);
} else if (Array.isArray(this.loss)) {
for (const loss of this.loss) {
if (typeof loss !== "string") {
throw new Error("Serialization of non-string loss is not supported.");
}
}
lossNames = this.loss.map((name) => toSnakeCase(name));
} else {
const outputNames = Object.keys(this.loss);
lossNames = {};
const losses = this.loss;
for (const outputName of outputNames) {
if (typeof losses[outputName] === "string") {
lossNames[outputName] = toSnakeCase(losses[outputName]);
} else {
throw new Error("Serialization of non-string loss is not supported.");
}
}
}
return lossNames;
}
getMetricIdentifiers() {
if (typeof this.metrics === "string" || typeof this.metrics === "function") {
return [toSnakeCase(getLossOrMetricName(this.metrics))];
} else if (Array.isArray(this.metrics)) {
return this.metrics.map((metric) => toSnakeCase(getLossOrMetricName(metric)));
} else {
const metricsIdentifiers = {};
for (const key in this.metrics) {
metricsIdentifiers[key] = toSnakeCase(getLossOrMetricName(this.metrics[key]));
}
return metricsIdentifiers;
}
}
getTrainingConfig() {
return {
loss: this.getLossIdentifiers(),
metrics: this.getMetricIdentifiers(),
optimizer_config: {
class_name: this.optimizer.getClassName(),
config: this.optimizer.getConfig(),
},
};
// TODO(cais): Add weight_metrics when they are supported.
// TODO(cais): Add sample_weight_mode when it's supported.
// TODO(cais): Add loss_weights when it's supported.
}
loadTrainingConfig(trainingConfig) {
if (trainingConfig.weighted_metrics != null) {
throw new Error("Loading weight_metrics is not supported yet.");
}
if (trainingConfig.loss_weights != null) {
throw new Error("Loading loss_weights is not supported yet.");
}
if (trainingConfig.sample_weight_mode != null) {
throw new Error("Loading sample_weight_mode is not supported yet.");
}
const tsConfig = convertPythonicToTs(trainingConfig.optimizer_config);
const optimizer = deserialize(tsConfig);
let loss;
if (typeof trainingConfig.loss === "string") {
loss = toCamelCase(trainingConfig.loss);
} else if (Array.isArray(trainingConfig.loss)) {
loss = trainingConfig.loss.map((lossEntry) => toCamelCase(lossEntry));
} else if (trainingConfig.loss != null) {
loss = {};
for (const key in trainingConfig.loss) {
loss[key] = toCamelCase(trainingConfig.loss[key]);
}
}
let metrics;
if (Array.isArray(trainingConfig.metrics)) {
metrics = trainingConfig.metrics.map((metric) => toCamelCase(metric));
} else if (trainingConfig.metrics != null) {
metrics = {};
for (const key in trainingConfig.metrics) {
metrics[key] = toCamelCase(trainingConfig.metrics[key]);
}
}
this.compile({ loss, metrics, optimizer });
}
/**
* Save the configuration and/or weights of the LayersModel.
*
* An `IOHandler` is an object that has a `save` method of the proper
* signature defined. The `save` method manages the storing or
* transmission of serialized data ("artifacts") that represent the
* model's topology and weights onto or via a specific medium, such as
* file downloads, local storage, IndexedDB in the web browser and HTTP
* requests to a server. TensorFlow.js provides `IOHandler`
* implementations for a number of frequently used saving mediums, such as
* `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`
* for more details.
*
* This method also allows you to refer to certain types of `IOHandler`s
* as URL-like string shortcuts, such as 'localstorage://' and
* 'indexeddb://'.
*
* Example 1: Save `model`'s topology and weights to browser [local
* storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
* then load it back.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* console.log('Prediction from original model:');
* model.predict(tf.ones([1, 3])).print();
*
* const saveResults = await model.save('localstorage://my-model-1');
*
* const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');
* console.log('Prediction from loaded model:');
* loadedModel.predict(tf.ones([1, 3])).print();
* ```
*
* Example 2. Saving `model`'s topology and weights to browser
* [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API);
* then load it back.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* console.log('Prediction from original model:');
* model.predict(tf.ones([1, 3])).print();
*
* const saveResults = await model.save('indexeddb://my-model-1');
*
* const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');
* console.log('Prediction from loaded model:');
* loadedModel.predict(tf.ones([1, 3])).print();
* ```
*
* Example 3. Saving `model`'s topology and weights as two files
* (`my-model-1.json` and `my-model-1.weights.bin`) downloaded from
* browser.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* const saveResults = await model.save('downloads://my-model-1');
* ```
*
* Example 4. Send `model`'s topology and weights to an HTTP server.
* See the documentation of `tf.io.http` for more details
* including specifying request parameters and implementation of the
* server.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* const saveResults = await model.save('http://my-server/model/upload');
* ```
*
* @param handlerOrURL An instance of `IOHandler` or a URL-like,
* scheme-based string shortcut for `IOHandler`.
* @param config Options for saving the model.
* @returns A `Promise` of `SaveResult`, which summarizes the result of
* the saving, such as byte sizes of the saved artifacts for the model's
* topology and weight values.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
*/
async save(handlerOrURL, config) {
if (typeof handlerOrURL === "string") {
const handlers = dist["io"].getSaveHandlers(handlerOrURL);
if (handlers.length === 0) {
throw new ValueError(`Cannot find any save handlers for URL '${handlerOrURL}'`);
} else if (handlers.length > 1) {
throw new ValueError(
`Found more than one (${handlers.length}) save handlers for ` +
`URL '${handlerOrURL}'`
);
}
handlerOrURL = handlers[0];
}
if (handlerOrURL.save == null) {
throw new ValueError(
"LayersModel.save() cannot proceed because the IOHandler " +
"provided does not have the `save` attribute defined."
);
}
const weightDataAndSpecs = await dist["io"].encodeWeights(this.getNamedWeights(config));
const returnString = false;
const unusedArg = null;
const modelConfig = this.toJSON(unusedArg, returnString);
const modelArtifacts = {
modelTopology: modelConfig,
format: LAYERS_MODEL_FORMAT_NAME,
generatedBy: `TensorFlow.js tfjs-layers v${version}`,
convertedBy: null,
};
const includeOptimizer = config == null ? false : config.includeOptimizer;
if (includeOptimizer && this.optimizer != null) {
modelArtifacts.trainingConfig = this.getTrainingConfig();
const weightType = "optimizer";
const { data: optimizerWeightData, specs: optimizerWeightSpecs } = await dist[
"io"
].encodeWeights(await this.optimizer.getWeights(), weightType);
weightDataAndSpecs.specs.push(...optimizerWeightSpecs);
weightDataAndSpecs.data = dist["io"].concatenateArrayBuffers([
weightDataAndSpecs.data,
optimizerWeightData,
]);
}
if (this.userDefinedMetadata != null) {
// Check serialized size of user-defined metadata.
const checkSize = true;
checkUserDefinedMetadata(this.userDefinedMetadata, this.name, checkSize);
modelArtifacts.userDefinedMetadata = this.userDefinedMetadata;
}
modelArtifacts.weightData = weightDataAndSpecs.data;
modelArtifacts.weightSpecs = weightDataAndSpecs.specs;
return handlerOrURL.save(modelArtifacts);
}
/**
* Set user-defined metadata.
*
* The set metadata will be serialized together with the topology
* and weights of the model during `save()` calls.
*
* @param setUserDefinedMetadata
*/
setUserDefinedMetadata(userDefinedMetadata) {
checkUserDefinedMetadata(userDefinedMetadata, this.name);
this.userDefinedMetadata = userDefinedMetadata;
}
/**
* Get user-defined metadata.
*
* The metadata is supplied via one of the two routes:
* 1. By calling `setUserDefinedMetadata()`.
* 2. Loaded during model loading (if the model is constructed
* via `tf.loadLayersModel()`.)
*
* If no user-defined metadata is available from either of the
* two routes, this function will return `undefined`.
*/
getUserDefinedMetadata() {
return this.userDefinedMetadata;
}
}
// The class name is 'Model' rather than 'LayersModel' for backwards
// compatibility since this class name shows up in the serialization format.
/** @nocollapse */
training_LayersModel.className = "Model";
dist["serialization"].registerClass(training_LayersModel);
//# sourceMappingURL=training.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/models.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original source keras/models.py */
/**
* Parses a JSON model configuration file and returns a model instance.
*
* ```js
* // This example shows how to serialize a model using `toJSON()` and
* // deserialize it as another model using `tf.models.modelFromJSON()`.
* // Note: this example serializes and deserializes only the topology
* // of the model; the weights of the loaded model will be different
* // from those of the the original model, due to random weight
* // initialization.
* // To load the topology and weights of a model, use `tf.loadLayersModel()`.
* const model1 = tf.sequential();
* model1.add(tf.layers.repeatVector({inputShape: [2], n: 4}));
* // Serialize `model1` as a JSON object.
* const model1JSON = model1.toJSON(null, false);
* model1.summary();
*
* const model2 = await tf.models.modelFromJSON(model1JSON);
* model2.summary();
* ```
*
* @param modelAndWeightsConfig JSON object or string encoding a model and
* weights configuration. It can also be only the topology JSON of the
* model, in which case the weights will not be loaded.
* @param custom_objects Optional dictionary mapping names
* (strings) to custom classes or functions to be
* considered during deserialization.
* @returns A TensorFlow.js Layers `tf.LayersModel` instance (uncompiled).
*/
async function modelFromJSON(modelAndWeightsConfig, customObjects) {
if (!("modelTopology" in modelAndWeightsConfig)) {
modelAndWeightsConfig = { modelTopology: modelAndWeightsConfig };
}
modelAndWeightsConfig = modelAndWeightsConfig;
let modelTopology = modelAndWeightsConfig.modelTopology;
if (modelTopology["model_config"] != null) {
// If the model-topology JSON contains a 'model_config' field, then it is
// a full model JSON (e.g., from `keras.Model.save()`), which contains
// not only the model's architecture in its 'model_config' field, but
// additional information such as the model's optimizer. We use only the
// 'model_config' field currently.
modelTopology = modelTopology["model_config"];
}
const tsConfig = convertPythonicToTs(modelTopology);
const model = deserialize(tsConfig, customObjects);
if (modelAndWeightsConfig.weightsManifest != null) {
// Load the weight values keyed by the original tensor names in the model
// file that was loaded. These should match the keys of the weight
// manifest.
const weightValues = await dist["io"].loadWeights(
modelAndWeightsConfig.weightsManifest,
modelAndWeightsConfig.pathPrefix,
model.weights.map((weight) => weight.originalName)
);
// Map the weights to the unique tensor names generated during model loading
const uniqueWeightValues = {};
for (const weight of model.weights) {
uniqueWeightValues[weight.originalName] = weightValues[weight.originalName];
}
model.loadWeights(uniqueWeightValues);
// Dispose temporary weight values.
Object(dist["dispose"])(weightValues);
}
return model;
}
/**
* Load a model, including its topology and optionally weights. See the
* Tutorial named "How to import a Keras Model" for usage examples.
*
* Example 1: Save `model`'s topology and weights to browser [local
* storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
* then load it back.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* console.log('Prediction from original model:');
* model.predict(tf.ones([1, 3])).print();
*
* const saveResults = await model.save('localstorage://my-model-1');
*
* const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');
* console.log('Prediction from loaded model:');
* loadedModel.predict(tf.ones([1, 3])).print();
* ```
*
* Example 2. Saving `model`'s topology and weights to browser
* [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API);
* then load it back.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* console.log('Prediction from original model:');
* model.predict(tf.ones([1, 3])).print();
*
* const saveResults = await model.save('indexeddb://my-model-1');
*
* const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');
* console.log('Prediction from loaded model:');
* loadedModel.predict(tf.ones([1, 3])).print();
* ```
*
* Example 3. Load a model from user-selected files from HTML
* [file input
* elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file).
*
* ```js
* // Note: this code snippet will not work without the HTML elements in the
* // page
* const jsonUpload = document.getElementById('json-upload');
* const weightsUpload = document.getElementById('weights-upload');
*
* const model = await tf.loadLayersModel(
* tf.io.browserFiles([jsonUpload.files[0], weightsUpload.files[0]]));
* ```
*
* Example 4. Load a model from an HTTP server.
*
* ```js
* const model = await
* tf.loadLayersModel('https://storage.googleapis.com/tfjs-models/tfjs/iris_v1/model.json');
* model.summary();
* ```
*
* @param pathOrIOHandler Can be either of the two formats
* 1. A string path to the `ModelAndWeightsConfig` JSON describing
* the model in the canonical TensorFlow.js format. This path will be
* interpreted as a relative HTTP path, to which `fetch` will be used to
* request the model topology and weight manifest JSON.
* The content of the JSON file is assumed to be a JSON object with the
* following fields and values:
* - 'modelTopology': A JSON object that can be either of:
* 1. a model architecture JSON consistent with the format of the return
* value of `keras.Model.to_json()`
* 2. a full model JSON in the format of `keras.models.save_model()`.
* - 'weightsManifest': A TensorFlow.js weights manifest.
* See the Python converter function `save_model()` for more details.
* It is also assumed that model weights can be accessed from relative
* paths described by the `paths` fields in weights manifest.
* 2. An `tf.io.IOHandler` object that loads model artifacts with its `load`
* method.
* @param options Optional configuration arguments for the model loading,
* including:
* - `strict`: Require that the provided weights exactly match those required
* by the layers. Default true. Passing false means that both extra
* weights and missing weights will be silently ignored.
* - `onProgress`: A progress callback of the form:
* `(fraction: number) => void`. This callback can be used to monitor the
* model-loading process.
* @returns A `Promise` of `tf.LayersModel`, with the topology and weights
* loaded.
*/
async function loadLayersModelInternal(pathOrIOHandler, options) {
if (options == null) {
options = {};
}
if (typeof pathOrIOHandler === "string") {
const handlers = dist["io"].getLoadHandlers(pathOrIOHandler, options);
if (handlers.length === 0) {
// For backward compatibility: if no load handler can be found,
// assume it is a relative http path.
// TODO(cais): Reformat the args into a single `LoadOptions` once the core
// is refactored.
handlers.push(dist["io"].browserHTTPRequest(pathOrIOHandler, options));
} else if (handlers.length > 1) {
throw new ValueError(
`Found more than one (${handlers.length}) load handlers for ` +
`URL '${pathOrIOHandler}'`
);
}
pathOrIOHandler = handlers[0];
}
return loadLayersModelFromIOHandler(pathOrIOHandler, undefined, options);
}
/**
* Load a model and optionally its weights, using an IOHandler object.
*
* @param handler The instance of `IOHandler` to be used during the model
* loading.
* @param customObjects Any optional custom objects to be used during model
* loading.
* @param strict Whether the weight loading will be done in strict mode.
* Default: `true`.
*/
async function loadLayersModelFromIOHandler(handler, customObjects, options) {
if (options == null) {
options = {};
}
if (handler.load == null) {
throw new ValueError(
"Cannot proceed with model loading because the IOHandler provided " +
"does not have the `load` method implemented."
);
}
const artifacts = await handler.load();
let modelTopology = artifacts.modelTopology;
if (modelTopology["model_config"] != null) {
modelTopology = modelTopology["model_config"];
}
const strict = options.strict == null ? true : options.strict;
// If weights are provided and the weight-loading mode is strict, use
// fast weight initialization. This skips costly initializers such as
// 'orthogonal' and saves unnecessary computation in cases where
// the initialized weight values will immediately be overwritten by
// loaded weight values.
const fastWeightInit =
artifacts.weightData != null && artifacts.weightSpecs != null && strict;
const model = deserialize(
convertPythonicToTs(modelTopology),
customObjects,
fastWeightInit
);
const trainingConfig = artifacts.trainingConfig;
if (trainingConfig != null) {
model.loadTrainingConfig(trainingConfig);
}
if (artifacts.userDefinedMetadata != null) {
model.setUserDefinedMetadata(artifacts.userDefinedMetadata);
}
// If weightData is present, load the weights into the model.
if (artifacts.weightData != null) {
// Loading weights requires weightSpecs.
if (artifacts.weightSpecs == null) {
throw new ValueError(
"LayersModel artifacts contains weight data, but not weight specs. " +
"Therefore loading of weights cannot proceed."
);
}
const { modelWeights, optimizerWeights } = decodeModelAndOptimizerWeights(
artifacts.weightData,
artifacts.weightSpecs
);
model.loadWeights(modelWeights, strict);
if (model.optimizer != null && optimizerWeights.length > 0) {
await model.optimizer.setWeights(optimizerWeights);
}
// Dispose temporary weight values.
Object(dist["dispose"])(modelWeights);
Object(dist["dispose"])(optimizerWeights.map((w) => w.tensor));
}
return model;
}
function decodeModelAndOptimizerWeights(buffer, specs) {
const name2Tensor = dist["io"].decodeWeights(buffer, specs);
const modelWeights = {};
const optimizerWeights = [];
specs.forEach((spec) => {
if (spec.group === "optimizer") {
optimizerWeights.push({ name: spec.name, tensor: name2Tensor[spec.name] });
} else {
modelWeights[spec.name] = name2Tensor[spec.name];
}
});
return { modelWeights, optimizerWeights };
}
/**
* A model with a stack of layers, feeding linearly from one to the next.
*
* `tf.sequential` is a factory function that creates an instance of
* `tf.Sequential`.
*
* ```js
* // Define a model for linear regression.
* const model = tf.sequential();
* model.add(tf.layers.dense({units: 1, inputShape: [1]}));
*
* // Prepare the model for training: Specify the loss and the optimizer.
* model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
*
* // Generate some synthetic data for training.
* const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
* const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
*
* // Train the model using the data then do inference on a data point the
* // model hasn't seen:
* await model.fit(xs, ys);
* model.predict(tf.tensor2d([5], [1, 1])).print();
* ```
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
class models_Sequential extends training_LayersModel {
constructor(args) {
super({ inputs: [], outputs: [] });
args = args || {};
this.trainable = true;
this.built = false;
// Set model name.
this.name = args.name != null ? args.name : getUid("sequential_");
// Add to the model any layers passed to the constructor.
if (args.layers != null) {
for (const layer of args.layers) {
this.add(layer);
}
}
}
// Helper function to Sequential.add Throws if the new output shape will be
// invalid.
checkShape(layer) {
const shape = layer.inboundNodes[0].outputTensors[0].shape;
if (shape.some((x) => x < 0)) {
throw new ValueError(
"Negative dimension size caused by adding layer " +
`${layer.name} with input shape [` +
`${layer.inboundNodes[0].inputTensors[0].shape}]`
);
}
}
/**
* Adds a layer instance on top of the layer stack.
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.dense({units: 8, inputShape: [1]}));
* model.add(tf.layers.dense({units: 4, activation: 'relu6'}));
* model.add(tf.layers.dense({units: 1, activation: 'relu6'}));
* // Note that the untrained model is random at this point.
* model.predict(tf.randomNormal([10, 1])).print();
* ```
* @param layer Layer instance.
*
* @exception ValueError In case the `layer` argument does not know its
* input shape.
* @exception ValueError In case the `layer` argument has multiple output
* tensors, or is already connected somewhere else (forbidden in
* `Sequential` models).
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
add(layer) {
const isLayerModelInstance =
layer instanceof models_Sequential || layer instanceof training_LayersModel;
let modelLayer;
if (isLayerModelInstance) {
modelLayer = layer;
if (modelLayer.outputs.length !== 1) {
throw new ValueError(
"All layers in a Sequential model " +
"should have a single output tensor. " +
"For multi-output layers, " +
"use the functional API."
);
}
if (modelLayer.inputs.length !== 1) {
throw new ValueError(
"All layers in a Sequential model " +
"should have a single input tensor. " +
"For multi-input layers, " +
"use the functional API."
);
}
}
if (this.outputs.length === 0) {
// first layer in model: check that it is an input layer
if (layer.inboundNodes.length === 0) {
// create an input layer
if (layer.batchInputShape == null) {
throw new ValueError(
"The first layer in a Sequential model must " +
"get an `inputShape` or `batchInputShape` argument."
);
}
// Instantiate the input layer.
const x = Input({
batchShape: layer.batchInputShape,
dtype: layer.dtype,
name: layer.name + "_input",
});
// This will build the current layer and create the node connecting
// the current layer to the input layer we just created.
layer.apply(x);
}
if (isLayerModelInstance) {
this.outputs = modelLayer.outputs;
this.inputs = modelLayer.inputs;
} else {
if (layer.inboundNodes.length !== 1) {
throw new ValueError(
"A layer added to a Sequential model must not already be " +
`connected somewhere else. LayersModel received layer ${layer.name} ` +
`which has ${layer.inboundNodes.length} pre-existing inbound ` +
"connections."
);
}
if (layer.inboundNodes[0].outputTensors.length !== 1) {
throw new ValueError(
"All layers in a Sequential model " +
"should have a single output tensor. " +
"For multi-output layers, " +
"use the functional API."
);
}
this.checkShape(layer);
this.outputs = [layer.inboundNodes[0].outputTensors[0]];
this.inputs = getSourceInputs(this.outputs[0]);
}
this.inboundNodes = [];
// We create an input node, which we will keep updated
// as we add more layers.
// (This call has side effects.)
// tslint:disable-next-line:no-unused-expression
new Node({
outboundLayer: this,
inboundLayers: [],
nodeIndices: [],
tensorIndices: [],
inputTensors: this.inputs,
outputTensors: this.outputs,
// no model-level masking for now
inputMasks: pyListRepeat(null, this.inputs.length),
outputMasks: [null],
inputShapes: this.inputs.map((x) => x.shape),
outputShapes: this.outputs[0].shape,
});
} else {
const outputTensor = layer.apply(this.outputs[0]);
if (Array.isArray(outputTensor)) {
throw new TypeError(
"All layers in a Sequential model " +
"should have a single output tensor. " +
"For multi-output layers, " +
"use the functional API."
);
}
this.checkShape(layer);
this.outputs = [outputTensor];
// update self.inbound_nodes
this.inboundNodes[0].outputTensors = this.outputs;
this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
}
this.layers.push(layer);
this.built = false;
}
/**
* Removes the last layer in the model.
*
* @exception TypeError if there are no layers in the model.
*/
pop() {
if (this.layers.length === 0) {
throw new TypeError("There are no layers in the model.");
}
this.layers.pop();
if (this.layers.length === 0) {
this.outputs = [];
this.inboundNodes = [];
this.outboundNodes = [];
} else {
const lastLayerIndex = this.layers.length - 1;
this.layers[lastLayerIndex].outboundNodes = [];
this.outputs = [this.layers[lastLayerIndex].output];
// update self.inbound_nodes
this.inboundNodes[0].outputTensors = this.outputs;
this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
}
}
call(inputs, kwargs) {
if (this.model == null) {
this.build();
}
return this.model.call(inputs, kwargs);
}
build(inputShape) {
// Call `getExactlyOneShape` without using its return value,
// to verify that exactly one input shape is provided.
getExactlyOneShape(inputShape);
if (this.inputs.length === 0 || this.outputs.length === 0) {
throw new TypeError(
"Sequential model cannot be built: model is empty." + " Add some layers first."
);
}
// actually create the model
this.model = new training_LayersModel({
inputs: this.inputs,
outputs: this.outputs[0],
name: this.name + "_model",
});
this.model.trainable = this.trainable;
// mirror model attributes
this.supportsMasking = this.model.supportsMasking;
// TODO(michaelterry): Add caches
this.inputLayers = this.model.inputLayers;
this.inputLayersNodeIndices = this.model.inputLayersNodeIndices;
this.inputLayersTensorIndices = this.model.inputLayersTensorIndices;
this.outputLayers = this.model.outputLayers;
this.outputLayersNodeIndices = this.model.outputLayersNodeIndices;
this.outputLayersTensorIndices = this.model.outputLayersTensorIndices;
this.nodesByDepth = this.model.nodesByDepth;
this.containerNodes = this.model.containerNodes;
this.outputNames = this.model.outputNames;
this.inputNames = this.model.inputNames;
// TODO(michaelterry): Add feedInputNames, feedInputs, if needed.
// TODO(michaelterry): Add callbackModel if needed.
this.built = true;
}
countParams() {
if (!this.built) {
this.build();
}
return super.countParams();
}
/**
* Print a text summary of the Sequential model's layers.
*
* The summary includes
* - Name and type of all layers that comprise the model.
* - Output shape(s) of the layers
* - Number of weight parameters of each layer
* - The total number of trainable and non-trainable parameters of the
* model.
*
* ```js
* const model = tf.sequential();
* model.add(
* tf.layers.dense({units: 100, inputShape: [10], activation: 'relu'}));
* model.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));
*
* model.summary();
* ```
*
* @param lineLength Custom line length, in number of characters.
* @param positions Custom widths of each of the columns, as either
* fractions of `lineLength` (e.g., `[0.5, 0.75, 1]`) or absolute number
* of characters (e.g., `[30, 50, 65]`). Each number corresponds to
* right-most (i.e., ending) position of a column.
* @param printFn Custom print function. Can be used to replace the default
* `console.log`. For example, you can use `x => {}` to mute the printed
* messages in the console.
*/
/** @doc {heading: 'Models', subheading: 'Classes'} */
summary(lineLength, positions, printFn = console.log) {
if (!this.built) {
this.build();
}
super.summary(lineLength, positions, printFn);
}
/**
* Sets the weights of the model.
*
* @param weights Should be a list of Tensors with shapes and types matching
* the output of `model.getWeights()`.
*/
setWeights(weights) {
if (this.model == null) {
this.build();
}
this.model.setWeights(weights);
}
/**
* Returns the loss value & metrics values for the model in test mode.
*
* Loss and metrics are specified during `compile()`, which needs to happen
* before calls to `evaluate()`.
*
* Computation is done in batches.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* const result = model.evaluate(tf.ones([8, 10]), tf.ones([8, 1]), {
* batchSize: 4,
* });
* result.print();
* ```
*
* @param x `tf.Tensor` of test data, or an `Array` of `tf.Tensor`s if the
* model has multiple inputs.
* @param y `tf.Tensor` of target data, or an `Array` of `tf.Tensor`s if the
* model has multiple outputs.
* @param args A `ModelEvaluateConfig`, containing optional fields.
*
* @return `Scalar` test loss (if the model has a single output and no
* metrics) or `Array` of `Scalar`s (if the model has multiple outputs
* and/or metrics). The attribute `model.metricsNames`
* will give you the display labels for the scalar outputs.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
evaluate(x, y, args = {}) {
if (!this.built) {
throw new RuntimeError("The model needs to be compiled before being used.");
}
return this.model.evaluate(x, y, args);
}
// TODO(cais): Add code snippet below once real dataset objects are
// available.
/**
* Evaluate model using a dataset object.
*
* Note: Unlike `evaluate()`, this method is asynchronous (`async`);
*
* @param dataset A dataset object. Its `iterator()` method is expected
* to generate a dataset iterator object, the `next()` method of which
* is expected to produce data batches for evaluation. The return value
* of the `next()` call ought to contain a boolean `done` field and a
* `value` field. The `value` field is expected to be an array of two
* `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former
* case is for models with exactly one input and one output (e.g..
* a sequential model). The latter case is for models with multiple
* inputs and/or multiple outputs. Of the two items in the array, the
* first is the input feature(s) and the second is the output target(s).
* @param args A configuration object for the dataset-based evaluation.
* @returns Loss and metric values as an Array of `Scalar` objects.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async evaluateDataset(dataset, args) {
if (!this.built) {
throw new RuntimeError("The model needs to be compiled before being used.");
}
return this.model.evaluateDataset(dataset, args);
}
/**
* Generates output predictions for the input samples.
*
* Computation is done in batches.
*
* Note: the "step" mode of predict() is currently not supported.
* This is because the TensorFow.js core backend is imperative only.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.predict(tf.ones([2, 10])).print();
* ```
*
* @param x The input data, as a Tensor, or an `Array` of `tf.Tensor`s if
* the model has multiple inputs.
* @param conifg A `ModelPredictConfig` object containing optional fields.
*
* @return `tf.Tensor`(s) of predictions.
*
* @exception ValueError In case of mismatch between the provided input data
* and the model's expectations, or in case a stateful model receives a
* number of samples that is not a multiple of the batch size.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
predict(x, args = {}) {
if (this.model == null) {
this.build();
}
return this.model.predict(x, args);
}
/**
* Returns predictions for a single batch of samples.
*
* @param x: Input samples, as a Tensor, or list of Tensors (if the model
* has multiple inputs).
* @return Tensor(s) of predictions
*/
predictOnBatch(x) {
if (this.model == null) {
this.build();
}
return this.model.predictOnBatch(x);
}
/**
* See `LayersModel.compile`.
*
* @param args
*/
compile(args) {
this.build();
this.model.compile(args);
this.optimizer_ = this.model.optimizer;
// tslint:disable-next-line:no-any
this.isOptimizerOwned = this.model.isOptimizerOwned;
this.loss = this.model.loss;
this.metrics = this.model.metrics;
// TODO(cais): Add this.lossWeights, this.sampleWeightMode,
// this.weightedMetrics, this.targets.
this.metricsTensors = this.model.metricsTensors;
this.metricsNames = this.model.metricsNames;
// TODO(cais): Add sampleWeights.
}
get optimizer() {
return this.model == null ? undefined : this.model.optimizer;
}
set optimizer(optimizer) {
this.model.optimizer = optimizer;
}
/**
* Trains the model for a fixed number of epochs (iterations on a dataset).
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* const history = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
* batchSize: 4,
* epochs: 3
* });
* console.log(history.history.loss[0]);
* ```
*
* @param x `tf.Tensor` of training data, or an array of `tf.Tensor`s if the
* model has multiple inputs. If all inputs in the model are named, you can
* also pass a dictionary mapping input names to `tf.Tensor`s.
* @param y `tf.Tensor` of target (label) data, or an array of `tf.Tensor`s if
* the model has multiple outputs. If all outputs in the model are named, you
* can also pass a dictionary mapping output names to `tf.Tensor`s.
* @param args A `ModelFitConfig`, containing optional fields.
*
* @return A `History` instance. Its `history` attribute contains all
* information collected during training.
*
* @exception ValueError In case of mismatch between the provided input data
* and what the model expects.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async fit(x, y, args = {}) {
if (!this.built) {
throw new RuntimeError("The model needs to be compiled before " + "being used.");
}
return this.model.fit(x, y, args);
}
/**
* Trains the model using a dataset object.
*
* ```js
* const xArray = [
* [1, 1, 1, 1, 1, 1, 1, 1, 1],
* [1, 1, 1, 1, 1, 1, 1, 1, 1],
* [1, 1, 1, 1, 1, 1, 1, 1, 1],
* [1, 1, 1, 1, 1, 1, 1, 1, 1],
* ];
* const yArray = [1, 1, 1, 1];
* // Create a dataset from the JavaScript array.
* const xDataset = tf.data.array(xArray);
* const yDataset = tf.data.array(yArray);
* // Zip combines the `x` and `y` Datasets into a single Dataset, the
* // iterator of which will return an object containing of two tensors,
* // corresponding to `x` and `y`. The call to `batch(4)` will bundle
* // four such samples into a single object, with the same keys now pointing
* // to tensors that hold 4 examples, organized along the batch dimension.
* // The call to `shuffle(4)` causes each iteration through the dataset to
* // happen in a different order. The size of the shuffle window is 4.
* const xyDataset = tf.data.zip({xs: xDataset, ys: yDataset})
* .batch(4)
* .shuffle(4);
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [9]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* const history = await model.fitDataset(xyDataset, {
* epochs: 4,
* callbacks: {onEpochEnd: (epoch, logs) => console.log(logs.loss)}
* });
* ```
*
* @param dataset A dataset object. Its `iterator()` method is expected to
* generate a dataset iterator object, the `next()` method of which is
* expected to produce data batches for evaluation. The return value of the
* `next()` call ought to contain a boolean `done` field and a `value`
* field.
*
* The `value` field is expected to be an object of with fields
* `xs` and `ys`, which point to the feature tensor and the target tensor,
* respectively. This case is for models with exactly one input and one
* output (e.g.. a sequential model). For example:
* ```js
* {value: {xs: xsTensor, ys: ysTensor}, done: false}
* ```
*
* If the model has multiple inputs, the `xs` field of `value` should
* be an object mapping input names to their respective feature tensors.
* For example:
* ```js
* {
* value: {
* xs: {
* input_1: xsTensor1,
* input_2: xsTensor2
* },
* ys: ysTensor
* },
* done: false
* }
* ```
* If the model has multiple outputs, the `ys` field of `value` should
* be an object mapping output names to their respective target tensors.
* For example:
* ```js
* {
* value: {
* xs: xsTensor,
* ys: {
* output_1: ysTensor1,
* output_2: ysTensor2
* },
* },
* done: false
* }
* ```
* @param args A `ModelFitDatasetArgs`, containing optional fields.
*
* @return A `History` instance. Its `history` attribute contains all
* information collected during training.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
*/
async fitDataset(dataset, args) {
if (!this.built) {
throw new RuntimeError("The model needs to be compiled before " + "being used.");
}
return this.model.fitDataset(dataset, args);
}
/**
* Runs a single gradient update on a single batch of data.
*
* This method differs from `fit()` and `fitDataset()` in the following
* regards:
* - It operates on exactly one batch of data.
* - It returns only the loss and matric values, instead of
* returning the batch-by-batch loss and metric values.
* - It doesn't support fine-grained options such as verbosity and
* callbacks.
*
* @param x Input data. It could be one of the following:
* - A `tf.Tensor`, or an Array of `tf.Tensor`s (in case the model has
* multiple inputs).
* - An Object mapping input names to corresponding `tf.Tensor` (if the
* model has named inputs).
* @param y Target darta. It could be either a `tf.Tensor` a multiple
* `tf.Tensor`s. It should be consistent with `x`.
* @returns Training loss or losses (in case the model has
* multiple outputs), along with metrics (if any), as numbers.
*/
/**
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async trainOnBatch(x, y) {
return this.model.trainOnBatch(x, y);
}
/* See parent class for JsDoc */
/** @nocollapse */
static fromConfig(cls, config, customObjects = {}, fastWeightInit = false) {
let configArray;
let extraModelConfig = {};
if (config instanceof Array) {
if (!(config[0].className != null) || config[0]["className"] === "Merge") {
throw new ValueError("Legacy serialization format not supported yet.");
}
configArray = config;
} else {
dist["util"].assert(
config["layers"] != null,
() =>
`When the config data for a Sequential model is not an Array, ` +
`it must be an Object that contains the 'layers' field.`
);
configArray = config["layers"];
delete config["layers"];
extraModelConfig = config;
}
const model = new cls(extraModelConfig);
if (!(model instanceof models_Sequential)) {
throw new NotImplementedError(
`Sequential.fromConfig called on non-Sequential input: ${model}`
);
}
for (const conf of configArray) {
const customObjects = undefined;
const layer = deserialize(conf, customObjects, fastWeightInit);
if (fastWeightInit) {
layer.setFastWeightInitDuringBuild(true);
}
model.add(layer);
}
return model;
}
/**
* Setter used for force stopping of LayersModel.fit() (i.e., training).
*
* Example:
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.dense({units: 1, inputShape: [10]}));
* model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
* const xs = tf.ones([8, 10]);
* const ys = tf.zeros([8, 1]);
*
* const history = await model.fit(xs, ys, {
* epochs: 10,
* callbacks: {
* onEpochEnd: async (epoch, logs) => {
* if (epoch === 2) {
* model.stopTraining = true;
* }
* }
* }
* });
*
* // There should be only 3 values in the loss array, instead of 10 values,
* // due to the stopping after 3 epochs.
* console.log(history.history.loss);
* ```
*/
set stopTraining(stop) {
// TODO(cais): When refactoring to remove the composition pattern happens,
// remove this method overriding.
if (this.model == null) {
throw new ValueError(
"Cannot set the stopTraining property of a sequential model before " +
"it is compiled."
);
}
this.model.stopTraining = stop;
}
get stopTraining() {
if (this.model == null) {
throw new ValueError(
"Cannot get the stopTraining property of a sequential model before " +
"it is compiled."
);
}
return this.model.stopTraining;
}
// TODO(cais): Override get trainableWeights() here
// tslint:disable-next-line:no-any
getConfig() {
// NOTE(cais): We override the return type of getConfig() to `any` here,
// because the `Sequential` class is a special case among `Container`
// subtypes in that its getConfig() method returns an Array (not a
// dict).
const layers = [];
for (const layer of this.layers) {
const dict = {};
dict["className"] = layer.getClassName();
dict["config"] = layer.getConfig();
layers.push(dict);
}
return { name: this.name, layers };
}
}
/** @nocollapse */
models_Sequential.className = "Sequential";
dist["serialization"].registerClass(models_Sequential);
//# sourceMappingURL=models.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/exports.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// TODO(cais): Add doc string to all the public static functions in this
// class; include exectuable JavaScript code snippets where applicable
// (b/74074458).
// LayersModel and related factory methods.
/**
* A model is a data structure that consists of `Layers` and defines inputs
* and outputs.
*
* The key difference between `tf.model` and `tf.sequential` is that
* `tf.model` is more generic, supporting an arbitrary graph (without
* cycles) of layers. `tf.sequential` is less generic and supports only a linear
* stack of layers.
*
* When creating a `tf.LayersModel`, specify its input(s) and output(s). Layers
* are used to wire input(s) to output(s).
*
* For example, the following code snippet defines a model consisting of
* two `dense` layers, with 10 and 4 units, respectively.
*
* ```js
* // Define input, which has a size of 5 (not including batch dimension).
* const input = tf.input({shape: [5]});
*
* // First dense layer uses relu activation.
* const denseLayer1 = tf.layers.dense({units: 10, activation: 'relu'});
* // Second dense layer uses softmax activation.
* const denseLayer2 = tf.layers.dense({units: 4, activation: 'softmax'});
*
* // Obtain the output symbolic tensor by applying the layers on the input.
* const output = denseLayer2.apply(denseLayer1.apply(input));
*
* // Create the model based on the inputs.
* const model = tf.model({inputs: input, outputs: output});
*
* // The model can be used for training, evaluation and prediction.
* // For example, the following line runs prediction with the model on
* // some fake data.
* model.predict(tf.ones([2, 5])).print();
* ```
* See also:
* `tf.sequential`, `tf.loadLayersModel`.
*/
/**
* @doc {heading: 'Models', subheading: 'Creation'}
*/
function exports_model(args) {
return new training_LayersModel(args);
}
/**
* Creates a `tf.Sequential` model. A sequential model is any model where the
* outputs of one layer are the inputs to the next layer, i.e. the model
* topology is a simple 'stack' of layers, with no branching or skipping.
*
* This means that the first layer passed to a `tf.Sequential` model should have
* a defined input shape. What that means is that it should have received an
* `inputShape` or `batchInputShape` argument, or for some type of layers
* (recurrent, Dense...) an `inputDim` argument.
*
* The key difference between `tf.model` and `tf.sequential` is that
* `tf.sequential` is less generic, supporting only a linear stack of layers.
* `tf.model` is more generic and supports an arbitrary graph (without
* cycles) of layers.
*
* Examples:
*
* ```js
* const model = tf.sequential();
*
* // First layer must have an input shape defined.
* model.add(tf.layers.dense({units: 32, inputShape: [50]}));
* // Afterwards, TF.js does automatic shape inference.
* model.add(tf.layers.dense({units: 4}));
*
* // Inspect the inferred shape of the model's output, which equals
* // `[null, 4]`. The 1st dimension is the undetermined batch dimension; the
* // 2nd is the output size of the model's last layer.
* console.log(JSON.stringify(model.outputs[0].shape));
* ```
*
* It is also possible to specify a batch size (with potentially undetermined
* batch dimension, denoted by "null") for the first layer using the
* `batchInputShape` key. The following example is equivalent to the above:
*
* ```js
* const model = tf.sequential();
*
* // First layer must have a defined input shape
* model.add(tf.layers.dense({units: 32, batchInputShape: [null, 50]}));
* // Afterwards, TF.js does automatic shape inference.
* model.add(tf.layers.dense({units: 4}));
*
* // Inspect the inferred shape of the model's output.
* console.log(JSON.stringify(model.outputs[0].shape));
* ```
*
* You can also use an `Array` of already-constructed `Layer`s to create
* a `tf.Sequential` model:
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 32, inputShape: [50]}),
* tf.layers.dense({units: 4})]
* });
* console.log(JSON.stringify(model.outputs[0].shape));
* ```
*/
/**
* @doc {heading: 'Models', subheading: 'Creation'}
*/
function sequential(config) {
return new models_Sequential(config);
}
/**
* Load a model composed of Layer objects, including its topology and optionally
* weights. See the Tutorial named "How to import a Keras Model" for usage
* examples.
*
* This method is applicable to:
*
* 1. Models created with the `tf.layers.*`, `tf.sequential`, and
* `tf.model` APIs of TensorFlow.js and later saved with the
* `tf.LayersModel.save` method.
* 2. Models converted from Keras or TensorFlow tf.keras using the
* [tensorflowjs_converter](https://github.com/tensorflow/tfjs/tree/master/tfjs-converter).
*
* This mode is *not* applicable to TensorFlow `SavedModel`s or their converted
* forms. For those models, use `tf.loadGraphModel`.
*
* Example 1. Load a model from an HTTP server.
*
* ```js
* const model = await tf.loadLayersModel(
* 'https://storage.googleapis.com/tfjs-models/tfjs/iris_v1/model.json');
* model.summary();
* ```
*
* Example 2: Save `model`'s topology and weights to browser [local
* storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
* then load it back.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* console.log('Prediction from original model:');
* model.predict(tf.ones([1, 3])).print();
*
* const saveResults = await model.save('localstorage://my-model-1');
*
* const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');
* console.log('Prediction from loaded model:');
* loadedModel.predict(tf.ones([1, 3])).print();
* ```
*
* Example 3. Saving `model`'s topology and weights to browser
* [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API);
* then load it back.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* console.log('Prediction from original model:');
* model.predict(tf.ones([1, 3])).print();
*
* const saveResults = await model.save('indexeddb://my-model-1');
*
* const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');
* console.log('Prediction from loaded model:');
* loadedModel.predict(tf.ones([1, 3])).print();
* ```
*
* Example 4. Load a model from user-selected files from HTML
* [file input
* elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file).
*
* ```js
* // Note: this code snippet will not work without the HTML elements in the
* // page
* const jsonUpload = document.getElementById('json-upload');
* const weightsUpload = document.getElementById('weights-upload');
*
* const model = await tf.loadLayersModel(
* tf.io.browserFiles([jsonUpload.files[0], weightsUpload.files[0]]));
* ```
*
* @param pathOrIOHandler Can be either of the two formats
* 1. A string path to the `ModelAndWeightsConfig` JSON describing
* the model in the canonical TensorFlow.js format. For file://
* (tfjs-node-only), http:// and https:// schemas, the path can be
* either absolute or relative.
* 2. An `tf.io.IOHandler` object that loads model artifacts with its `load`
* method.
* @param options Optional configuration arguments for the model loading,
* including:
* - `strict`: Require that the provided weights exactly match those required
* by the layers. Default true. Passing false means that both extra
* weights and missing weights will be silently ignored.
* - `onProgress`: A function of the signature `(fraction: number) => void',
* that can be used as the progress callback for the model loading.
* @returns A `Promise` of `tf.LayersModel`, with the topology and weights
* loaded.
*/
/** @doc {heading: 'Models', subheading: 'Loading'} */
function loadLayersModel(pathOrIOHandler, options) {
if (options == null) {
options = {};
}
return loadLayersModelInternal(pathOrIOHandler, options);
}
/**
* Used to instantiate an input to a model as a `tf.SymbolicTensor`.
*
* Users should call the `input` factory function for
* consistency with other generator functions.
*
* Example:
*
* ```js
* // Defines a simple logistic regression model with 32 dimensional input
* // and 3 dimensional output.
* const x = tf.input({shape: [32]});
* const y = tf.layers.dense({units: 3, activation: 'softmax'}).apply(x);
* const model = tf.model({inputs: x, outputs: y});
* model.predict(tf.ones([2, 32])).print();
* ```
*
* Note: `input` is only necessary when using `model`. When using
* `sequential`, specify `inputShape` for the first layer or use `inputLayer`
* as the first layer.
*/
/** @doc {heading: 'Models', subheading: 'Inputs'} */
function exports_input(config) {
return Input(config);
}
function registerCallbackConstructor(verbosityLevel, callbackConstructor) {
base_callbacks_CallbackConstructorRegistry.registerCallbackConstructor(
verbosityLevel,
callbackConstructor
);
}
//# sourceMappingURL=exports.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/activations.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// Layer activation functions
/**
* Base class for Activations.
*
* Special note: due to cross-language compatibility reasons, the
* static readonly className field in this family of classes must be set to
* the initialLowerCamelCase name of the activation.
*/
class activations_Activation extends dist["serialization"].Serializable {
getConfig() {
return {};
}
}
/**
* Exponential linear unit (ELU).
* Reference: https://arxiv.org/abs/1511.07289
*/
class activations_Elu extends activations_Activation {
/**
* Calculate the activation function.
*
* @param x: Input.
* @param alpha: Scaling factor the negative section.
* @return Output of the ELU activation.
*/
apply(x, alpha = 1) {
return elu(x, alpha);
}
}
/** @nocollapse */
activations_Elu.className = "elu";
dist["serialization"].registerClass(activations_Elu);
/**
* Scaled Exponential Linear Unit. (Klambauer et al., 2017).
* Reference: Self-Normalizing Neural Networks, https://arxiv.org/abs/1706.02515
* Notes:
* - To be used together with the initialization "lecunNormal".
* - To be used together with the dropout variant "AlphaDropout".
*/
class activations_Selu extends activations_Activation {
apply(x) {
return dist["selu"](x);
}
}
/** @nocollapse */
activations_Selu.className = "selu";
dist["serialization"].registerClass(activations_Selu);
/**
* Rectified linear unit
*/
class activations_Relu extends activations_Activation {
apply(x) {
return dist["relu"](x);
}
}
/** @nocollapse */
activations_Relu.className = "relu";
dist["serialization"].registerClass(activations_Relu);
/**
* Rectified linear unit activation maxing out at 6.0.
*/
class activations_Relu6 extends activations_Activation {
apply(x) {
return Object(dist["tidy"])(() => dist["minimum"](6.0, dist["relu"](x)));
}
}
/** @nocollapse */
activations_Relu6.className = "relu6";
dist["serialization"].registerClass(activations_Relu6);
//* Linear activation (no-op) */
class Linear extends activations_Activation {
apply(x) {
return x;
}
}
/** @nocollapse */
Linear.className = "linear";
dist["serialization"].registerClass(Linear);
/**
* Sigmoid activation function.
*/
class activations_Sigmoid extends activations_Activation {
apply(x) {
return dist["sigmoid"](x);
}
}
/** @nocollapse */
activations_Sigmoid.className = "sigmoid";
dist["serialization"].registerClass(activations_Sigmoid);
/**
* Segment-wise linear approximation of sigmoid.
*/
class activations_HardSigmoid extends activations_Activation {
apply(x) {
return hardSigmoid(x);
}
}
/** @nocollapse */
activations_HardSigmoid.className = "hardSigmoid";
dist["serialization"].registerClass(activations_HardSigmoid);
/**
* Softplus activation function.
*/
class activations_Softplus extends activations_Activation {
apply(x) {
return dist["softplus"](x);
}
}
/** @nocollapse */
activations_Softplus.className = "softplus";
dist["serialization"].registerClass(activations_Softplus);
/**
* Softsign activation function.
*/
class activations_Softsign extends activations_Activation {
apply(x) {
return softsign(x);
}
}
/** @nocollapse */
activations_Softsign.className = "softsign";
dist["serialization"].registerClass(activations_Softsign);
/**
* Hyperbolic tangent function.
*/
class activations_Tanh extends activations_Activation {
apply(x) {
return dist["tanh"](x);
}
}
/** @nocollapse */
activations_Tanh.className = "tanh";
dist["serialization"].registerClass(activations_Tanh);
/**
* Softmax activation function
*/
class activations_Softmax extends activations_Activation {
/**
* Calculate the activation function.
*
* @param x Tensor.
* @param axis Integer, axis along which the softmax normalization is applied.
* Invalid if < 2, as softmax across 1 (the batch dimension) is assumed to be
* an error.
*
* @returns a Tensor of the same shape as x
*
* @throws ValueError: In case `dim(x) < 2`.
*/
apply(x, axis = -1) {
return dist["softmax"](x, axis);
}
}
/** @nocollapse */
activations_Softmax.className = "softmax";
dist["serialization"].registerClass(activations_Softmax);
/**
* Log softmax activation function
*/
class activations_LogSoftmax extends activations_Activation {
/**
* Calculate the activation function of log softmax:
* log( exp(x_i) / sum(exp(x)) )
*
* @param x Tensor.
* @param axis Integer, axis along which the softmax normalization is applied.
* Invalid if < 2, as softmax across 1 (the batch dimension) is assumed to be
* an error.
*
* @returns a Tensor of the same shape as x
*
* @throws ValueError: In case `dim(x) < 2`.
*/
apply(x, axis = -1) {
return dist["logSoftmax"](x, axis);
}
}
/** @nocollapse */
activations_LogSoftmax.className = "logSoftmax";
dist["serialization"].registerClass(activations_LogSoftmax);
function serializeActivation(activation) {
return activation.getClassName();
}
function deserializeActivation(config, customObjects = {}) {
return deserializeKerasObject(
config,
dist["serialization"].SerializationMap.getMap().classNameMap,
customObjects,
"activation"
);
}
function getActivation(identifier) {
if (identifier == null) {
const config = {};
config["className"] = "linear";
config["config"] = {};
return deserializeActivation(config);
}
if (typeof identifier === "string") {
const config = {};
config["className"] = identifier;
config["config"] = {};
return deserializeActivation(config);
} else if (identifier instanceof activations_Activation) {
return identifier;
} else {
return deserializeActivation(identifier);
}
}
//# sourceMappingURL=activations.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/regularizers.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* original source: keras/regularizers.py */
function assertObjectArgs(args) {
if (args != null && typeof args !== "object") {
throw new Error(
`Argument to L1L2 regularizer's constructor is expected to be an ` +
`object, but received: ${args}`
);
}
}
/**
* Regularizer base class.
*/
class regularizers_Regularizer extends dist["serialization"].Serializable {}
class regularizers_L1L2 extends regularizers_Regularizer {
constructor(args) {
super();
assertObjectArgs(args);
this.l1 = args == null || args.l1 == null ? 0.01 : args.l1;
this.l2 = args == null || args.l2 == null ? 0.01 : args.l2;
this.hasL1 = this.l1 !== 0;
this.hasL2 = this.l2 !== 0;
}
/**
* Porting note: Renamed from __call__.
* @param x Variable of which to calculate the regularization score.
*/
apply(x) {
return Object(dist["tidy"])(() => {
let regularization = Object(dist["zeros"])([1]);
if (this.hasL1) {
regularization = Object(dist["add"])(
regularization,
Object(dist["sum"])(dist["mul"](this.l1, Object(dist["abs"])(x)))
);
}
if (this.hasL2) {
regularization = Object(dist["add"])(
regularization,
Object(dist["sum"])(dist["mul"](this.l2, square(x)))
);
}
return regularization.asScalar();
});
}
getConfig() {
return { l1: this.l1, l2: this.l2 };
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls({ l1: config["l1"], l2: config["l2"] });
}
}
/** @nocollapse */
regularizers_L1L2.className = "L1L2";
dist["serialization"].registerClass(regularizers_L1L2);
function l1(args) {
assertObjectArgs(args);
return new regularizers_L1L2({ l1: args != null ? args.l1 : null, l2: 0 });
}
function l2(args) {
assertObjectArgs(args);
return new regularizers_L1L2({ l2: args != null ? args.l2 : null, l1: 0 });
}
// Maps the JavaScript-like identifier keys to the corresponding keras symbols.
const REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
l1l2: "L1L2",
};
function serializeRegularizer(constraint) {
return serializeKerasObject(constraint);
}
function deserializeRegularizer(config, customObjects = {}) {
return deserializeKerasObject(
config,
dist["serialization"].SerializationMap.getMap().classNameMap,
customObjects,
"regularizer"
);
}
function getRegularizer(identifier) {
if (identifier == null) {
return null;
}
if (typeof identifier === "string") {
const className =
identifier in REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP
? REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier]
: identifier;
const config = { className, config: {} };
return deserializeRegularizer(config);
} else if (identifier instanceof regularizers_Regularizer) {
return identifier;
} else {
return deserializeRegularizer(identifier);
}
}
//# sourceMappingURL=regularizers.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/advanced_activations.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Advanced activation layers.
*/
class advanced_activations_ReLU extends topology_Layer {
constructor(args) {
super(args == null ? {} : args);
this.supportsMasking = true;
if (args != null) {
this.maxValue = args.maxValue;
}
}
call(inputs, kwargs) {
inputs = getExactlyOneTensor(inputs);
let output = Object(dist["relu"])(inputs);
if (this.maxValue != null) {
output = Object(dist["clipByValue"])(output, 0, this.maxValue);
}
return output;
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const config = { maxValue: this.maxValue };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
advanced_activations_ReLU.className = "ReLU";
dist["serialization"].registerClass(advanced_activations_ReLU);
class advanced_activations_LeakyReLU extends topology_Layer {
constructor(args) {
super(args == null ? {} : args);
this.DEFAULT_ALPHA = 0.3;
if (args == null) {
args = {};
}
this.alpha = args.alpha == null ? this.DEFAULT_ALPHA : args.alpha;
}
call(inputs, kwargs) {
const x = getExactlyOneTensor(inputs);
return Object(dist["leakyRelu"])(x, this.alpha);
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const config = { alpha: this.alpha };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
advanced_activations_LeakyReLU.className = "LeakyReLU";
dist["serialization"].registerClass(advanced_activations_LeakyReLU);
class advanced_activations_PReLU extends topology_Layer {
constructor(args) {
super(args == null ? {} : args);
this.DEFAULT_ALPHA_INITIALIZER = "zeros";
if (args == null) {
args = {};
}
this.supportsMasking = true;
this.alphaInitializer = getInitializer(
args.alphaInitializer || this.DEFAULT_ALPHA_INITIALIZER
);
this.alphaRegularizer = getRegularizer(args.alphaRegularizer);
this.alphaConstraint = getConstraint(args.alphaConstraint);
if (args.sharedAxes == null) {
this.sharedAxes = null;
} else if (Array.isArray(args.sharedAxes)) {
this.sharedAxes = args.sharedAxes;
} else if (typeof args.sharedAxes === "number") {
this.sharedAxes = [args.sharedAxes];
} else {
throw new ValueError(
`Expected sharedAxes to be a number or an array of numbers, ` +
`but got ${args.sharedAxes}`
);
}
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const paramShape = inputShape.slice(1);
if (this.sharedAxes != null) {
for (const i of this.sharedAxes) {
paramShape[i - 1] = 1;
}
}
this.alpha = this.addWeight(
"alpha",
paramShape,
"float32",
this.alphaInitializer,
this.alphaRegularizer,
true,
this.alphaConstraint
);
// Set input spec.
const axes = {};
if (this.sharedAxes != null) {
for (let i = 1; i < inputShape.length; ++i) {
axes[i] = inputShape[i];
}
}
this.inputSpec = [
new InputSpec({
ndim: inputShape.length,
axes,
}),
];
this.built = true;
}
call(inputs, kwargs) {
inputs = getExactlyOneTensor(inputs);
return Object(dist["prelu"])(inputs, this.alpha.read());
}
getConfig() {
const config = {
alphaInitializer: serializeInitializer(this.alphaInitializer),
alphaRegularizer: serializeRegularizer(this.alphaRegularizer),
alphaConstraint: serializeConstraint(this.alphaConstraint),
sharedAxes: this.sharedAxes,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
advanced_activations_PReLU.className = "PReLU";
dist["serialization"].registerClass(advanced_activations_PReLU);
class advanced_activations_ELU extends topology_Layer {
constructor(args) {
super(args == null ? {} : args);
this.DEFAULT_ALPHA = 1.0;
if (args == null) {
args = {};
}
if (args.alpha != null && args.alpha !== this.DEFAULT_ALPHA) {
throw new NotImplementedError(
`Non-default alpha value (${args.alpha}) is not supported by the ` + `ELU layer yet.`
);
}
this.alpha = args.alpha == null ? this.DEFAULT_ALPHA : args.alpha;
}
call(inputs, kwargs) {
const x = getExactlyOneTensor(inputs);
return Object(dist["elu"])(x);
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const config = { alpha: this.alpha };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
advanced_activations_ELU.className = "ELU";
dist["serialization"].registerClass(advanced_activations_ELU);
class advanced_activations_ThresholdedReLU extends topology_Layer {
constructor(args) {
super(args == null ? {} : args);
this.DEFAULT_THETA = 1.0;
if (args == null) {
args = {};
}
this.theta = args.theta == null ? this.DEFAULT_THETA : args.theta;
}
call(inputs, kwargs) {
const x = getExactlyOneTensor(inputs);
return x.mul(cast(x.greater(this.theta), "float32"));
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const config = { theta: this.theta };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
advanced_activations_ThresholdedReLU.className = "ThresholdedReLU";
dist["serialization"].registerClass(advanced_activations_ThresholdedReLU);
class advanced_activations_Softmax extends topology_Layer {
constructor(args) {
super(args == null ? {} : args);
this.DEFAULT_AXIS = 1.0;
if (args == null) {
args = {};
}
this.softmax = new activations_Softmax().apply;
this.axis = args.axis == null ? this.DEFAULT_AXIS : args.axis;
}
call(inputs, kwargs) {
const x = getExactlyOneTensor(inputs);
return this.softmax(x, this.axis);
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const config = { axis: this.axis };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
advanced_activations_Softmax.className = "Softmax";
dist["serialization"].registerClass(advanced_activations_Softmax);
//# sourceMappingURL=advanced_activations.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/utils/conv_utils.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Transforms a single number of array of numbers into an array of numbers.
* @param value
* @param n: The size of the tuple to be returned.
* @param name: Name of the parameter, used for generating error messages.
* @returns An array of numbers.
*/
function normalizeArray(value, n, name) {
if (typeof value === "number") {
return pyListRepeat(value, n);
} else {
if (value.length !== n) {
throw new ValueError(
`The ${name} argument must be an integer or tuple of ${n} integers.` +
` Received: ${value.length} elements.`
);
}
for (let i = 0; i < n; ++i) {
const singleValue = value[i];
if (!isInteger(singleValue)) {
throw new ValueError(
`The ${name} argument must be an integer or tuple of ${n}` +
` integers. Received: ${JSON.stringify(value)} including a` +
` non-integer number ${singleValue}`
);
}
}
return value;
}
}
/**
* Determines output length of a convolution given input length.
* @param inputLength
* @param filterSize
* @param padding
* @param stride
* @param dilation: dilation rate.
*/
function convOutputLength(inputLength, filterSize, padding, stride, dilation = 1) {
if (inputLength == null) {
return inputLength;
}
const dilatedFilterSize = filterSize + (filterSize - 1) * (dilation - 1);
let outputLength;
if (padding === "same") {
outputLength = inputLength;
} else {
// VALID
outputLength = inputLength - dilatedFilterSize + 1;
}
return Math.floor((outputLength + stride - 1) / stride);
}
function deconvLength(dimSize, strideSize, kernelSize, padding) {
if (dimSize == null) {
return null;
}
if (padding === "valid") {
dimSize = dimSize * strideSize + max([kernelSize - strideSize, 0]);
} else if (padding === "same") {
dimSize = dimSize * strideSize;
} else {
throw new ValueError(`Unsupport padding mode: ${padding}.`);
}
return dimSize;
}
//# sourceMappingURL=conv_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/convolutional.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Convolutional Layers
*/
/**
* Transpose and cast the input before the conv2d.
* @param x Input image tensor.
* @param dataFormat
*/
function preprocessConv2DInput(x, dataFormat) {
// TODO(cais): Cast type to float32 if not.
return Object(dist["tidy"])(() => {
checkDataFormat(dataFormat);
if (dataFormat === "channelsFirst") {
return dist["transpose"](x, [0, 2, 3, 1]); // NCHW -> NHWC.
} else {
return x;
}
});
}
/**
* Transpose and cast the input before the conv3d.
* @param x Input image tensor.
* @param dataFormat
*/
function preprocessConv3DInput(x, dataFormat) {
return Object(dist["tidy"])(() => {
checkDataFormat(dataFormat);
if (dataFormat === "channelsFirst") {
return dist["transpose"](x, [0, 2, 3, 4, 1]); // NCDHW -> NDHWC.
} else {
return x;
}
});
}
/**
* 1D-convolution with bias added.
*
* Porting Note: This function does not exist in the Python Keras backend.
* It is exactly the same as `conv2d`, except the added `bias`.
*
* @param x Input tensor, rank-3, of shape `[batchSize, width, inChannels]`.
* @param kernel Kernel, rank-3, of shape `[filterWidth, inDepth, outDepth]`.
* @param bias Bias, rank-3, of shape `[outDepth]`.
* @param strides
* @param padding Padding mode.
* @param dataFormat Data format.
* @param dilationRate
* @returns The result of the 1D convolution.
* @throws ValueError, if `x`, `kernel` or `bias` is not of the correct rank.
*/
function conv1dWithBias(
x,
kernel,
bias,
strides = 1,
padding = "valid",
dataFormat,
dilationRate = 1
) {
return Object(dist["tidy"])(() => {
if (dataFormat == null) {
dataFormat = imageDataFormat();
}
checkDataFormat(dataFormat);
// Check the ranks of x, kernel and bias.
if (x.shape.length !== 3) {
throw new ValueError(
`The input of a conv1dWithBias operation should be 3, but is ` +
`${x.shape.length} instead.`
);
}
if (kernel.shape.length !== 3) {
throw new ValueError(
`The kernel for a conv1dWithBias operation should be 3, but is ` +
`${kernel.shape.length} instead`
);
}
if (bias != null && bias.shape.length !== 1) {
throw new ValueError(
`The bias for a conv1dWithBias operation should be 1, but is ` +
`${kernel.shape.length} instead`
);
}
// TODO(cais): Support CAUSAL padding mode.
if (dataFormat === "channelsFirst") {
x = dist["transpose"](x, [0, 2, 1]); // NCW -> NWC.
}
if (padding === "causal") {
throw new NotImplementedError(
"The support for CAUSAL padding mode in conv1dWithBias is not " + "implemented yet."
);
}
let y = dist["conv1d"](
x,
kernel,
strides,
padding === "same" ? "same" : "valid",
"NWC",
dilationRate
);
if (bias != null) {
y = biasAdd(y, bias);
}
return y;
});
}
/**
* 1D-convolution.
*
* @param x Input tensor, rank-3, of shape `[batchSize, width, inChannels]`.
* @param kernel Kernel, rank-3, of shape `[filterWidth, inDepth, outDepth]`.s
* @param strides
* @param padding Padding mode.
* @param dataFormat Data format.
* @param dilationRate
* @returns The result of the 1D convolution.
* @throws ValueError, if `x`, `kernel` or `bias` is not of the correct rank.
*/
function conv1d(x, kernel, strides = 1, padding = "valid", dataFormat, dilationRate = 1) {
return Object(dist["tidy"])(() => {
checkDataFormat(dataFormat);
return conv1dWithBias(x, kernel, null, strides, padding, dataFormat, dilationRate);
});
}
/**
* 2D Convolution
* @param x
* @param kernel kernel of the convolution.
* @param strides strides array.
* @param padding padding mode. Default to 'valid'.
* @param dataFormat data format. Defaults to 'channelsLast'.
* @param dilationRate dilation rate array.
* @returns Result of the 2D pooling.
*/
function conv2d(x, kernel, strides = [1, 1], padding = "valid", dataFormat, dilationRate) {
return Object(dist["tidy"])(() => {
checkDataFormat(dataFormat);
return conv2dWithBiasActivation(
x,
kernel,
null,
strides,
padding,
dataFormat,
dilationRate
);
});
}
/**
* 2D Convolution with an added bias and optional activation.
* Note: This function does not exist in the Python Keras Backend. This function
* is exactly the same as `conv2d`, except the added `bias`.
*/
function conv2dWithBiasActivation(
x,
kernel,
bias,
strides = [1, 1],
padding = "valid",
dataFormat,
dilationRate,
activation = null
) {
return Object(dist["tidy"])(() => {
if (dataFormat == null) {
dataFormat = imageDataFormat();
}
checkDataFormat(dataFormat);
if (x.rank !== 3 && x.rank !== 4) {
throw new ValueError(
`conv2dWithBiasActivation expects input to be of rank 3 or 4, ` +
`but received ${x.rank}.`
);
}
if (kernel.rank !== 3 && kernel.rank !== 4) {
throw new ValueError(
`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, ` +
`but received ${x.rank}.`
);
}
let y = preprocessConv2DInput(x, dataFormat);
if (padding === "causal") {
throw new NotImplementedError(
"The support for CAUSAL padding mode in conv1dWithBias is not " + "implemented yet."
);
}
y = dist["fused"].conv2d({
x: y,
filter: kernel,
strides: strides,
pad: padding === "same" ? "same" : "valid",
dilations: dilationRate,
dataFormat: "NHWC",
bias,
activation,
});
if (dataFormat === "channelsFirst") {
y = dist["transpose"](y, [0, 3, 1, 2]);
}
return y;
});
}
/**
* 3D Convolution.
* @param x
* @param kernel kernel of the convolution.
* @param strides strides array.
* @param padding padding mode. Default to 'valid'.
* @param dataFormat data format. Defaults to 'channelsLast'.
* @param dilationRate dilation rate array.
* @returns Result of the 3D convolution.
*/
function conv3d(x, kernel, strides = [1, 1, 1], padding = "valid", dataFormat, dilationRate) {
return Object(dist["tidy"])(() => {
checkDataFormat(dataFormat);
return conv3dWithBias(x, kernel, null, strides, padding, dataFormat, dilationRate);
});
}
/**
* 3D Convolution with an added bias.
* Note: This function does not exist in the Python Keras Backend. This function
* is exactly the same as `conv3d`, except the added `bias`.
*/
function conv3dWithBias(
x,
kernel,
bias,
strides = [1, 1, 1],
padding = "valid",
dataFormat,
dilationRate
) {
return Object(dist["tidy"])(() => {
if (dataFormat == null) {
dataFormat = imageDataFormat();
}
checkDataFormat(dataFormat);
if (x.rank !== 4 && x.rank !== 5) {
throw new ValueError(
`conv3dWithBias expects input to be of rank 4 or 5, but received ` + `${x.rank}.`
);
}
if (kernel.rank !== 4 && kernel.rank !== 5) {
throw new ValueError(
`conv3dWithBias expects kernel to be of rank 4 or 5, but received ` + `${x.rank}.`
);
}
let y = preprocessConv3DInput(x, dataFormat);
if (padding === "causal") {
throw new NotImplementedError(
"The support for CAUSAL padding mode in conv3dWithBias is not " + "implemented yet."
);
}
y = dist["conv3d"](
y,
kernel,
strides,
padding === "same" ? "same" : "valid",
"NDHWC",
dilationRate
);
if (bias != null) {
y = biasAdd(y, bias);
}
if (dataFormat === "channelsFirst") {
y = dist["transpose"](y, [0, 4, 1, 2, 3]);
}
return y;
});
}
/**
* Abstract convolution layer.
*/
class convolutional_BaseConv extends topology_Layer {
constructor(rank, args) {
super(args);
this.bias = null;
this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
this.DEFAULT_BIAS_INITIALIZER = "zeros";
convolutional_BaseConv.verifyArgs(args);
this.rank = rank;
assertPositiveInteger(this.rank, "rank");
if (this.rank !== 1 && this.rank !== 2 && this.rank !== 3) {
throw new NotImplementedError(
`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is ` +
`not implemented yet.`
);
}
this.kernelSize = normalizeArray(args.kernelSize, rank, "kernelSize");
this.strides = normalizeArray(args.strides == null ? 1 : args.strides, rank, "strides");
this.padding = args.padding == null ? "valid" : args.padding;
checkPaddingMode(this.padding);
this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
checkDataFormat(this.dataFormat);
this.activation = getActivation(args.activation);
this.useBias = args.useBias == null ? true : args.useBias;
this.biasInitializer = getInitializer(
args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER
);
this.biasConstraint = getConstraint(args.biasConstraint);
this.biasRegularizer = getRegularizer(args.biasRegularizer);
this.activityRegularizer = getRegularizer(args.activityRegularizer);
this.dilationRate = normalizeArray(
args.dilationRate == null ? 1 : args.dilationRate,
rank,
"dilationRate"
);
if (
this.rank === 1 &&
Array.isArray(this.dilationRate) &&
this.dilationRate.length !== 1
) {
throw new ValueError(
`dilationRate must be a number or an array of a single number ` +
`for 1D convolution, but received ` +
`${JSON.stringify(this.dilationRate)}`
);
} else if (this.rank === 2) {
if (typeof this.dilationRate === "number") {
this.dilationRate = [this.dilationRate, this.dilationRate];
} else if (this.dilationRate.length !== 2) {
throw new ValueError(
`dilationRate must be a number or array of two numbers for 2D ` +
`convolution, but received ${JSON.stringify(this.dilationRate)}`
);
}
} else if (this.rank === 3) {
if (typeof this.dilationRate === "number") {
this.dilationRate = [this.dilationRate, this.dilationRate, this.dilationRate];
} else if (this.dilationRate.length !== 3) {
throw new ValueError(
`dilationRate must be a number or array of three numbers for 3D ` +
`convolution, but received ${JSON.stringify(this.dilationRate)}`
);
}
}
}
static verifyArgs(args) {
// Check config.kernelSize type and shape.
assert("kernelSize" in args, `required key 'kernelSize' not in config`);
if (
typeof args.kernelSize !== "number" &&
!checkArrayTypeAndLength(args.kernelSize, "number", 1, 3)
) {
throw new ValueError(
`BaseConv expects config.kernelSize to be number or number[] with ` +
`length 1, 2, or 3, but received ${JSON.stringify(args.kernelSize)}.`
);
}
}
getConfig() {
const config = {
kernelSize: this.kernelSize,
strides: this.strides,
padding: this.padding,
dataFormat: this.dataFormat,
dilationRate: this.dilationRate,
activation: serializeActivation(this.activation),
useBias: this.useBias,
biasInitializer: serializeInitializer(this.biasInitializer),
biasRegularizer: serializeRegularizer(this.biasRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
biasConstraint: serializeConstraint(this.biasConstraint),
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/**
* Abstract nD convolution layer. Ancestor of convolution layers which reduce
* across channels, i.e., Conv1D and Conv2D, but not DepthwiseConv2D.
*/
class convolutional_Conv extends convolutional_BaseConv {
constructor(rank, args) {
super(rank, args);
this.kernel = null;
convolutional_Conv.verifyArgs(args);
this.filters = args.filters;
assertPositiveInteger(this.filters, "filters");
this.kernelInitializer = getInitializer(
args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER
);
this.kernelConstraint = getConstraint(args.kernelConstraint);
this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const channelAxis = this.dataFormat === "channelsFirst" ? 1 : inputShape.length - 1;
if (inputShape[channelAxis] == null) {
throw new ValueError(
`The channel dimension of the input should be defined. ` +
`Found ${inputShape[channelAxis]}`
);
}
const inputDim = inputShape[channelAxis];
const kernelShape = this.kernelSize.concat([inputDim, this.filters]);
this.kernel = this.addWeight(
"kernel",
kernelShape,
null,
this.kernelInitializer,
this.kernelRegularizer,
true,
this.kernelConstraint
);
if (this.useBias) {
this.bias = this.addWeight(
"bias",
[this.filters],
null,
this.biasInitializer,
this.biasRegularizer,
true,
this.biasConstraint
);
}
this.inputSpec = [{ ndim: this.rank + 2, axes: { [channelAxis]: inputDim } }];
this.built = true;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = getExactlyOneTensor(inputs);
let outputs;
const biasValue = this.bias == null ? null : this.bias.read();
const fusedActivationName = mapActivationToFusedKernel(this.activation.getClassName());
if (fusedActivationName != null && this.rank === 2) {
outputs = conv2dWithBiasActivation(
inputs,
this.kernel.read(),
biasValue,
this.strides,
this.padding,
this.dataFormat,
this.dilationRate,
fusedActivationName
);
} else {
if (this.rank === 1) {
outputs = conv1dWithBias(
inputs,
this.kernel.read(),
biasValue,
this.strides[0],
this.padding,
this.dataFormat,
this.dilationRate[0]
);
} else if (this.rank === 2) {
// TODO(cais): Move up to constructor.
outputs = conv2dWithBiasActivation(
inputs,
this.kernel.read(),
biasValue,
this.strides,
this.padding,
this.dataFormat,
this.dilationRate
);
} else if (this.rank === 3) {
outputs = conv3dWithBias(
inputs,
this.kernel.read(),
biasValue,
this.strides,
this.padding,
this.dataFormat,
this.dilationRate
);
} else {
throw new NotImplementedError(
"convolutions greater than 3D are not implemented yet."
);
}
if (this.activation != null) {
outputs = this.activation.apply(outputs);
}
}
return outputs;
});
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const newSpace = [];
const space =
this.dataFormat === "channelsLast"
? inputShape.slice(1, inputShape.length - 1)
: inputShape.slice(2);
for (let i = 0; i < space.length; ++i) {
const newDim = convOutputLength(
space[i],
this.kernelSize[i],
this.padding,
this.strides[i],
typeof this.dilationRate === "number" ? this.dilationRate : this.dilationRate[i]
);
newSpace.push(newDim);
}
let outputShape = [inputShape[0]];
if (this.dataFormat === "channelsLast") {
outputShape = outputShape.concat(newSpace);
outputShape.push(this.filters);
} else {
outputShape.push(this.filters);
outputShape = outputShape.concat(newSpace);
}
return outputShape;
}
getConfig() {
const config = {
filters: this.filters,
kernelInitializer: serializeInitializer(this.kernelInitializer),
kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
kernelConstraint: serializeConstraint(this.kernelConstraint),
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
static verifyArgs(args) {
// Check config.filters type, shape, and value.
if (!("filters" in args) || typeof args.filters !== "number" || args.filters < 1) {
throw new ValueError(
`Convolution layer expected config.filters to be a 'number' > 0 ` +
`but got ${JSON.stringify(args.filters)}`
);
}
}
}
class convolutional_Conv2D extends convolutional_Conv {
constructor(args) {
super(2, args);
convolutional_Conv2D.verifyArgs(args);
}
getConfig() {
const config = super.getConfig();
delete config["rank"];
return config;
}
static verifyArgs(args) {
// config.kernelSize must be a number or array of numbers.
if (
typeof args.kernelSize !== "number" &&
!checkArrayTypeAndLength(args.kernelSize, "number", 1, 2)
) {
throw new ValueError(
`Conv2D expects config.kernelSize to be number or number[] with ` +
`length 1 or 2, but received ${JSON.stringify(args.kernelSize)}.`
);
}
}
}
/** @nocollapse */
convolutional_Conv2D.className = "Conv2D";
dist["serialization"].registerClass(convolutional_Conv2D);
class convolutional_Conv3D extends convolutional_Conv {
constructor(args) {
super(3, args);
convolutional_Conv3D.verifyArgs(args);
}
getConfig() {
const config = super.getConfig();
delete config["rank"];
return config;
}
static verifyArgs(args) {
// config.kernelSize must be a number or array of numbers.
if (typeof args.kernelSize !== "number") {
if (
!(
Array.isArray(args.kernelSize) &&
(args.kernelSize.length === 1 || args.kernelSize.length === 3)
)
) {
throw new ValueError(
`Conv3D expects config.kernelSize to be number or` +
` [number, number, number], but received ${JSON.stringify(args.kernelSize)}.`
);
}
}
}
}
/** @nocollapse */
convolutional_Conv3D.className = "Conv3D";
dist["serialization"].registerClass(convolutional_Conv3D);
class convolutional_Conv2DTranspose extends convolutional_Conv2D {
constructor(args) {
super(args);
this.inputSpec = [new InputSpec({ ndim: 4 })];
if (this.padding !== "same" && this.padding !== "valid") {
throw new ValueError(
`Conv2DTranspose currently supports only padding modes 'same' ` +
`and 'valid', but received padding mode ${this.padding}`
);
}
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
if (inputShape.length !== 4) {
throw new ValueError(
"Input should have rank 4; Received input shape: " + JSON.stringify(inputShape)
);
}
const channelAxis = this.dataFormat === "channelsFirst" ? 1 : inputShape.length - 1;
if (inputShape[channelAxis] == null) {
throw new ValueError(
"The channel dimension of the inputs should be defined. " + "Found `None`."
);
}
const inputDim = inputShape[channelAxis];
const kernelShape = this.kernelSize.concat([this.filters, inputDim]);
this.kernel = this.addWeight(
"kernel",
kernelShape,
"float32",
this.kernelInitializer,
this.kernelRegularizer,
true,
this.kernelConstraint
);
if (this.useBias) {
this.bias = this.addWeight(
"bias",
[this.filters],
"float32",
this.biasInitializer,
this.biasRegularizer,
true,
this.biasConstraint
);
}
// Set input spec.
this.inputSpec = [new InputSpec({ ndim: 4, axes: { [channelAxis]: inputDim } })];
this.built = true;
}
call(inputs, kwargs) {
return dist["tidy"](() => {
let input = getExactlyOneTensor(inputs);
if (input.shape.length !== 4) {
throw new ValueError(
`Conv2DTranspose.call() expects input tensor to be rank-4, but ` +
`received a tensor of rank-${input.shape.length}`
);
}
const inputShape = input.shape;
const batchSize = inputShape[0];
let hAxis;
let wAxis;
if (this.dataFormat === "channelsFirst") {
hAxis = 2;
wAxis = 3;
} else {
hAxis = 1;
wAxis = 2;
}
const height = inputShape[hAxis];
const width = inputShape[wAxis];
const kernelH = this.kernelSize[0];
const kernelW = this.kernelSize[1];
const strideH = this.strides[0];
const strideW = this.strides[1];
// Infer the dynamic output shape.
const outHeight = deconvLength(height, strideH, kernelH, this.padding);
const outWidth = deconvLength(width, strideW, kernelW, this.padding);
// Porting Note: We don't branch based on `this.dataFormat` here,
// because
// the tjfs-core function `conv2dTranspose` called below always
// assumes channelsLast.
const outputShape = [batchSize, outHeight, outWidth, this.filters];
if (this.dataFormat !== "channelsLast") {
input = dist["transpose"](input, [0, 2, 3, 1]);
}
let outputs = dist["conv2dTranspose"](
input,
this.kernel.read(),
outputShape,
this.strides,
this.padding
);
if (this.dataFormat !== "channelsLast") {
outputs = dist["transpose"](outputs, [0, 3, 1, 2]);
}
if (this.bias != null) {
outputs = biasAdd(outputs, this.bias.read(), this.dataFormat);
}
if (this.activation != null) {
outputs = this.activation.apply(outputs);
}
return outputs;
});
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const outputShape = inputShape.slice();
let channelAxis;
let heightAxis;
let widthAxis;
if (this.dataFormat === "channelsFirst") {
channelAxis = 1;
heightAxis = 2;
widthAxis = 3;
} else {
channelAxis = 3;
heightAxis = 1;
widthAxis = 2;
}
const kernelH = this.kernelSize[0];
const kernelW = this.kernelSize[1];
const strideH = this.strides[0];
const strideW = this.strides[1];
outputShape[channelAxis] = this.filters;
outputShape[heightAxis] = deconvLength(
outputShape[heightAxis],
strideH,
kernelH,
this.padding
);
outputShape[widthAxis] = deconvLength(
outputShape[widthAxis],
strideW,
kernelW,
this.padding
);
return outputShape;
}
getConfig() {
const config = super.getConfig();
delete config["dilationRate"];
return config;
}
}
/** @nocollapse */
convolutional_Conv2DTranspose.className = "Conv2DTranspose";
dist["serialization"].registerClass(convolutional_Conv2DTranspose);
class convolutional_SeparableConv extends convolutional_Conv {
constructor(rank, config) {
super(rank, config);
this.DEFAULT_DEPTHWISE_INITIALIZER = "glorotUniform";
this.DEFAULT_POINTWISE_INITIALIZER = "glorotUniform";
this.depthwiseKernel = null;
this.pointwiseKernel = null;
if (config.filters == null) {
throw new ValueError(
"The `filters` configuration field is required by SeparableConv, " +
"but is unspecified."
);
}
if (
config.kernelInitializer != null ||
config.kernelRegularizer != null ||
config.kernelConstraint != null
) {
throw new ValueError(
"Fields kernelInitializer, kernelRegularizer and kernelConstraint " +
"are invalid for SeparableConv2D. Use depthwiseInitializer, " +
"depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, " +
"pointwiseRegularizer and pointwiseConstraint instead."
);
}
if (config.padding != null && config.padding !== "same" && config.padding !== "valid") {
throw new ValueError(
`SeparableConv${this.rank}D supports only padding modes: ` +
`'same' and 'valid', but received ${JSON.stringify(config.padding)}`
);
}
this.depthMultiplier = config.depthMultiplier == null ? 1 : config.depthMultiplier;
this.depthwiseInitializer = getInitializer(
config.depthwiseInitializer || this.DEFAULT_DEPTHWISE_INITIALIZER
);
this.depthwiseRegularizer = getRegularizer(config.depthwiseRegularizer);
this.depthwiseConstraint = getConstraint(config.depthwiseConstraint);
this.pointwiseInitializer = getInitializer(
config.depthwiseInitializer || this.DEFAULT_POINTWISE_INITIALIZER
);
this.pointwiseRegularizer = getRegularizer(config.pointwiseRegularizer);
this.pointwiseConstraint = getConstraint(config.pointwiseConstraint);
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
if (inputShape.length < this.rank + 2) {
throw new ValueError(
`Inputs to SeparableConv${this.rank}D should have rank ` +
`${this.rank + 2}, but received input shape: ` +
`${JSON.stringify(inputShape)}`
);
}
const channelAxis = this.dataFormat === "channelsFirst" ? 1 : inputShape.length - 1;
if (inputShape[channelAxis] == null || inputShape[channelAxis] < 0) {
throw new ValueError(
`The channel dimension of the inputs should be defined, ` +
`but found ${JSON.stringify(inputShape[channelAxis])}`
);
}
const inputDim = inputShape[channelAxis];
const depthwiseKernelShape = this.kernelSize.concat([inputDim, this.depthMultiplier]);
const pointwiseKernelShape = [];
for (let i = 0; i < this.rank; ++i) {
pointwiseKernelShape.push(1);
}
pointwiseKernelShape.push(inputDim * this.depthMultiplier, this.filters);
const trainable = true;
this.depthwiseKernel = this.addWeight(
"depthwise_kernel",
depthwiseKernelShape,
"float32",
this.depthwiseInitializer,
this.depthwiseRegularizer,
trainable,
this.depthwiseConstraint
);
this.pointwiseKernel = this.addWeight(
"pointwise_kernel",
pointwiseKernelShape,
"float32",
this.pointwiseInitializer,
this.pointwiseRegularizer,
trainable,
this.pointwiseConstraint
);
if (this.useBias) {
this.bias = this.addWeight(
"bias",
[this.filters],
"float32",
this.biasInitializer,
this.biasRegularizer,
trainable,
this.biasConstraint
);
} else {
this.bias = null;
}
this.inputSpec = [
new InputSpec({ ndim: this.rank + 2, axes: { [channelAxis]: inputDim } }),
];
this.built = true;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = getExactlyOneTensor(inputs);
let output;
if (this.rank === 1) {
throw new NotImplementedError("1D separable convolution is not implemented yet.");
} else if (this.rank === 2) {
if (this.dataFormat === "channelsFirst") {
inputs = dist["transpose"](inputs, [0, 2, 3, 1]); // NCHW -> NHWC.
}
output = dist["separableConv2d"](
inputs,
this.depthwiseKernel.read(),
this.pointwiseKernel.read(),
this.strides,
this.padding,
this.dilationRate,
"NHWC"
);
}
if (this.useBias) {
output = biasAdd(output, this.bias.read(), this.dataFormat);
}
if (this.activation != null) {
output = this.activation.apply(output);
}
if (this.dataFormat === "channelsFirst") {
output = dist["transpose"](output, [0, 3, 1, 2]); // NHWC -> NCHW.
}
return output;
});
}
getConfig() {
const config = super.getConfig();
delete config["rank"];
delete config["kernelInitializer"];
delete config["kernelRegularizer"];
delete config["kernelConstraint"];
config["depthwiseInitializer"] = serializeInitializer(this.depthwiseInitializer);
config["pointwiseInitializer"] = serializeInitializer(this.pointwiseInitializer);
config["depthwiseRegularizer"] = serializeRegularizer(this.depthwiseRegularizer);
config["pointwiseRegularizer"] = serializeRegularizer(this.pointwiseRegularizer);
config["depthwiseConstraint"] = serializeConstraint(this.depthwiseConstraint);
config["pointwiseConstraint"] = serializeConstraint(this.pointwiseConstraint);
return config;
}
}
/** @nocollapse */
convolutional_SeparableConv.className = "SeparableConv";
class SeparableConv2D extends convolutional_SeparableConv {
constructor(args) {
super(2, args);
}
}
/** @nocollapse */
SeparableConv2D.className = "SeparableConv2D";
dist["serialization"].registerClass(SeparableConv2D);
class convolutional_Conv1D extends convolutional_Conv {
constructor(args) {
super(1, args);
convolutional_Conv1D.verifyArgs(args);
this.inputSpec = [{ ndim: 3 }];
}
getConfig() {
const config = super.getConfig();
delete config["rank"];
delete config["dataFormat"];
return config;
}
static verifyArgs(args) {
// config.kernelSize must be a number or array of numbers.
if (
typeof args.kernelSize !== "number" &&
!checkArrayTypeAndLength(args.kernelSize, "number", 1, 1)
) {
throw new ValueError(
`Conv1D expects config.kernelSize to be number or number[] with ` +
`length 1, but received ${JSON.stringify(args.kernelSize)}.`
);
}
}
}
/** @nocollapse */
convolutional_Conv1D.className = "Conv1D";
dist["serialization"].registerClass(convolutional_Conv1D);
class convolutional_Cropping2D extends topology_Layer {
constructor(args) {
super(args);
if (typeof args.cropping === "number") {
this.cropping = [
[args.cropping, args.cropping],
[args.cropping, args.cropping],
];
} else if (typeof args.cropping[0] === "number") {
this.cropping = [
[args.cropping[0], args.cropping[0]],
[args.cropping[1], args.cropping[1]],
];
} else {
this.cropping = args.cropping;
}
this.dataFormat = args.dataFormat === undefined ? "channelsLast" : args.dataFormat;
this.inputSpec = [{ ndim: 4 }];
}
computeOutputShape(inputShape) {
if (this.dataFormat === "channelsFirst") {
return [
inputShape[0],
inputShape[1],
inputShape[2] - this.cropping[0][0] - this.cropping[0][1],
inputShape[3] - this.cropping[1][0] - this.cropping[1][1],
];
} else {
return [
inputShape[0],
inputShape[1] - this.cropping[0][0] - this.cropping[0][1],
inputShape[2] - this.cropping[1][0] - this.cropping[1][1],
inputShape[3],
];
}
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = getExactlyOneTensor(inputs);
if (this.dataFormat === "channelsLast") {
const hSliced = sliceAlongAxis(
inputs,
this.cropping[0][0],
inputs.shape[1] - this.cropping[0][0] - this.cropping[0][1],
2
);
return sliceAlongAxis(
hSliced,
this.cropping[1][0],
inputs.shape[2] - this.cropping[1][1] - this.cropping[1][0],
3
);
} else {
const hSliced = sliceAlongAxis(
inputs,
this.cropping[0][0],
inputs.shape[2] - this.cropping[0][0] - this.cropping[0][1],
3
);
return sliceAlongAxis(
hSliced,
this.cropping[1][0],
inputs.shape[3] - this.cropping[1][1] - this.cropping[1][0],
4
);
}
});
}
getConfig() {
const config = { cropping: this.cropping, dataFormat: this.dataFormat };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
convolutional_Cropping2D.className = "Cropping2D";
dist["serialization"].registerClass(convolutional_Cropping2D);
class convolutional_UpSampling2D extends topology_Layer {
constructor(args) {
super(args);
this.DEFAULT_SIZE = [2, 2];
this.inputSpec = [{ ndim: 4 }];
this.size = args.size == null ? this.DEFAULT_SIZE : args.size;
this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
}
computeOutputShape(inputShape) {
if (this.dataFormat === "channelsFirst") {
const height = inputShape[2] == null ? null : this.size[0] * inputShape[2];
const width = inputShape[3] == null ? null : this.size[1] * inputShape[3];
return [inputShape[0], inputShape[1], height, width];
} else {
const height = inputShape[1] == null ? null : this.size[0] * inputShape[1];
const width = inputShape[2] == null ? null : this.size[1] * inputShape[2];
return [inputShape[0], height, width, inputShape[3]];
}
}
call(inputs, kwargs) {
return dist["tidy"](() => {
let input = getExactlyOneTensor(inputs);
const inputShape = input.shape;
if (this.dataFormat === "channelsFirst") {
input = dist["transpose"](input, [0, 2, 3, 1]);
const height = this.size[0] * inputShape[2];
const width = this.size[1] * inputShape[3];
const resized = input.resizeNearestNeighbor([height, width]);
return dist["transpose"](resized, [0, 3, 1, 2]);
} else {
const height = this.size[0] * inputShape[1];
const width = this.size[1] * inputShape[2];
return input.resizeNearestNeighbor([height, width]);
}
});
}
getConfig() {
const config = { size: this.size, dataFormat: this.dataFormat };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
convolutional_UpSampling2D.className = "UpSampling2D";
dist["serialization"].registerClass(convolutional_UpSampling2D);
//# sourceMappingURL=convolutional.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/convolutional_depthwise.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Depthwise Convolutional Layers
*/
/**
* 2D convolution with separable filters.
* @param x Input tensor.
* @param depthwiseKernel Convolution kernel for depthwise convolution.
* @param strides Strides (Array of two integers).
* @param padding Padding model.
* @param dataFormat Data format.
* @param dilationRate Array of two integers, dilation rates for the separable
* convolution.
* @returns Output tensor.
* @throws ValueError If depthwiseKernel is not a 4D array.
*/
function depthwiseConv2d(
x,
depthwiseKernel,
strides = [1, 1],
padding = "valid",
dataFormat,
dilationRate
) {
return Object(dist["tidy"])(() => {
if (dataFormat == null) {
dataFormat = imageDataFormat();
}
checkDataFormat(dataFormat);
let y = preprocessConv2DInput(x, dataFormat);
if (x.rank !== 4) {
throw new ValueError(
`Input for depthwiseConv2d is required to be 4-D, but is instead ` + `${x.rank}-D`
);
}
if (depthwiseKernel.rank !== 4) {
throw new ValueError(
`depthwiseKernel is required to be 4-D, but is instead ` + `${depthwiseKernel.rank}-D`
);
}
y = dist["depthwiseConv2d"](
y,
depthwiseKernel,
strides,
padding === "same" ? "same" : "valid",
"NHWC",
dilationRate
);
if (dataFormat === "channelsFirst") {
y = dist["transpose"](y, [0, 3, 1, 2]);
}
return y;
});
}
class convolutional_depthwise_DepthwiseConv2D extends convolutional_BaseConv {
constructor(args) {
super(2, args);
this.depthwiseKernel = null;
this.depthMultiplier = args.depthMultiplier == null ? 1 : args.depthMultiplier;
this.depthwiseInitializer = getInitializer(
args.depthwiseInitializer || this.DEFAULT_KERNEL_INITIALIZER
);
this.depthwiseConstraint = getConstraint(args.depthwiseConstraint);
this.depthwiseRegularizer = getRegularizer(args.depthwiseRegularizer);
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
if (inputShape.length < 4) {
throw new ValueError(
`Inputs to DepthwiseConv2D should have rank 4. ` +
`Received input shape: ${JSON.stringify(inputShape)}.`
);
}
const channelAxis = this.dataFormat === "channelsFirst" ? 1 : 3;
if (inputShape[channelAxis] == null || inputShape[channelAxis] < 0) {
throw new ValueError(
"The channel dimension of the inputs to DepthwiseConv2D should " +
`be defined, but is not (${inputShape[channelAxis]}).`
);
}
const inputDim = inputShape[channelAxis];
const depthwiseKernelShape = [
this.kernelSize[0],
this.kernelSize[1],
inputDim,
this.depthMultiplier,
];
this.depthwiseKernel = this.addWeight(
"depthwise_kernel",
depthwiseKernelShape,
null,
this.depthwiseInitializer,
this.depthwiseRegularizer,
true,
this.depthwiseConstraint
);
if (this.useBias) {
this.bias = this.addWeight(
"bias",
[inputDim * this.depthMultiplier],
null,
this.biasInitializer,
this.biasRegularizer,
true,
this.biasConstraint
);
} else {
this.bias = null;
}
this.built = true;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = getExactlyOneTensor(inputs);
let outputs = depthwiseConv2d(
inputs,
this.depthwiseKernel.read(),
this.strides,
this.padding,
this.dataFormat,
null
);
// TODO(cais): Add support for dilation.
if (this.useBias) {
outputs = biasAdd(outputs, this.bias.read(), this.dataFormat);
}
if (this.activation != null) {
outputs = this.activation.apply(outputs);
}
return outputs;
});
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const rows = this.dataFormat === "channelsFirst" ? inputShape[2] : inputShape[1];
const cols = this.dataFormat === "channelsFirst" ? inputShape[3] : inputShape[2];
const outFilters =
this.dataFormat === "channelsFirst"
? inputShape[1] * this.depthMultiplier
: inputShape[3] * this.depthMultiplier;
const outRows = convOutputLength(rows, this.kernelSize[0], this.padding, this.strides[0]);
const outCols = convOutputLength(cols, this.kernelSize[1], this.padding, this.strides[1]);
if (this.dataFormat === "channelsFirst") {
return [inputShape[0], outFilters, outRows, outCols];
} else {
// In this case, assume 'channelsLast'.
return [inputShape[0], outRows, outCols, outFilters];
}
}
getConfig() {
const config = super.getConfig();
config["depthMultiplier"] = this.depthMultiplier;
config["depthwiseInitializer"] = serializeInitializer(this.depthwiseInitializer);
config["depthwiseRegularizer"] = serializeRegularizer(this.depthwiseRegularizer);
config["depthwiseConstraint"] = serializeConstraint(this.depthwiseRegularizer);
return config;
}
}
/** @nocollapse */
convolutional_depthwise_DepthwiseConv2D.className = "DepthwiseConv2D";
dist["serialization"].registerClass(convolutional_depthwise_DepthwiseConv2D);
//# sourceMappingURL=convolutional_depthwise.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/core.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Basic Layers.
*/
class core_Dropout extends topology_Layer {
constructor(args) {
super(args);
this.rate = Math.max(Math.min(args.rate, 1), 0);
// So that the scalar doesn't get tidied up between executions.
this.noiseShape = args.noiseShape;
this.seed = args.seed;
this.supportsMasking = true;
}
getNoiseShape(input) {
if (this.noiseShape == null) {
return this.noiseShape;
}
const inputShape = input.shape;
const noiseShape = [];
for (let i = 0; i < this.noiseShape.length; ++i) {
noiseShape.push(this.noiseShape[i] == null ? inputShape[i] : this.noiseShape[i]);
}
return noiseShape;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
const input = getExactlyOneTensor(inputs);
if (0 < this.rate && this.rate < 1) {
const training = kwargs["training"] == null ? false : kwargs["training"];
const noiseShape = this.getNoiseShape(input);
const output = inTrainPhase(
() => dropout(input, this.rate, noiseShape, this.seed),
() => input,
training
);
return output;
}
return inputs;
});
}
getConfig() {
const config = {
rate: this.rate,
noiseShape: this.noiseShape,
seed: this.seed,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
dispose() {
return super.dispose();
}
}
/** @nocollapse */
core_Dropout.className = "Dropout";
dist["serialization"].registerClass(core_Dropout);
class SpatialDropout1D extends core_Dropout {
constructor(args) {
super(args);
this.inputSpec = [{ ndim: 3 }];
}
getNoiseShape(input) {
const inputShape = input.shape;
return [inputShape[0], 1, inputShape[2]];
}
}
/** @nocollapse */
SpatialDropout1D.className = "SpatialDropout1D";
dist["serialization"].registerClass(SpatialDropout1D);
class core_Dense extends topology_Layer {
constructor(args) {
super(args);
// Default activation: Linear (none).
this.activation = null;
this.useBias = true;
this.kernel = null;
this.bias = null;
this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
this.DEFAULT_BIAS_INITIALIZER = "zeros";
if (args.batchInputShape == null && args.inputShape == null && args.inputDim != null) {
// This logic is copied from Layer's constructor, since we can't
// do exactly what the Python constructor does for Dense().
let batchSize = null;
if (args.batchSize != null) {
batchSize = args.batchSize;
}
this.batchInputShape = [batchSize, args.inputDim];
}
this.units = args.units;
assertPositiveInteger(this.units, "units");
this.activation = getActivation(args.activation);
if (args.useBias != null) {
this.useBias = args.useBias;
}
this.kernelInitializer = getInitializer(
args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER
);
this.biasInitializer = getInitializer(
args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER
);
this.kernelConstraint = getConstraint(args.kernelConstraint);
this.biasConstraint = getConstraint(args.biasConstraint);
this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
this.biasRegularizer = getRegularizer(args.biasRegularizer);
this.activityRegularizer = getRegularizer(args.activityRegularizer);
this.supportsMasking = true;
this.inputSpec = [{ minNDim: 2 }];
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const inputLastDim = inputShape[inputShape.length - 1];
if (this.kernel == null) {
this.kernel = this.addWeight(
"kernel",
[inputLastDim, this.units],
null,
this.kernelInitializer,
this.kernelRegularizer,
true,
this.kernelConstraint
);
if (this.useBias) {
this.bias = this.addWeight(
"bias",
[this.units],
null,
this.biasInitializer,
this.biasRegularizer,
true,
this.biasConstraint
);
}
}
this.inputSpec = [{ minNDim: 2, axes: { [-1]: inputLastDim } }];
this.built = true;
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const outputShape = inputShape.slice();
outputShape[outputShape.length - 1] = this.units;
return outputShape;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
// Dense layer accepts only a single input.
const input = getExactlyOneTensor(inputs);
const fusedActivationName = mapActivationToFusedKernel(this.activation.getClassName());
let output;
if (fusedActivationName != null) {
output = dot(
input,
this.kernel.read(),
fusedActivationName,
this.bias ? this.bias.read() : null
);
} else {
output = dot(input, this.kernel.read());
if (this.bias != null) {
output = biasAdd(output, this.bias.read());
}
if (this.activation != null) {
output = this.activation.apply(output);
}
}
return output;
});
}
getConfig() {
const config = {
units: this.units,
activation: serializeActivation(this.activation),
useBias: this.useBias,
kernelInitializer: serializeInitializer(this.kernelInitializer),
biasInitializer: serializeInitializer(this.biasInitializer),
kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
biasRegularizer: serializeRegularizer(this.biasRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
kernelConstraint: serializeConstraint(this.kernelConstraint),
biasConstraint: serializeConstraint(this.biasConstraint),
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
core_Dense.className = "Dense";
dist["serialization"].registerClass(core_Dense);
class core_Flatten extends topology_Layer {
constructor(args) {
args = args || {};
super(args);
this.inputSpec = [{ minNDim: 3 }];
this.dataFormat = args.dataFormat;
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
for (const dim of inputShape.slice(1)) {
if (dim == null) {
throw new ValueError(
`The shape of the input to "Flatten" is not fully defined ` +
`(got ${inputShape.slice(1)}). Make sure to pass a complete ` +
`"input_shape" or "batch_input_shape" argument to the first ` +
`layer in your model.`
);
}
}
return [inputShape[0], arrayProd(inputShape, 1)];
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
let input = getExactlyOneTensor(inputs);
if (this.dataFormat === "channelsFirst" && input.rank > 1) {
const permutation = [0];
for (let i = 2; i < input.rank; ++i) {
permutation.push(i);
}
permutation.push(1);
input = input.transpose(permutation);
}
return batchFlatten(input);
});
}
getConfig() {
const config = {};
if (this.dataFormat != null) {
config["dataFormat"] = this.dataFormat;
}
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
core_Flatten.className = "Flatten";
dist["serialization"].registerClass(core_Flatten);
class core_Activation extends topology_Layer {
constructor(args) {
super(args);
this.supportsMasking = true;
this.activation = getActivation(args.activation);
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
const input = getExactlyOneTensor(inputs);
return this.activation.apply(input);
});
}
getConfig() {
const config = { activation: serializeActivation(this.activation) };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
core_Activation.className = "Activation";
dist["serialization"].registerClass(core_Activation);
class core_RepeatVector extends topology_Layer {
constructor(args) {
super(args);
this.n = args.n;
this.inputSpec = [{ ndim: 2 }];
}
computeOutputShape(inputShape) {
return [inputShape[0], this.n, inputShape[1]];
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = getExactlyOneTensor(inputs);
return repeat(inputs, this.n);
});
}
getConfig() {
const config = {
n: this.n,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
core_RepeatVector.className = "RepeatVector";
dist["serialization"].registerClass(core_RepeatVector);
class core_Reshape extends topology_Layer {
constructor(args) {
super(args);
this.targetShape = args.targetShape;
// Make sure that all unknown dimensions are represented as `null`.
for (let i = 0; i < this.targetShape.length; ++i) {
if (this.isUnknown(this.targetShape[i])) {
this.targetShape[i] = null;
}
}
}
isUnknown(dim) {
return dim < 0 || dim == null;
}
/**
* Finds and replaces a missing dimension in output shape.
*
* This is a near direct port of the internal Numpy function
* `_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c`.
*
* @param inputShape: Original shape of array begin reshape.
* @param outputShape: Target shape of the array, with at most a single
* `null` or negative number, which indicates an underdetermined dimension
* that should be derived from `inputShape` and the known dimensions of
* `outputShape`.
* @returns: The output shape with `null` replaced with its computed value.
* @throws: ValueError: If `inputShape` and `outputShape` do not match.
*/
fixUnknownDimension(inputShape, outputShape) {
const errorMsg = "Total size of new array must be unchanged.";
const finalShape = outputShape.slice();
let known = 1;
let unknown = null;
for (let i = 0; i < finalShape.length; ++i) {
const dim = finalShape[i];
if (this.isUnknown(dim)) {
if (unknown === null) {
unknown = i;
} else {
throw new ValueError("Can only specifiy one unknown dimension.");
}
} else {
known *= dim;
}
}
const originalSize = arrayProd(inputShape);
if (unknown !== null) {
if (known === 0 || originalSize % known !== 0) {
throw new ValueError(errorMsg);
}
finalShape[unknown] = originalSize / known;
} else if (originalSize !== known) {
throw new ValueError(errorMsg);
}
return finalShape;
}
computeOutputShape(inputShape) {
let anyUnknownDims = false;
for (let i = 0; i < inputShape.length; ++i) {
if (this.isUnknown(inputShape[i])) {
anyUnknownDims = true;
break;
}
}
if (anyUnknownDims) {
return inputShape.slice(0, 1).concat(this.targetShape);
} else {
return inputShape
.slice(0, 1)
.concat(this.fixUnknownDimension(inputShape.slice(1), this.targetShape));
}
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
const input = getExactlyOneTensor(inputs);
const inputShape = input.shape;
const outputShape = inputShape
.slice(0, 1)
.concat(this.fixUnknownDimension(inputShape.slice(1), this.targetShape));
return input.reshape(outputShape);
});
}
getConfig() {
const config = {
targetShape: this.targetShape,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
core_Reshape.className = "Reshape";
dist["serialization"].registerClass(core_Reshape);
class core_Permute extends topology_Layer {
constructor(args) {
super(args);
if (args.dims == null) {
throw new Error(
"Required configuration field `dims` is missing during Permute " + "constructor call."
);
}
if (!Array.isArray(args.dims)) {
throw new Error(
"Permute constructor requires `dims` to be an Array, but received " +
`${args.dims} instead.`
);
}
// Check the validity of the permutation indices.
const expectedSortedIndices = range(1, args.dims.length + 1);
if (!dist["util"].arraysEqual(args.dims.slice().sort(), expectedSortedIndices)) {
throw new Error(
"Invalid permutation `dims`: " +
JSON.stringify(args.dims) +
" `dims` must contain consecutive integers starting from 1."
);
}
this.dims = args.dims;
this.dimsIncludingBatch = [0].concat(this.dims);
this.inputSpec = [new InputSpec({ ndim: this.dims.length + 1 })];
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const outputShape = inputShape.slice();
this.dims.forEach((dim, i) => {
outputShape[i + 1] = inputShape[dim];
});
return outputShape;
}
call(inputs, kwargs) {
return Object(dist["transpose"])(getExactlyOneTensor(inputs), this.dimsIncludingBatch);
}
getConfig() {
const config = {
dims: this.dims,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
core_Permute.className = "Permute";
dist["serialization"].registerClass(core_Permute);
class core_Masking extends topology_Layer {
constructor(args) {
super(args == null ? {} : args);
this.supportsMasking = true;
if (args != null) {
this.maskValue = args.maskValue == null ? 0 : args.maskValue;
} else {
this.maskValue = 0;
}
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const baseConfig = super.getConfig();
const config = { maskValue: this.maskValue };
Object.assign(config, baseConfig);
return config;
}
computeMask(inputs, mask) {
const input = getExactlyOneTensor(inputs);
const axis = -1;
return Object(dist["any"])(Object(dist["notEqual"])(input, this.maskValue), axis);
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
const input = getExactlyOneTensor(inputs);
const axis = -1;
const keepDims = true;
const booleanMask = Object(dist["any"])(
Object(dist["notEqual"])(input, this.maskValue),
axis,
keepDims
);
const output = input.mul(booleanMask.asType(input.dtype));
return output;
});
}
}
/** @nocollapse */
core_Masking.className = "Masking";
dist["serialization"].registerClass(core_Masking);
//# sourceMappingURL=core.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/embeddings.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Embedding Layer.
*
* Original source: keras/constraints.py
*/
class embeddings_Embedding extends topology_Layer {
constructor(args) {
super(args);
this.embeddings = null;
this.DEFAULT_EMBEDDINGS_INITIALIZER = "randomUniform";
if (args.batchInputShape == null && args.inputShape == null) {
// Porting Note: This logic is copied from Layer's constructor, since we
// can't do exactly what the Python constructor does for Embedding().
// Specifically, the super constructor can not be called after the
// mutation of the `config` argument.
let batchSize = null;
if (args.batchSize != null) {
batchSize = args.batchSize;
}
if (args.inputLength == null) {
// Fix super-constructor to what it would have done if
// 'config.inputShape' were (None, )
this.batchInputShape = [batchSize, null];
} else {
// Fix super-constructor to what it would have done if
// 'config.inputShape' were (config.inputLength, )
this.batchInputShape = [batchSize].concat(toList(args.inputLength));
}
}
this.inputDim = args.inputDim;
assertPositiveInteger(this.inputDim, "inputDim");
this.outputDim = args.outputDim;
assertPositiveInteger(this.outputDim, "outputDim");
this.embeddingsInitializer = getInitializer(
args.embeddingsInitializer || this.DEFAULT_EMBEDDINGS_INITIALIZER
);
this.embeddingsRegularizer = getRegularizer(args.embeddingsRegularizer);
this.activityRegularizer = getRegularizer(args.activityRegularizer);
this.embeddingsConstraint = getConstraint(args.embeddingsConstraint);
this.maskZero = args.maskZero;
this.supportsMasking = args.maskZero;
this.inputLength = args.inputLength;
}
build(inputShape) {
this.embeddings = this.addWeight(
"embeddings",
[this.inputDim, this.outputDim],
this.dtype,
this.embeddingsInitializer,
this.embeddingsRegularizer,
true,
this.embeddingsConstraint
);
this.built = true;
}
// Override warnOnIncompatibleInputShape because an embedding layer allows
// the input to have varying ranks.
warnOnIncompatibleInputShape(inputShape) {}
computeMask(inputs, mask) {
return Object(dist["tidy"])(() => {
if (!this.maskZero) {
return null;
} else {
inputs = getExactlyOneTensor(inputs);
return Object(dist["notEqual"])(inputs, Object(dist["zerosLike"])(inputs));
}
});
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
if (this.inputLength == null) {
return [...inputShape, this.outputDim];
}
// inputLength can be an array if input is 3D or higher.
const inLens = toList(this.inputLength);
if (inLens.length !== inputShape.length - 1) {
throw new ValueError(
`"inputLength" is ${this.inputLength}, but received ` +
`input shape has shape ${inputShape}`
);
} else {
let i = 0;
for (let k = 0; k < inLens.length; ++k) {
const s1 = inLens[k];
const s2 = inputShape[k + 1];
if (s1 != null && s2 != null && s1 !== s2) {
throw new ValueError(
`"inputLength" is ${this.inputLength}, but received ` +
`input shape has shape ${inputShape}`
);
} else if (s1 == null) {
inLens[i] = s2;
}
i++;
}
}
return [inputShape[0], ...inLens, this.outputDim];
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
// Embedding layer accepts only a single input.
let input = getExactlyOneTensor(inputs);
if (input.dtype !== "int32") {
input = cast(input, "int32");
}
const output = gather(this.embeddings.read(), input.as1D());
return output.reshape(getExactlyOneShape(this.computeOutputShape(input.shape)));
});
}
getConfig() {
const config = {
inputDim: this.inputDim,
outputDim: this.outputDim,
embeddingsInitializer: serializeInitializer(this.embeddingsInitializer),
embeddingsRegularizer: serializeRegularizer(this.embeddingsRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
embeddingsConstraint: serializeConstraint(this.embeddingsConstraint),
maskZero: this.maskZero,
inputLength: this.inputLength,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
embeddings_Embedding.className = "Embedding";
dist["serialization"].registerClass(embeddings_Embedding);
//# sourceMappingURL=embeddings.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/merge.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Merge Layers.
*/
/**
* Generic Merge layer for element-wise merge functions.
*
* Used to implement `Sum`, `Average`, `Concatenate`, etc.
*/
class merge_Merge extends topology_Layer {
constructor(args) {
super(args || {});
this.supportsMasking = true;
}
/**
* Logic for merging multiple tensors, to be overridden by subclasses.
* @param inputs
*/
mergeFunction(inputs) {
throw new NotImplementedError();
}
/**
* Computes the shape of the result of an elementwise operation.
*
* @param shape1: Shape of the first tensor.
* @param shape2: Shape of the second tensor.
* @returns Expected output shape when an elementwise operation is carried
* out on 2 tensors with shapes `shape1` and `shape2`.
* @throws ValueError: If `shape1` and `shape2` are not compatible for
* element-wise operations.
*/
computeElementwiseOpOutputShape(shape1, shape2) {
if (shape1 == null || shape2 == null) {
return null;
} else if (shape1.length < shape2.length) {
return this.computeElementwiseOpOutputShape(shape2, shape1);
} else if (shape2.length === 0) {
return shape1;
}
const outputShape = shape1.slice(0, shape1.length - shape2.length);
for (let k = 0; k < shape2.length; ++k) {
const i = shape1[shape1.length - shape2.length + k];
const j = shape2[k];
if (i == null || j == null || i < 0 || j < 0) {
outputShape.push(null);
} else if (i === 1) {
outputShape.push(j);
} else if (j === 1) {
outputShape.push(i);
} else {
if (i !== j) {
throw new ValueError(
"Operands could not be broadcast together with shapes " +
JSON.stringify(shape1) +
" " +
JSON.stringify(shape2)
);
}
outputShape.push(i);
}
}
return outputShape;
}
build(inputShape) {
// Used purely for shape validation.
if (Array.isArray(inputShape) && !Array.isArray(inputShape[0])) {
// Make sure that inputShape is an Array of shape.
inputShape = [getExactlyOneShape(inputShape)];
}
inputShape = inputShape;
if (inputShape.length < 2) {
throw new ValueError(
"A merge layer should be called on an Array of at least 2 inputs." +
` Got ${inputShape.length} input(s).`
);
}
// Make sure that there is at most one unique batch size among the input
// shapes.
let batchSizes = [];
for (const shape of inputShape) {
if (shape != null && shape[0] !== null) {
batchSizes.push(shape[0]);
}
}
batchSizes = unique(batchSizes);
if (batchSizes.length > 1) {
throw new ValueError(
`Can not merge tensors with different batch sizes. ` +
`Got tensors with shapes: ${JSON.stringify(inputShape)}.`
);
}
let outputShape = inputShape[0] == null ? null : inputShape[0].slice(1);
for (let i = 1; i < inputShape.length; ++i) {
const shape = inputShape[i] == null ? null : inputShape[i].slice(1);
outputShape = this.computeElementwiseOpOutputShape(outputShape, shape);
}
// If the inputs have different ranks, we have to reshape them to make them
// broadcastable.
const allRanks = inputShape.map((shape) => shape.length);
if (inputShape.indexOf(null) === -1 && unique(allRanks).length === 1) {
this.reshapeRequired = false;
} else {
this.reshapeRequired = true;
}
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = inputs;
if (this.reshapeRequired) {
const reshapedInputs = [];
const inputDims = inputs.map((input) => input.rank);
if (inputDims.indexOf(null) === -1) {
// If ranks of all inputs are available, we simply expand each of them
// at axis=1 until all of them have the same rank.
const maxNDim = max(inputDims);
for (let x of inputs) {
const xNDim = x.rank;
for (let k = 0; k < maxNDim - xNDim; ++k) {
x = expandDims(x, 1);
}
reshapedInputs.push(x);
}
return this.mergeFunction(reshapedInputs);
} else {
// Transpose all inputs so that batch size is the last dimension.
// [batchSize, dim1, dim2, ...] -> [dim1, dim2, ..., batchSize]
let transposed = false;
for (const x of inputs) {
const xNDim = x.rank;
if (xNDim == null) {
const xShape = x.shape;
const batchSize = xShape[0];
const newShape = xShape.slice(1).concat([batchSize]);
let xTransposed = x.reshape([batchSize].concat(arrayProd(xShape.slice(1))));
xTransposed = dist["transpose"](xTransposed, [1, 0]);
xTransposed = xTransposed.reshape(newShape);
reshapedInputs.push(xTransposed);
transposed = true;
} else if (xNDim > 1) {
const dims = range(1, xNDim).concat([0]);
reshapedInputs.push(dist["transpose"](x, dims));
transposed = true;
} else {
// We don't transpose inputs if they are 1D vectors or scalars.
reshapedInputs.push(x);
}
}
let y = this.mergeFunction(reshapedInputs);
const yNDim = y.rank;
if (transposed) {
// If inputs have been transposed, we have to transpose the output
// too.
if (yNDim == null) {
const yShape = y.shape;
const yNDim = yShape.length;
const batchSize = yShape[yNDim - 1];
const newShape = [batchSize].concat(yShape.slice(0, yShape.length - 1));
y = dist["transpose"](y.reshape([-1, batchSize]), [1, 0]).reshape(newShape);
} else if (yNDim > 1) {
const dims = [yNDim - 1].concat(range(0, yNDim - 1));
y = dist["transpose"](y, dims);
}
}
return y;
}
} else {
return this.mergeFunction(inputs);
}
});
}
computeOutputShape(inputShape) {
inputShape = inputShape;
let outputShape;
if (inputShape[0] == null) {
outputShape = null;
} else {
outputShape = inputShape[0].slice(1);
}
for (let i = 1; i < inputShape.length; ++i) {
const shape = inputShape[i] == null ? null : inputShape[i].slice(1);
outputShape = this.computeElementwiseOpOutputShape(outputShape, shape);
}
let batchSizes = [];
for (const shape of inputShape) {
if (shape != null && shape[0] !== null) {
batchSizes.push(shape[0]);
}
}
batchSizes = unique(batchSizes);
if (batchSizes.length === 1) {
outputShape = batchSizes.concat(outputShape);
} else {
outputShape = [null].concat(outputShape);
}
return outputShape;
}
computeMask(inputs, mask) {
return dist["tidy"](() => {
if (mask == null) {
return null;
}
if (!Array.isArray(mask)) {
throw new ValueError("`mask` should be an Array");
}
if (!Array.isArray(inputs)) {
throw new ValueError("`inputs` should be an Array");
}
if (mask.length !== inputs.length) {
throw new ValueError(
`The Array 'inputs' and 'mask' are expected to have the same ` +
`length, but have different lengths ` +
`(${inputs.length} vs ${mask.length})`
);
}
if (mask.every((m) => m == null)) {
return null;
}
mask = mask.map((m) => (m == null ? m : dist["expandDims"](m, 0)));
let output = mask[0];
for (let i = 1; i < mask.length - 1; ++i) {
output = dist["logicalAnd"](output, mask[i]);
}
return output;
});
}
}
class merge_Add extends merge_Merge {
constructor(args) {
super(args);
}
mergeFunction(inputs) {
return Object(dist["tidy"])(() => {
let output = inputs[0].clone();
for (let i = 1; i < inputs.length; ++i) {
output = dist["add"](output, inputs[i]);
}
return output;
});
}
}
/** @nocollapse */
merge_Add.className = "Add";
dist["serialization"].registerClass(merge_Add);
/**
* Calculate the element-wise sum of inputs, which all have the same shape.
*
* This function can be invoked in three ways.
*
* 1. Construct an instance of `Add` layer, by using no input argument
* or a single configuration argument. The resultant `Add` layer can then
* be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:
*
* ```js
* const addLayer = tf.layers.add();
*
* // The layer can be applied to inputs.
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = addLayer.apply([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.SymbolicTensor`. For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = tf.layers.add([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.Tensor` as the result of the computation. For
* example:
*
* ```js
* const input1 = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const input2 = tf.tensor2d([10, 20, 30, 40], [2, 2]);
* tf.layers.add([input1, input2]).print();
* // Gives [[11, 22], [33, 44]].
*
*/
function add(config) {
if (Array.isArray(config)) {
const layer = new merge_Add({});
return layer.apply(config);
} else {
return new merge_Add(config);
}
}
class merge_Multiply extends merge_Merge {
constructor(args) {
super(args);
}
mergeFunction(inputs) {
return Object(dist["tidy"])(() => {
let output = inputs[0].clone();
for (let i = 1; i < inputs.length; ++i) {
output = dist["mul"](output, inputs[i]);
}
return output;
});
}
}
/** @nocollapse */
merge_Multiply.className = "Multiply";
dist["serialization"].registerClass(merge_Multiply);
/**
* Calculate the element-wise product of inputs, which all have the same shape.
*
* This function can be invoked in three ways.
*
* 1. Construct an instance of `Multiply` layer, by using no input argument
* or a single configuration argument. The resultant `Multiply` layer can
* then be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:
*
* ```js
* const multiplyLayer = tf.layers.multiply();
*
* // The layer can be applied to inputs.
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = multiplyLayer.apply([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.SymbolicTensor`. For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = tf.layers.multiply([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.Tensor` as the result of the computation. For
* example:
*
* ```js
* const input1 = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const input2 = tf.tensor2d([10, 20, 30, 40], [2, 2]);
* tf.layers.multiply([input1, input2]).print();
* // Gives [[10, 40], [90, 160]].
*
*/
function multiply(config) {
if (Array.isArray(config)) {
const layer = new merge_Multiply({});
return layer.apply(config);
} else {
return new merge_Multiply(config);
}
}
class merge_Average extends merge_Merge {
constructor(args) {
super(args);
}
mergeFunction(inputs) {
return Object(dist["tidy"])(() => {
let output = inputs[0].clone();
for (let i = 1; i < inputs.length; ++i) {
output = dist["add"](output, inputs[i]);
}
return dist["mul"](1 / inputs.length, output);
});
}
}
/** @nocollapse */
merge_Average.className = "Average";
dist["serialization"].registerClass(merge_Average);
/**
* Calculate the element-wise arithmetic mean of inputs, which all have the same
* shape.
*
* This function can be invoked in three ways.
*
* 1. Construct an instance of `Average` layer, by using no input argument
* or a single configuration argument. The resultant `Average` layer can then
* be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:
*
* ```js
* const averageLayer = tf.layers.average();
*
* // The layer can be applied to inputs.
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = averageLayer.apply([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.SymbolicTensor`. For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = tf.layers.average([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.Tensor` as the result of the computation. For
* example:
*
* ```js
* const input1 = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const input2 = tf.tensor2d([10, 20, 30, 40], [2, 2]);
* tf.layers.average([input1, input2]).print();
* // Gives [[5.5, 11], [16.5, 22]].
*
*/
function average(config) {
if (Array.isArray(config)) {
const layer = new merge_Average({});
return layer.apply(config);
} else {
return new merge_Average(config);
}
}
class merge_Maximum extends merge_Merge {
constructor(args) {
super(args);
}
mergeFunction(inputs) {
return Object(dist["tidy"])(() => {
let output = inputs[0];
for (let i = 1; i < inputs.length; ++i) {
output = dist["maximum"](output, inputs[i]);
}
return output;
});
}
}
/** @nocollapse */
merge_Maximum.className = "Maximum";
dist["serialization"].registerClass(merge_Maximum);
/**
* Calculate the element-wise maximum of inputs, which all have the same shape.
*
* This function can be invoked in three ways.
*
* 1. Construct an instance of `Maximum` layer, by using no input argument
* or a single configuration argument. The resultant `Maximum` layer can then
* be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:
*
* ```js
* const maximumLayer = tf.layers.maximum();
*
* // The layer can be applied to inputs.
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = maximumLayer.apply([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.SymbolicTensor`. For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = tf.layers.maximum([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.Tensor` as the result of the computation. For
* example:
*
* ```js
* const input1 = tf.tensor2d([1, 20, 3, 40], [2, 2]);
* const input2 = tf.tensor2d([10, 2, 30, 4], [2, 2]);
* tf.layers.maximum([input1, input2]).print();
* // Gives [[10, 20], [30, 40]].
*
*/
function maximum(config) {
if (Array.isArray(config)) {
const layer = new merge_Maximum({});
return layer.apply(config);
} else {
return new merge_Maximum(config);
}
}
class merge_Minimum extends merge_Merge {
constructor(args) {
super(args);
}
mergeFunction(inputs) {
return Object(dist["tidy"])(() => {
let output = inputs[0];
for (let i = 1; i < inputs.length; ++i) {
output = dist["minimum"](output, inputs[i]);
}
return output;
});
}
}
/** @nocollapse */
merge_Minimum.className = "Minimum";
dist["serialization"].registerClass(merge_Minimum);
/**
* Calculate the element-wise minimum of inputs, which all have the same shape.
*
* This function can be invoked in three ways.
*
* 1. Construct an instance of `Minimum` layer, by using no input argument
* or a single configuration argument. The resultant `Minimum` layer can then
* be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:
*
* ```js
* const minimumLayer = tf.layers.minimum();
*
* // The layer can be applied to inputs.
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = minimumLayer.apply([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.SymbolicTensor`. For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const output = tf.layers.minimum([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.Tensor` as the result of the computation. For
* example:
*
* ```js
* const input1 = tf.tensor2d([1, 20, 3, 40], [2, 2]);
* const input2 = tf.tensor2d([10, 2, 30, 4], [2, 2]);
* tf.layers.minimum([input1, input2]).print();
* // Gives [[1, 2], [3, 4]].
*
*/
function minimum(config) {
if (Array.isArray(config)) {
const layer = new merge_Minimum({});
return layer.apply(config);
} else {
return new merge_Minimum(config);
}
}
class merge_Concatenate extends merge_Merge {
constructor(args) {
super(args);
this.DEFAULT_AXIS = -1;
if (args == null) {
args = {};
}
this.axis = args.axis == null ? this.DEFAULT_AXIS : args.axis;
this.supportsMasking = true;
this.reshapeRequired = false;
}
build(inputShape) {
// Used purely for shape validation.]
if (
!(Array.isArray(inputShape) && Array.isArray(inputShape[0])) ||
inputShape.length === 1
) {
throw new ValueError(
"A `Concatenate` layer should be called on a list of at least 2 " + "inputs"
);
}
inputShape = inputShape;
let allNoneShape = true;
for (const shape of inputShape) {
if (shape != null) {
allNoneShape = false;
break;
}
}
if (allNoneShape) {
return;
}
const shapeSet = [];
for (let i = 0; i < inputShape.length; ++i) {
const shapeWithoutConcatAxis = inputShape[i].slice();
shapeWithoutConcatAxis.splice(this.axis, 1);
let exists = false;
for (const shape of shapeSet) {
if (dist["util"].arraysEqual(shape, shapeWithoutConcatAxis)) {
exists = true;
break;
}
}
if (!exists) {
shapeSet.push(shapeWithoutConcatAxis);
}
}
if (shapeSet.length > 1) {
throw new ValueError(
"A `Concatenate` layer requires inputs with matching shapes " +
"except for the concat axis. Got input shapes: " +
JSON.stringify(inputShape)
);
}
}
mergeFunction(inputs) {
return Object(dist["tidy"])(() => {
return concatenate(inputs, this.axis);
});
}
computeOutputShape(inputShape) {
if (!(Array.isArray(inputShape) && Array.isArray(inputShape[0]))) {
throw new ValueError("A `Concatenate` layer should be called on a list of inputs.");
}
const inputShapes = inputShape;
const outputShape = inputShapes[0].slice();
const axis = this.axis < 0 ? outputShape.length + this.axis : this.axis;
// Porting Note: the line above is because TypeScript doesn't support
// negative indices.
for (const shape of inputShapes.slice(1)) {
if (outputShape[axis] == null || shape[axis] == null) {
outputShape[axis] = null;
break;
}
outputShape[axis] += shape[axis];
}
return outputShape;
}
computeMask(inputs, mask) {
if (mask == null) {
return null;
}
if (!Array.isArray(mask)) {
throw new ValueError("`mask` should be an array for Concatenate");
}
if (!Array.isArray(inputs)) {
throw new ValueError("`inputs` should be an array for Concatenate");
}
if (mask.length !== inputs.length) {
throw new ValueError(
`Mismatch in the length of mask (${mask.length}) ` +
`and the legnth of inputs (${inputs.length})`
);
}
return dist["tidy"](() => {
let allNullMasks = true;
mask.forEach((m) => {
if (m != null) {
allNullMasks = false;
return;
}
});
if (allNullMasks) {
return null;
}
const outputMasks = [];
for (let i = 0; i < inputs.length; ++i) {
if (mask[i] == null) {
// Input is unmasked. Append all 1's to masks.
outputMasks.push(dist["onesLike"](inputs[i]).asType("bool"));
} else if (mask[i].rank < inputs[i].rank) {
// Mask is smaller than the input, expand it.
outputMasks.push(dist["expandDims"](mask[i], -1));
} else {
outputMasks.push(mask[i]);
}
}
const concatenatedMasks = dist["concat"](outputMasks, this.axis);
return dist["all"](concatenatedMasks, -1, false);
});
}
getConfig() {
const config = {
axis: this.axis,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
merge_Concatenate.className = "Concatenate";
dist["serialization"].registerClass(merge_Concatenate);
/**
* Concatenate an `Array` of inputs.
*
* This function can be invoked in three ways.
*
* 1. Construct an instance of `Concatenate` layer, by using no input argument
* or a single configuration argument. The resultant `Concatenate` layer can
* then be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:
*
* ```js
* const concatLayer = tf.layers.concatenate();
*
* // The layer can be applied to inputs.
* const input1 = tf.input({shape: [2, 3]});
* const input2 = tf.input({shape: [2, 4]});
* const output = concatLayer.apply([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 7], with the first dimension as the undetermined batch
* // dimension and the last dimension as the result of concatenating the
* // last dimensions of the two inputs.
* ```
*
* 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.SymbolicTensor`. For example:
*
* ```js
* const input1 = tf.input({shape: [2, 3]});
* const input2 = tf.input({shape: [2, 4]});
* const output = tf.layers.concatenate([input1, input2]);
* console.log(output.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension and the last dimension as the result of concatenating the
* // last dimensions of the two inputs.
* ```
*
* 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs
* an `Layer` object internally and calls its `apply` method on the inputs,
* generating a new `tf.Tensor` as the result of the computation. For
* example:
*
* ```js
* const input1 = tf.tensor2d([[1, 2], [3, 4]], [2, 2]);
* const input2 = tf.tensor2d([[10, 20], [30, 40]], [2, 2]);
* tf.layers.concatenate([input1, input2]).print();
* // Gives [[1, 2, 10, 20], [3, 4, 30, 40]].
*
*/
function merge_concatenate(config) {
if (Array.isArray(config)) {
const layer = new merge_Concatenate({});
return layer.apply(config);
} else {
return new merge_Concatenate(config);
}
}
/**
* Interpretable potentially negative axis index.
*
* For example, given axis = -1, and dim = 3, this function will return 2.
*
* @param axis The axis index, may be a positive, zero or negative integer.
* @param dim Total number of dimensions, a positive integer.
* @returns A non-negative axis index equivalent to the input `axis`.
*/
function interpretAxis(axis, dim) {
while (axis < 0) {
axis += dim;
}
return axis;
}
function batchDot(x, y, axes) {
if (x.shape.length > 3 || y.shape.length > 3) {
throw new NotImplementedError(
"batchDot is not implemented for tensors of 4D or higher rank yet"
);
}
dist["util"].assert(
x.shape.length >= 2,
() => `batchDot requires the rank of x to be >= 2, ` + `but got ${x.shape.length}`
);
dist["util"].assert(
x.shape.length >= 2,
() => `batchDot requires the rank of y to be >= 2, ` + `but got ${y.shape.length}`
);
if (typeof axes === "number") {
axes = [axes, axes];
}
if (x.dtype === "complex64" || y.dtype === "complex64") {
throw new NotImplementedError(
"batchDot is not implemented for complex64-type Tensors yet."
);
}
const xNDim = x.shape.length;
const yNDim = y.shape.length;
if (axes == null) {
// Behave like batchMatmul by default.
axes = [xNDim - 1, yNDim - 2];
}
const axesArray = axes;
return dist["tidy"](() => {
let diff;
if (xNDim > yNDim) {
diff = xNDim - yNDim;
const diffShape = [];
for (let i = 0; i < diff; ++i) {
diffShape.push(1);
}
y = y.reshape(y.shape.concat(diffShape));
} else if (yNDim > xNDim) {
diff = yNDim - xNDim;
const diffShape = [];
for (let i = 0; i < diff; ++i) {
diffShape.push(1);
}
x = x.reshape(x.shape.concat(diffShape));
} else {
diff = 0;
}
let out;
if (x.shape.length === 2 && y.shape.length === 2) {
if (axesArray[0] === axesArray[1]) {
out = x.mul(y).sum(axesArray[0]);
} else {
out = x.transpose([1, 0]).mul(y).sum(axesArray[1]);
}
} else {
const adjX = axesArray[0] !== x.shape.length - 1;
const adjY = axesArray[1] === y.shape.length - 1;
out = x.matMul(y, adjX, adjY);
}
if (diff > 0) {
let idx;
if (xNDim > yNDim) {
idx = xNDim + yNDim - 3;
} else {
idx = xNDim - 1;
}
const squeezeAxes = [];
for (let i = idx; i < idx + diff; ++i) {
squeezeAxes.push(i);
}
out = out.squeeze(squeezeAxes);
}
if (out.shape.length === 1) {
out = out.expandDims(1);
}
return out;
});
}
class merge_Dot extends merge_Merge {
constructor(args) {
super(args);
this.axes = args.axes;
this.normalize = args.normalize == null ? false : args.normalize;
this.supportsMasking = true;
this.reshapeRequired = false;
}
build(inputShape) {
dist["util"].assert(
Array.isArray(inputShape) &&
inputShape.length === 2 &&
Array.isArray(inputShape[0]) &&
Array.isArray(inputShape[1]),
() => "A `Dot` layer should be called on a list of exactly 2 inputs."
);
const shape1 = inputShape[0];
const shape2 = inputShape[1];
if (shape1.length > 3 || shape2.length > 3) {
throw new NotImplementedError(
"Dot layer does not support tensors of 4D or higher rank yet."
);
}
const axes = this.interpretAxes(shape1, shape2);
if (shape1[axes[0]] !== shape2[axes[1]]) {
throw new ValueError(
`Dimension incompatibility: ` + `${shape1[axes[0]]} !== ${shape2[axes[1]]}`
);
}
}
mergeFunction(inputs) {
if (inputs.length !== 2) {
throw new ValueError(
"A `Dot` layer must be called on exactly 2 inputs, " +
`but received ${inputs.length} input(s).`
);
}
let x1 = inputs[0];
let x2 = inputs[1];
let axes;
if (!Array.isArray(this.axes)) {
axes = [
interpretAxis(this.axes, x1.shape.length),
interpretAxis(this.axes, x2.shape.length),
];
} else {
axes = this.axes.map((axis, i) => interpretAxis(axis, inputs[i].shape.length));
}
if (this.normalize) {
x1 = l2Normalize(x1, axes[0]);
x2 = l2Normalize(x2, axes[1]);
}
return batchDot(x1, x2, axes);
}
interpretAxes(shape1, shape2) {
let axes;
if (!Array.isArray(this.axes)) {
// `this.axes` is a single integer.
axes = [
interpretAxis(this.axes, shape1.length),
interpretAxis(this.axes, shape2.length),
];
} else {
// `this.axes` is an Array of integers.
axes = this.axes;
}
return axes;
}
computeOutputShape(inputShape) {
dist["util"].assert(
Array.isArray(inputShape) &&
inputShape.length === 2 &&
Array.isArray(inputShape[0]) &&
Array.isArray(inputShape[1]),
() => "A `Dot` layer should be called on a list of exactly 2 inputs."
);
const shape1 = inputShape[0].slice();
const shape2 = inputShape[1].slice();
if (shape1.length > 3 || shape2.length > 3) {
throw new NotImplementedError(
"Dot layer does not support tensors of 4D or higher rank yet."
);
}
const axes = this.interpretAxes(shape1, shape2);
shape1.splice(axes[0], 1);
shape2.splice(axes[1], 1);
shape2.splice(0, 1);
const outputShape = shape1.concat(shape2);
if (outputShape.length === 1) {
outputShape.push(1);
}
return outputShape;
}
computeMask(inputs, mask) {
return null;
}
getConfig() {
const config = {
axes: this.axes,
normalize: this.normalize,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
merge_Dot.className = "Dot";
dist["serialization"].registerClass(merge_Dot);
// TODO(cais): Add functional interfaces for the merge layers.
//# sourceMappingURL=merge.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/noise.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Noise Layers.
*/
class noise_GaussianNoise extends topology_Layer {
constructor(args) {
super(args);
this.supportsMasking = true;
this.stddev = args.stddev;
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const baseConfig = super.getConfig();
const config = { stddev: this.stddev };
Object.assign(config, baseConfig);
return config;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
const input = getExactlyOneTensor(inputs);
const noised = () => randomNormal(input.shape, 0, this.stddev).add(input);
const output = inTrainPhase(noised, () => input, kwargs["training"] || false);
return output;
});
}
}
/** @nocollapse */
noise_GaussianNoise.className = "GaussianNoise";
dist["serialization"].registerClass(noise_GaussianNoise);
class noise_GaussianDropout extends topology_Layer {
constructor(args) {
super(args);
this.supportsMasking = true;
this.rate = args.rate;
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const baseConfig = super.getConfig();
const config = { rate: this.rate };
Object.assign(config, baseConfig);
return config;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
const input = getExactlyOneTensor(inputs);
if (this.rate > 0 && this.rate < 1) {
const noised = () => {
const stddev = Math.sqrt(this.rate / (1 - this.rate));
return input.mul(randomNormal(input.shape, 1, stddev));
};
return inTrainPhase(noised, () => input, kwargs["training"] || false);
}
return input;
});
}
}
/** @nocollapse */
noise_GaussianDropout.className = "GaussianDropout";
dist["serialization"].registerClass(noise_GaussianDropout);
/**
* Applies Alpha Dropout to the input.
*
* As it is a regularization layer, it is only active at training time.
*
* Alpha Dropout is a `Dropout` that keeps mean and variance of inputs
* to their original values, in order to ensure the self-normalizing property
* even after this dropout.
* Alpha Dropout fits well to Scaled Exponential Linear Units
* by randomly setting activations to the negative saturation value.
*
* Arguments:
* - `rate`: float, drop probability (as with `Dropout`).
* The multiplicative noise will have
* standard deviation `sqrt(rate / (1 - rate))`.
* - `noise_shape`: A 1-D `Tensor` of type `int32`, representing the
* shape for randomly generated keep/drop flags.
*
* Input shape:
* Arbitrary. Use the keyword argument `inputShape`
* (tuple of integers, does not include the samples axis)
* when using this layer as the first layer in a model.
*
* Output shape:
* Same shape as input.
*
* References:
* - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
*/
class noise_AlphaDropout extends topology_Layer {
constructor(args) {
super(args);
this.supportsMasking = true;
this.rate = args.rate;
this.noiseShape = args.noiseShape;
}
_getNoiseShape(inputs) {
return this.noiseShape || getExactlyOneTensor(inputs).shape;
}
computeOutputShape(inputShape) {
return inputShape;
}
getConfig() {
const baseConfig = super.getConfig();
const config = { rate: this.rate };
Object.assign(config, baseConfig);
return config;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
if (this.rate < 1 && this.rate > 0) {
const noiseShape = this._getNoiseShape(inputs);
const droppedInputs = () => {
const input = getExactlyOneTensor(inputs);
const alpha = 1.6732632423543772848170429916717;
const scale = 1.0507009873554804934193349852946;
const alphaP = -alpha * scale;
let keptIdx = Object(dist["greaterEqual"])(
Object(dist["randomUniform"])(noiseShape),
this.rate
);
keptIdx = cast(keptIdx, "float32"); // get default dtype.
// Get affine transformation params.
const a = ((1 - this.rate) * (1 + this.rate * alphaP ** 2)) ** -0.5;
const b = -a * alphaP * this.rate;
// Apply mask.
const x = input.mul(keptIdx).add(keptIdx.add(-1).mul(alphaP));
return x.mul(a).add(b);
};
return inTrainPhase(
droppedInputs,
() => getExactlyOneTensor(inputs),
kwargs["training"] || false
);
}
return inputs;
});
}
}
/** @nocollapse */
noise_AlphaDropout.className = "AlphaDropout";
dist["serialization"].registerClass(noise_AlphaDropout);
//# sourceMappingURL=noise.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/normalization.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Normalization layers.
*/
/**
* Applies batch normalization on x given mean, var, beta and gamma.
*
* I.e. returns:
* `output = (x - mean) / (sqrt(var) + epsilon) * gamma + beta`
*
* @param x Input tensor.
* @param mean Mean of batch.
* @param variance Variance of batch.
* @param beta Tensor with which to center the input.
* @param gamma Tensor by which to scale the input.
* @param epsilon Fuzz factor.
* @returns The result of the batch normalization.
*/
function batchNormalization(x, mean, variance, beta, gamma, epsilon = 1e-3) {
let out;
if (x.rank === 2) {
out = dist["batchNorm2d"](x, mean, variance, beta, gamma, epsilon);
} else if (x.rank === 3) {
// TODO(cais): Check rank; give proper error message.
out = dist["batchNorm3d"](x, mean, variance, beta, gamma, epsilon);
} else if (x.rank === 4) {
out = dist["batchNorm4d"](x, mean, variance, beta, gamma, epsilon);
} else {
throw new NotImplementedError(
`batchNormalization is not implemented for array of rank ${x.rank} ` + `yet`
);
}
return out;
}
/**
* Non-broadcasting batch normalization for use in training (not inference).
*
* The input is normalized to zero mean and unit variance along the
* `reductionAxes`, followed by scaling with `gamma` and shifted by `beta`.
* The result of that is returned as the first element
* of the returned `Array`. The other two elements are the mean and variance,
* respectively.
*
* @param x Input tensor to be normalized.
* @param gamma Tensor by which to scale the input.
* @param beta Tensor by which to center the input.
* @param reductionAxes Axes over which to normalize.
* @param epsilon Fuzz factor.
* @returns An `Array` of three `Tensors`:
* [normalized tensor, mean of input, variance of input].
*/
function regularNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon = 1e-3) {
return Object(dist["tidy"])(() => {
const meanAndVariance = dist["moments"](x, reductionAxes);
const mean = meanAndVariance.mean;
const variance = meanAndVariance.variance;
const normed = batchNormalization(x, mean, variance, beta, gamma, epsilon);
return [normed, mean, variance];
});
}
/**
* Broadcasting batch normalization for use in training (not inference).
*
* The input is normalized to zero mean and unit variance along the
* `reductionAxes`, followed by scaling with `gamma` and shifted by `beta`.
* The result of that is returned as the first element
* of the returned `Array`. The other two elements are the mean and variance,
* respectively.
*
* @param x Input tensor to be normalized.
* @param gamma Tensor by which to scale the input.
* @param beta Tensor by which to center the input.
* @param reductionAxes Axes over which to normalize.
* @param epsilon Fuzz factor.
* @returns An `Array` of three `Tensors`:
* [normalized tensor, mean of input, variance of input].
*/
function broadcastNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon = 1e-3) {
return Object(dist["tidy"])(() => {
const meanAndVariance = dist["moments"](x, reductionAxes);
const mean = meanAndVariance.mean;
const variance = meanAndVariance.variance;
const targetShape = [];
for (const axis of range(0, x.rank)) {
if (reductionAxes.indexOf(axis) !== -1) {
targetShape.push(1);
} else {
targetShape.push(x.shape[axis]);
}
}
const broadcastMean = mean.reshape(targetShape);
const broadcastVariance = variance.reshape(targetShape);
const broadcastGamma = gamma == null ? null : gamma.reshape(targetShape);
const broadcastBeta = beta == null ? null : beta.reshape(targetShape);
const normed = batchNormalization(
x,
broadcastMean,
broadcastVariance,
broadcastBeta,
broadcastGamma,
epsilon
);
return [normed, mean, variance];
});
}
/**
* Batch normalization for use in training (not inference).
*
* @param x Input tensor to be normalized.
* @param gamma Tensor by which to scale the input.
* @param beta Tensor by which to center the input.
* @param reductionAxes Axes over which to normalize.
* @param epsilon Fuzz factor.
* @returns An `Array` of three `Tensors`:
* [normalized tensor, mean of input, variance of input].
*/
function normalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon = 1e-3) {
if (dist["util"].arraysEqual(reductionAxes.slice().sort(), range(0, x.rank - 1))) {
return regularNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon);
} else {
return broadcastNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon);
}
}
class normalization_BatchNormalization extends topology_Layer {
constructor(args) {
if (args == null) {
args = {};
}
super(args);
this.supportsMasking = true;
this.axis = args.axis == null ? -1 : args.axis;
this.momentum = args.momentum == null ? 0.99 : args.momentum;
this.epsilon = args.epsilon == null ? 1e-3 : args.epsilon;
this.center = args.center == null ? true : args.center;
this.scale = args.scale == null ? true : args.scale;
this.betaInitializer = getInitializer(args.betaInitializer || "zeros");
this.gammaInitializer = getInitializer(args.gammaInitializer || "ones");
this.movingMeanInitializer = getInitializer(args.movingMeanInitializer || "zeros");
this.movingVarianceInitializer = getInitializer(args.movingVarianceInitializer || "ones");
this.betaConstraint = getConstraint(args.betaConstraint);
this.gammaConstraint = getConstraint(args.gammaConstraint);
this.betaRegularizer = getRegularizer(args.betaRegularizer);
this.gammaRegularizer = getRegularizer(args.gammaRegularizer);
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const axis = this.axis >= 0 ? this.axis : this.axis + inputShape.length;
const dim = inputShape[axis];
if (dim == null) {
throw new ValueError(
`Axis ${axis} of input tensor should have a defined dimension but ` +
`the layer received an input with shape ` +
`${JSON.stringify(inputShape)}.`
);
}
this.inputSpec = [new InputSpec({ ndim: inputShape.length, axes: { [axis]: dim } })];
const shape = [dim];
if (this.scale) {
this.gamma = this.addWeight(
"gamma",
shape,
null,
this.gammaInitializer,
this.gammaRegularizer,
true,
this.gammaConstraint
);
}
if (this.center) {
this.beta = this.addWeight(
"beta",
shape,
null,
this.betaInitializer,
this.betaRegularizer,
true,
this.betaConstraint
);
}
this.movingMean = this.addWeight(
"moving_mean",
shape,
null,
this.movingMeanInitializer,
null,
false
);
this.movingVariance = this.addWeight(
"moving_variance",
shape,
null,
this.movingVarianceInitializer,
null,
false
);
this.built = true;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
const training = kwargs["training"] == null ? false : kwargs["training"];
const input = getExactlyOneTensor(inputs);
const inputShape = input.shape;
const ndim = inputShape.length;
const reductionAxes = range(0, ndim);
const axis = this.axis >= 0 ? this.axis : this.axis + ndim;
reductionAxes.splice(axis, 1);
const broadcastShape = pyListRepeat(1, ndim);
broadcastShape[axis] = inputShape[axis];
const sortedReductionAxes = reductionAxes.slice();
sortedReductionAxes.sort();
const needsBroadcasting = !dist["util"].arraysEqual(
sortedReductionAxes,
range(0, ndim).slice(0, ndim - 1)
);
const normalizeInference = () => {
if (needsBroadcasting) {
const broadcastMovingMean = this.movingMean.read().reshape(broadcastShape);
const broadcastMovingVariance = this.movingVariance.read().reshape(broadcastShape);
const broadcastBeta = this.center ? this.beta.read().reshape(broadcastShape) : null;
const broadcastGamma = this.scale
? this.gamma.read().reshape(broadcastShape)
: null;
return batchNormalization(
input,
broadcastMovingMean,
broadcastMovingVariance,
broadcastBeta,
broadcastGamma,
this.epsilon
);
} else {
return batchNormalization(
input,
this.movingMean.read(),
this.movingVariance.read(),
this.beta == null ? null : this.beta.read(),
this.gamma == null ? null : this.gamma.read(),
this.epsilon
);
}
};
if (!training) {
return normalizeInference();
}
const [normedTraining, mean, variance] = normalizeBatchInTraining(
input,
this.gamma.read(),
this.beta.read(),
reductionAxes,
this.epsilon
);
const doMovingAverage = (variable, value, momentum) => {
dist["tidy"](() => {
const decay = 1 - momentum;
const origValue = variable.read();
const updateDelta = origValue.sub(value).mul(decay);
variable.write(origValue.sub(updateDelta));
});
};
// Perform updates to moving mean and moving variance for training.
// Porting Note: In PyKeras, these updates to `movingMean` and
// `movingAverage` are done as a deferred Graph, added to the `Layer`'s
// `update`s using the `add_update()` method. Here we do it imperatively
// and encapsulate the updates in a function that is invoked
// immediately.
const updateMovingMeanAndVariance = () => {
doMovingAverage(this.movingMean, mean, this.momentum);
doMovingAverage(this.movingVariance, variance, this.momentum);
};
updateMovingMeanAndVariance();
return normedTraining;
});
}
getConfig() {
const config = {
axis: this.axis,
momentum: this.momentum,
epsilon: this.epsilon,
center: this.center,
scale: this.scale,
betaInitializer: serializeInitializer(this.betaInitializer),
gammaInitializer: serializeInitializer(this.gammaInitializer),
movingMeanInitializer: serializeInitializer(this.movingMeanInitializer),
movingVarianceInitializer: serializeInitializer(this.movingVarianceInitializer),
betaRegularizer: serializeRegularizer(this.betaRegularizer),
gammaRegularizer: serializeRegularizer(this.gammaRegularizer),
betaConstraint: serializeConstraint(this.betaConstraint),
gammaConstraint: serializeConstraint(this.gammaConstraint),
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
normalization_BatchNormalization.className = "BatchNormalization";
dist["serialization"].registerClass(normalization_BatchNormalization);
class normalization_LayerNormalization extends topology_Layer {
constructor(args) {
if (args == null) {
args = {};
}
super(args);
this.axis = args.axis == null ? -1 : args.axis;
if (typeof this.axis === "number") {
if (!Number.isInteger(this.axis)) {
throw new Error(`Expected axis to be an integer, but received ${this.axis}`);
}
} else if (Array.isArray(this.axis)) {
for (const axis of this.axis) {
if (!Number.isInteger(axis)) {
throw new Error(
`Expected axis to be an array of integers, ` +
`but received ${JSON.stringify(this.axis)}`
);
}
}
} else {
throw new Error(
`Expected axis to be an integer or an array of integers, ` +
`but received ${JSON.stringify(this.axis)}`
);
}
this.epsilon = args.epsilon == null ? 1e-3 : args.epsilon;
this.center = args.center == null ? true : args.center;
this.scale = args.scale == null ? true : args.scale;
this.betaInitializer = getInitializer(args.betaInitializer || "zeros");
this.gammaInitializer = getInitializer(args.gammaInitializer || "ones");
this.betaRegularizer = getRegularizer(args.betaRegularizer);
this.gammaRegularizer = getRegularizer(args.gammaRegularizer);
this.supportsMasking = true;
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const nDims = inputShape.length;
// Convert axis to array and resolve negatives.
if (typeof this.axis === "number") {
this.axis = [this.axis];
}
for (let i = 0; i < this.axis.length; ++i) {
if (this.axis[i] < 0) {
this.axis[i] += nDims;
}
}
// Further validate axes.
for (const axis of this.axis) {
if (axis < 0 || axis >= nDims) {
throw new Error(`Invalid axis: ${axis}`);
}
}
if (this.axis.length !== unique(this.axis).length) {
throw new Error(`Found duplicate axes in: ${this.axis}`);
}
const paramShape = this.axis.map((axis) => inputShape[axis]);
const trainable = true;
if (this.scale) {
this.gamma = this.addWeight(
"gamma",
paramShape,
"float32",
this.gammaInitializer,
this.gammaRegularizer,
trainable
);
} else {
this.gamma = null;
}
if (this.center) {
this.beta = this.addWeight(
"beta",
paramShape,
"float32",
this.betaInitializer,
this.betaRegularizer,
trainable
);
} else {
this.beta = null;
}
this.built = true;
}
call(inputs, kwargs) {
const input = getExactlyOneTensor(inputs);
const inputShape = input.shape;
const nDims = inputShape.length;
return Object(dist["tidy"])(() => {
const keepDims = true;
let { mean, variance } = Object(dist["moments"])(input, this.axis, keepDims);
const broadcastShape = pyListRepeat(1, nDims);
for (const dim of this.axis) {
broadcastShape[dim] = inputShape[dim];
}
const broadcast = (v) => {
if (v != null && v.shape.length !== nDims && this.axis !== [nDims - 1]) {
return v.reshape(broadcastShape);
} else {
return v;
}
};
let scale = broadcast(this.gamma.read());
let offset = broadcast(this.beta.read());
// TODO(https://github.com/tensorflow/tfjs/issues/2120): The tiling below
// is a workaround for the limitation of core's batchNormalization?d don't
// support broadcasting in their gradients. In addition, the tiling is
// necessary to ensure correctness on the browser CPU backend regardless
// of forward or backward computation. Remove this workaround once the
// limitation is addressed. See .
const momentsTiling = [];
const scaleOffsetTiling = [];
for (let i = 0; i < nDims; ++i) {
if (this.axis.indexOf(i) !== -1) {
momentsTiling.push(inputShape[i]);
scaleOffsetTiling.push(1);
} else {
momentsTiling.push(1);
scaleOffsetTiling.push(inputShape[i]);
}
}
mean = mean.tile(momentsTiling);
variance = variance.tile(momentsTiling);
scale = scale.tile(scaleOffsetTiling);
offset = offset.tile(scaleOffsetTiling);
return batchNormalization(input, mean, variance, offset, scale, this.epsilon);
});
}
getConfig() {
const config = {
axis: this.axis,
epsilon: this.epsilon,
center: this.center,
scale: this.scale,
betaInitializer: serializeInitializer(this.betaInitializer),
gammaInitializer: serializeInitializer(this.gammaInitializer),
betaRegularizer: serializeRegularizer(this.betaRegularizer),
gammaRegularizer: serializeRegularizer(this.gammaRegularizer),
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
normalization_LayerNormalization.className = "LayerNormalization";
dist["serialization"].registerClass(normalization_LayerNormalization);
//# sourceMappingURL=normalization.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/padding.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Padding Layers.
*/
// Porting Note: In Python Keras, the padding layers are in convolutional.py,
// but we decided to put them in a separate file (padding.ts) for clarity.
/**
* Pads the middle dimension of a 3D tensor.
*
* @param x Input `tf.Tensor` to be padded.
* @param padding `Array` of 2 integers, how many zeros to add at the start and
* end of the middle dimension (i.e., dimension 1).
* @return A padded 3D `tf.Tensor`.
*/
function temporalPadding(x, padding) {
return Object(dist["tidy"])(() => {
if (x.rank !== 3) {
throw new ValueError(
`temporalPadding expects input tensor to be 3-D, but received a ` +
`${x.rank}-D tensor.`
);
}
if (padding == null) {
padding = [1, 1];
}
if (padding.length !== 2) {
throw new ValueError(
`temporalPadding expects input padding pattern to be a length-2 ` +
`array, but received a length-${padding.length} array.`
);
}
const pattern = [[0, 0], padding, [0, 0]];
return dist["pad"](x, pattern);
});
}
/**
* Pads the 2nd and 3rd dimensions of a 4D tensor.
*
* @param x Input `tf.Tensor` to be padded.
* @param padding `Array` of two `Array`s, each of which is an `Array` of two
* integers. The amount of padding at the beginning and end of the 2nd and 3rd
* dimensions, respectively.
* @param dataFormat 'channelsLast' (default) or 'channelsFirst'.
* @return Padded 4D `tf.Tensor`.
*/
function spatial2dPadding(x, padding, dataFormat) {
return Object(dist["tidy"])(() => {
if (x.rank !== 4) {
throw new ValueError(
`temporalPadding expects input tensor to be 4-D, but received a ` +
`${x.rank}-D tensor.`
);
}
if (padding == null) {
padding = [
[1, 1],
[1, 1],
];
}
if (padding.length !== 2 || padding[0].length !== 2 || padding[1].length !== 2) {
throw new ValueError(
"spatial2dPadding expects `padding` to be an Array of two Arrays, " +
"each of which is an Array of two integers."
);
}
if (dataFormat == null) {
dataFormat = imageDataFormat();
}
if (dataFormat !== "channelsLast" && dataFormat !== "channelsFirst") {
throw new ValueError(
`Unknown data format: ${dataFormat}. ` +
`Supported data formats are 'channelsLast' and 'channelsFirst.`
);
}
let pattern;
if (dataFormat === "channelsFirst") {
pattern = [[0, 0], [0, 0], padding[0], padding[1]];
} else {
pattern = [[0, 0], padding[0], padding[1], [0, 0]];
}
return dist["pad"](x, pattern);
});
}
class padding_ZeroPadding2D extends topology_Layer {
constructor(args) {
if (args == null) {
args = {};
}
super(args);
this.dataFormat = args.dataFormat == null ? imageDataFormat() : args.dataFormat;
// TODO(cais): Maybe refactor the following logic surrounding `padding`
// into a helper method.
if (args.padding == null) {
this.padding = [
[1, 1],
[1, 1],
];
} else if (typeof args.padding === "number") {
this.padding = [
[args.padding, args.padding],
[args.padding, args.padding],
];
} else {
args.padding = args.padding;
if (args.padding.length !== 2) {
throw new ValueError(
`ZeroPadding2D expects padding to be a length-2 array, but ` +
`received a length-${args.padding.length} array.`
);
}
let heightPadding;
let widthPadding;
if (typeof args.padding[0] === "number") {
heightPadding = [args.padding[0], args.padding[0]];
widthPadding = [args.padding[1], args.padding[1]];
} else {
args.padding = args.padding;
if (args.padding[0].length !== 2) {
throw new ValueError(
`ZeroPadding2D expects height padding to be a length-2 array, ` +
`but received a length-${args.padding[0].length} array.`
);
}
heightPadding = args.padding[0];
if (args.padding[1].length !== 2) {
throw new ValueError(
`ZeroPadding2D expects width padding to be a length-2 array, ` +
`but received a length-${args.padding[1].length} array.`
);
}
widthPadding = args.padding[1];
}
this.padding = [heightPadding, widthPadding];
}
this.inputSpec = [new InputSpec({ ndim: 4 })];
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
let rows;
let cols;
if (this.dataFormat === "channelsFirst") {
if (inputShape[2] != null && inputShape[2] >= 0) {
rows = inputShape[2] + this.padding[0][0] + this.padding[0][1];
} else {
rows = null;
}
if (inputShape[3] != null && inputShape[3] >= 0) {
cols = inputShape[3] + this.padding[1][0] + this.padding[1][1];
} else {
cols = null;
}
return [inputShape[0], inputShape[1], rows, cols];
} else {
if (inputShape[1] != null && inputShape[1] >= 0) {
rows = inputShape[1] + this.padding[0][0] + this.padding[0][1];
} else {
rows = null;
}
if (inputShape[2] != null && inputShape[2] >= 0) {
cols = inputShape[2] + this.padding[1][0] + this.padding[1][1];
} else {
cols = null;
}
return [inputShape[0], rows, cols, inputShape[3]];
}
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() =>
spatial2dPadding(getExactlyOneTensor(inputs), this.padding, this.dataFormat)
);
}
getConfig() {
const config = {
padding: this.padding,
dataFormat: this.dataFormat,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
padding_ZeroPadding2D.className = "ZeroPadding2D";
dist["serialization"].registerClass(padding_ZeroPadding2D);
//# sourceMappingURL=padding.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/pooling.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Pooling Layers.
*/
/**
* 2D pooling.
* @param x
* @param poolSize
* @param stridesdes strides. Defaults to [1, 1].
* @param padding padding. Defaults to 'valid'.
* @param dataFormat data format. Defaults to 'channelsLast'.
* @param poolMode Mode of pooling. Defaults to 'max'.
* @returns Result of the 2D pooling.
*/
function pool2d(x, poolSize, strides, padding, dataFormat, poolMode) {
return Object(dist["tidy"])(() => {
checkDataFormat(dataFormat);
checkPoolMode(poolMode);
checkPaddingMode(padding);
if (strides == null) {
strides = [1, 1];
}
if (padding == null) {
padding = "valid";
}
if (dataFormat == null) {
dataFormat = imageDataFormat();
}
if (poolMode == null) {
poolMode = "max";
}
// TODO(cais): Remove the preprocessing step once deeplearn.js supports
// dataFormat as an input argument.
x = preprocessConv2DInput(x, dataFormat); // x is NHWC after preprocessing.
let y;
const paddingString = padding === "same" ? "same" : "valid";
if (poolMode === "max") {
// TODO(cais): Rank check?
y = dist["maxPool"](x, poolSize, strides, paddingString);
} else {
// 'avg'
// TODO(cais): Check the dtype and rank of x and give clear error message
// if those are incorrect.
y = dist["avgPool"](
// TODO(cais): Rank check?
x,
poolSize,
strides,
paddingString
);
}
if (dataFormat === "channelsFirst") {
y = dist["transpose"](y, [0, 3, 1, 2]); // NHWC -> NCHW.
}
return y;
});
}
/**
* 3D pooling.
* @param x
* @param poolSize. Default to [1, 1, 1].
* @param strides strides. Defaults to [1, 1, 1].
* @param padding padding. Defaults to 'valid'.
* @param dataFormat data format. Defaults to 'channelsLast'.
* @param poolMode Mode of pooling. Defaults to 'max'.
* @returns Result of the 3D pooling.
*/
function pool3d(x, poolSize, strides, padding, dataFormat, poolMode) {
return Object(dist["tidy"])(() => {
checkDataFormat(dataFormat);
checkPoolMode(poolMode);
checkPaddingMode(padding);
if (strides == null) {
strides = [1, 1, 1];
}
if (padding == null) {
padding = "valid";
}
if (dataFormat == null) {
dataFormat = imageDataFormat();
}
if (poolMode == null) {
poolMode = "max";
}
// x is NDHWC after preprocessing.
x = preprocessConv3DInput(x, dataFormat);
let y;
const paddingString = padding === "same" ? "same" : "valid";
if (poolMode === "max") {
y = dist["maxPool3d"](x, poolSize, strides, paddingString);
} else {
// 'avg'
y = dist["avgPool3d"](x, poolSize, strides, paddingString);
}
if (dataFormat === "channelsFirst") {
y = dist["transpose"](y, [0, 4, 1, 2, 3]); // NDHWC -> NCDHW.
}
return y;
});
}
/**
* Abstract class for different pooling 1D layers.
*/
class pooling_Pooling1D extends topology_Layer {
/**
*
* @param args Parameters for the Pooling layer.
*
* config.poolSize defaults to 2.
*/
constructor(args) {
if (args.poolSize == null) {
args.poolSize = 2;
}
super(args);
if (typeof args.poolSize === "number") {
this.poolSize = [args.poolSize];
} else if (
Array.isArray(args.poolSize) &&
args.poolSize.length === 1 &&
typeof args.poolSize[0] === "number"
) {
this.poolSize = args.poolSize;
} else {
throw new ValueError(
`poolSize for 1D convolutional layer must be a number or an ` +
`Array of a single number, but received ` +
`${JSON.stringify(args.poolSize)}`
);
}
assertPositiveInteger(this.poolSize, "poolSize");
if (args.strides == null) {
this.strides = this.poolSize;
} else {
if (typeof args.strides === "number") {
this.strides = [args.strides];
} else if (
Array.isArray(args.strides) &&
args.strides.length === 1 &&
typeof args.strides[0] === "number"
) {
this.strides = args.strides;
} else {
throw new ValueError(
`strides for 1D convolutional layer must be a number or an ` +
`Array of a single number, but received ` +
`${JSON.stringify(args.strides)}`
);
}
}
assertPositiveInteger(this.strides, "strides");
this.padding = args.padding == null ? "valid" : args.padding;
checkPaddingMode(this.padding);
this.inputSpec = [new InputSpec({ ndim: 3 })];
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const length = convOutputLength(
inputShape[1],
this.poolSize[0],
this.padding,
this.strides[0]
);
return [inputShape[0], length, inputShape[2]];
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
// Add dummy last dimension.
inputs = expandDims(getExactlyOneTensor(inputs), 2);
const output = this.poolingFunction(
getExactlyOneTensor(inputs),
[this.poolSize[0], 1],
[this.strides[0], 1],
this.padding,
"channelsLast"
);
// Remove dummy last dimension.
return dist["squeeze"](output, [2]);
});
}
getConfig() {
const config = {
poolSize: this.poolSize,
padding: this.padding,
strides: this.strides,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
class pooling_MaxPooling1D extends pooling_Pooling1D {
constructor(args) {
super(args);
}
poolingFunction(inputs, poolSize, strides, padding, dataFormat) {
checkDataFormat(dataFormat);
checkPaddingMode(padding);
return pool2d(inputs, poolSize, strides, padding, dataFormat, "max");
}
}
/** @nocollapse */
pooling_MaxPooling1D.className = "MaxPooling1D";
dist["serialization"].registerClass(pooling_MaxPooling1D);
class pooling_AveragePooling1D extends pooling_Pooling1D {
constructor(args) {
super(args);
}
poolingFunction(inputs, poolSize, strides, padding, dataFormat) {
checkDataFormat(dataFormat);
checkPaddingMode(padding);
return pool2d(inputs, poolSize, strides, padding, dataFormat, "avg");
}
}
/** @nocollapse */
pooling_AveragePooling1D.className = "AveragePooling1D";
dist["serialization"].registerClass(pooling_AveragePooling1D);
/**
* Abstract class for different pooling 2D layers.
*/
class pooling_Pooling2D extends topology_Layer {
constructor(args) {
if (args.poolSize == null) {
args.poolSize = [2, 2];
}
super(args);
this.poolSize = Array.isArray(args.poolSize)
? args.poolSize
: [args.poolSize, args.poolSize];
if (args.strides == null) {
this.strides = this.poolSize;
} else if (Array.isArray(args.strides)) {
if (args.strides.length !== 2) {
throw new ValueError(
`If the strides property of a 2D pooling layer is an Array, ` +
`it is expected to have a length of 2, but received length ` +
`${args.strides.length}.`
);
}
this.strides = args.strides;
} else {
// `config.strides` is a number.
this.strides = [args.strides, args.strides];
}
assertPositiveInteger(this.poolSize, "poolSize");
assertPositiveInteger(this.strides, "strides");
this.padding = args.padding == null ? "valid" : args.padding;
this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
checkDataFormat(this.dataFormat);
checkPaddingMode(this.padding);
this.inputSpec = [new InputSpec({ ndim: 4 })];
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
let rows = this.dataFormat === "channelsFirst" ? inputShape[2] : inputShape[1];
let cols = this.dataFormat === "channelsFirst" ? inputShape[3] : inputShape[2];
rows = convOutputLength(rows, this.poolSize[0], this.padding, this.strides[0]);
cols = convOutputLength(cols, this.poolSize[1], this.padding, this.strides[1]);
if (this.dataFormat === "channelsFirst") {
return [inputShape[0], inputShape[1], rows, cols];
} else {
return [inputShape[0], rows, cols, inputShape[3]];
}
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
return this.poolingFunction(
getExactlyOneTensor(inputs),
this.poolSize,
this.strides,
this.padding,
this.dataFormat
);
});
}
getConfig() {
const config = {
poolSize: this.poolSize,
padding: this.padding,
strides: this.strides,
dataFormat: this.dataFormat,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
class pooling_MaxPooling2D extends pooling_Pooling2D {
constructor(args) {
super(args);
}
poolingFunction(inputs, poolSize, strides, padding, dataFormat) {
checkDataFormat(dataFormat);
checkPaddingMode(padding);
return pool2d(inputs, poolSize, strides, padding, dataFormat, "max");
}
}
/** @nocollapse */
pooling_MaxPooling2D.className = "MaxPooling2D";
dist["serialization"].registerClass(pooling_MaxPooling2D);
class pooling_AveragePooling2D extends pooling_Pooling2D {
constructor(args) {
super(args);
}
poolingFunction(inputs, poolSize, strides, padding, dataFormat) {
checkDataFormat(dataFormat);
checkPaddingMode(padding);
return pool2d(inputs, poolSize, strides, padding, dataFormat, "avg");
}
}
/** @nocollapse */
pooling_AveragePooling2D.className = "AveragePooling2D";
dist["serialization"].registerClass(pooling_AveragePooling2D);
/**
* Abstract class for different pooling 3D layers.
*/
class pooling_Pooling3D extends topology_Layer {
constructor(args) {
if (args.poolSize == null) {
args.poolSize = [2, 2, 2];
}
super(args);
this.poolSize = Array.isArray(args.poolSize)
? args.poolSize
: [args.poolSize, args.poolSize, args.poolSize];
if (args.strides == null) {
this.strides = this.poolSize;
} else if (Array.isArray(args.strides)) {
if (args.strides.length !== 3) {
throw new ValueError(
`If the strides property of a 3D pooling layer is an Array, ` +
`it is expected to have a length of 3, but received length ` +
`${args.strides.length}.`
);
}
this.strides = args.strides;
} else {
// `config.strides` is a number.
this.strides = [args.strides, args.strides, args.strides];
}
assertPositiveInteger(this.poolSize, "poolSize");
assertPositiveInteger(this.strides, "strides");
this.padding = args.padding == null ? "valid" : args.padding;
this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
checkDataFormat(this.dataFormat);
checkPaddingMode(this.padding);
this.inputSpec = [new InputSpec({ ndim: 5 })];
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
let depths = this.dataFormat === "channelsFirst" ? inputShape[2] : inputShape[1];
let rows = this.dataFormat === "channelsFirst" ? inputShape[3] : inputShape[2];
let cols = this.dataFormat === "channelsFirst" ? inputShape[4] : inputShape[3];
depths = convOutputLength(depths, this.poolSize[0], this.padding, this.strides[0]);
rows = convOutputLength(rows, this.poolSize[1], this.padding, this.strides[1]);
cols = convOutputLength(cols, this.poolSize[2], this.padding, this.strides[2]);
if (this.dataFormat === "channelsFirst") {
return [inputShape[0], inputShape[1], depths, rows, cols];
} else {
return [inputShape[0], depths, rows, cols, inputShape[4]];
}
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
this.invokeCallHook(inputs, kwargs);
return this.poolingFunction(
getExactlyOneTensor(inputs),
this.poolSize,
this.strides,
this.padding,
this.dataFormat
);
});
}
getConfig() {
const config = {
poolSize: this.poolSize,
padding: this.padding,
strides: this.strides,
dataFormat: this.dataFormat,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
class pooling_MaxPooling3D extends pooling_Pooling3D {
constructor(args) {
super(args);
}
poolingFunction(inputs, poolSize, strides, padding, dataFormat) {
checkDataFormat(dataFormat);
checkPaddingMode(padding);
return pool3d(inputs, poolSize, strides, padding, dataFormat, "max");
}
}
/** @nocollapse */
pooling_MaxPooling3D.className = "MaxPooling3D";
dist["serialization"].registerClass(pooling_MaxPooling3D);
class pooling_AveragePooling3D extends pooling_Pooling3D {
constructor(args) {
super(args);
}
poolingFunction(inputs, poolSize, strides, padding, dataFormat) {
checkDataFormat(dataFormat);
checkPaddingMode(padding);
return pool3d(inputs, poolSize, strides, padding, dataFormat, "avg");
}
}
/** @nocollapse */
pooling_AveragePooling3D.className = "AveragePooling3D";
dist["serialization"].registerClass(pooling_AveragePooling3D);
/**
* Abstract class for different global pooling 1D layers.
*/
class pooling_GlobalPooling1D extends topology_Layer {
constructor(args) {
super(args);
this.inputSpec = [new InputSpec({ ndim: 3 })];
}
computeOutputShape(inputShape) {
return [inputShape[0], inputShape[2]];
}
call(inputs, kwargs) {
throw new NotImplementedError();
}
}
class pooling_GlobalAveragePooling1D extends pooling_GlobalPooling1D {
constructor(args) {
super(args || {});
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
const input = getExactlyOneTensor(inputs);
return dist["mean"](input, 1);
});
}
}
/** @nocollapse */
pooling_GlobalAveragePooling1D.className = "GlobalAveragePooling1D";
dist["serialization"].registerClass(pooling_GlobalAveragePooling1D);
class pooling_GlobalMaxPooling1D extends pooling_GlobalPooling1D {
constructor(args) {
super(args || {});
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
const input = getExactlyOneTensor(inputs);
return dist["max"](input, 1);
});
}
}
/** @nocollapse */
pooling_GlobalMaxPooling1D.className = "GlobalMaxPooling1D";
dist["serialization"].registerClass(pooling_GlobalMaxPooling1D);
/**
* Abstract class for different global pooling 2D layers.
*/
class pooling_GlobalPooling2D extends topology_Layer {
constructor(args) {
super(args);
this.dataFormat = args.dataFormat == null ? "channelsLast" : args.dataFormat;
checkDataFormat(this.dataFormat);
this.inputSpec = [new InputSpec({ ndim: 4 })];
}
computeOutputShape(inputShape) {
inputShape = inputShape;
if (this.dataFormat === "channelsLast") {
return [inputShape[0], inputShape[3]];
} else {
return [inputShape[0], inputShape[1]];
}
}
call(inputs, kwargs) {
throw new NotImplementedError();
}
getConfig() {
const config = { dataFormat: this.dataFormat };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
class pooling_GlobalAveragePooling2D extends pooling_GlobalPooling2D {
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
const input = getExactlyOneTensor(inputs);
if (this.dataFormat === "channelsLast") {
return dist["mean"](input, [1, 2]);
} else {
return dist["mean"](input, [2, 3]);
}
});
}
}
/** @nocollapse */
pooling_GlobalAveragePooling2D.className = "GlobalAveragePooling2D";
dist["serialization"].registerClass(pooling_GlobalAveragePooling2D);
class pooling_GlobalMaxPooling2D extends pooling_GlobalPooling2D {
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
const input = getExactlyOneTensor(inputs);
if (this.dataFormat === "channelsLast") {
return dist["max"](input, [1, 2]);
} else {
return dist["max"](input, [2, 3]);
}
});
}
}
/** @nocollapse */
pooling_GlobalMaxPooling2D.className = "GlobalMaxPooling2D";
dist["serialization"].registerClass(pooling_GlobalMaxPooling2D);
//# sourceMappingURL=pooling.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/recurrent.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Recurrent Neural Network Layers.
*/
/**
* Standardize `apply()` args to a single list of tensor inputs.
*
* When running a model loaded from file, the input tensors `initialState` and
* `constants` are passed to `RNN.apply()` as part of `inputs` instead of the
* dedicated kwargs fields. `inputs` consists of
* `[inputs, initialState0, initialState1, ..., constant0, constant1]` in this
* case.
* This method makes sure that arguments are
* separated and that `initialState` and `constants` are `Array`s of tensors
* (or None).
*
* @param inputs Tensor or `Array` of tensors.
* @param initialState Tensor or `Array` of tensors or `null`/`undefined`.
* @param constants Tensor or `Array` of tensors or `null`/`undefined`.
* @returns An object consisting of
* inputs: A tensor.
* initialState: `Array` of tensors or `null`.
* constants: `Array` of tensors or `null`.
* @throws ValueError, if `inputs` is an `Array` but either `initialState` or
* `constants` is provided.
*/
function standardizeArgs(inputs, initialState, constants, numConstants) {
if (Array.isArray(inputs)) {
if (initialState != null || constants != null) {
throw new ValueError(
"When inputs is an array, neither initialState or constants " + "should be provided"
);
}
if (numConstants != null) {
constants = inputs.slice(inputs.length - numConstants, inputs.length);
inputs = inputs.slice(0, inputs.length - numConstants);
}
if (inputs.length > 1) {
initialState = inputs.slice(1, inputs.length);
}
inputs = inputs[0];
}
function toListOrNull(x) {
if (x == null || Array.isArray(x)) {
return x;
} else {
return [x];
}
}
initialState = toListOrNull(initialState);
constants = toListOrNull(constants);
return { inputs, initialState, constants };
}
/**
* Iterates over the time dimension of a tensor.
*
* @param stepFunction RNN step function.
* Parameters:
* inputs: tensor with shape `[samples, ...]` (no time dimension),
* representing input for the batch of samples at a certain time step.
* states: an Array of tensors.
* Returns:
* outputs: tensor with shape `[samples, outputDim]` (no time dimension).
* newStates: list of tensors, same length and shapes as `states`. The first
* state in the list must be the output tensor at the previous timestep.
* @param inputs Tensor of temporal data of shape `[samples, time, ...]` (at
* least 3D).
* @param initialStates Tensor with shape `[samples, outputDim]` (no time
* dimension), containing the initial values of the states used in the step
* function.
* @param goBackwards If `true`, do the iteration over the time dimension in
* reverse order and return the reversed sequence.
* @param mask Binary tensor with shape `[sample, time, 1]`, with a zero for
* every element that is masked.
* @param constants An Array of constant values passed at each step.
* @param unroll Whether to unroll the RNN or to use a symbolic loop. *Not*
* applicable to this imperative deeplearn.js backend. Its value is ignored.
* @param needPerStepOutputs Whether the per-step outputs are to be
* concatenated into a single tensor and returned (as the second return
* value). Default: `false`. This arg is included so that the relatively
* expensive concatenation of the stepwise outputs can be omitted unless
* the stepwise outputs need to be kept (e.g., for an LSTM layer of which
* `returnSequence` is `true`.)
* @returns An Array: `[lastOutput, outputs, newStates]`.
* lastOutput: the lastest output of the RNN, of shape `[samples, ...]`.
* outputs: tensor with shape `[samples, time, ...]` where each entry
* `output[s, t]` is the output of the step function at time `t` for sample
* `s`. This return value is provided if and only if the
* `needPerStepOutputs` is set as `true`. If it is set as `false`, this
* return value will be `undefined`.
* newStates: Array of tensors, latest states returned by the step function,
* of shape `(samples, ...)`.
* @throws ValueError If input dimension is less than 3.
*
* TODO(nielsene): This needs to be tidy-ed.
*/
function rnn(
stepFunction,
inputs,
initialStates,
goBackwards = false,
mask,
constants,
unroll = false,
needPerStepOutputs = false
) {
return dist["tidy"](() => {
const ndim = inputs.shape.length;
if (ndim < 3) {
throw new ValueError(`Input should be at least 3D, but is ${ndim}D.`);
}
// Transpose to time-major, i.e., from [batch, time, ...] to [time, batch,
// ...].
const axes = [1, 0].concat(range(2, ndim));
inputs = dist["transpose"](inputs, axes);
if (constants != null) {
throw new NotImplementedError(
"The rnn() functoin of the deeplearn.js backend does not support " + "constants yet."
);
}
// Porting Note: the unroll option is ignored by the imperative backend.
if (unroll) {
console.warn(
"Backend rnn(): the unroll = true option is not applicable to the " +
"imperative deeplearn.js backend."
);
}
if (mask != null) {
mask = mask.asType("bool").asType("float32");
if (mask.rank === ndim - 1) {
mask = dist["expandDims"](mask, -1);
}
mask = dist["transpose"](mask, axes);
}
if (goBackwards) {
inputs = dist["reverse"](inputs, 0);
if (mask != null) {
mask = dist["reverse"](mask, 0);
}
}
// Porting Note: PyKeras with TensorFlow backend uses a symbolic loop
// (tf.while_loop). But for the imperative deeplearn.js backend, we just
// use the usual TypeScript control flow to iterate over the time steps in
// the inputs.
// Porting Note: PyKeras patches a "_use_learning_phase" attribute to
// outputs.
// This is not idiomatic in TypeScript. The info regarding whether we are
// in a learning (i.e., training) phase for RNN is passed in a different
// way.
const perStepOutputs = [];
let lastOutput;
let states = initialStates;
const timeSteps = inputs.shape[0];
const perStepInputs = dist["unstack"](inputs);
let perStepMasks;
if (mask != null) {
perStepMasks = dist["unstack"](mask);
}
for (let t = 0; t < timeSteps; ++t) {
const currentInput = perStepInputs[t];
const stepOutputs = dist["tidy"](() => stepFunction(currentInput, states));
if (mask == null) {
lastOutput = stepOutputs[0];
states = stepOutputs[1];
} else {
const maskedOutputs = dist["tidy"](() => {
const stepMask = perStepMasks[t];
const negStepMask = dist["onesLike"](stepMask).sub(stepMask);
// TODO(cais): Would tfc.where() be better for performance?
const output = stepOutputs[0].mul(stepMask).add(states[0].mul(negStepMask));
const newStates = states.map((state, i) => {
return stepOutputs[1][i].mul(stepMask).add(state.mul(negStepMask));
});
return { output, newStates };
});
lastOutput = maskedOutputs.output;
states = maskedOutputs.newStates;
}
if (needPerStepOutputs) {
perStepOutputs.push(lastOutput);
}
}
let outputs;
if (needPerStepOutputs) {
const axis = 1;
outputs = dist["stack"](perStepOutputs, axis);
}
return [lastOutput, outputs, states];
});
}
class recurrent_RNN extends topology_Layer {
constructor(args) {
super(args);
let cell;
if (args.cell == null) {
throw new ValueError("cell property is missing for the constructor of RNN.");
} else if (Array.isArray(args.cell)) {
cell = new recurrent_StackedRNNCells({ cells: args.cell });
} else {
cell = args.cell;
}
if (cell.stateSize == null) {
throw new ValueError(
"The RNN cell should have an attribute `stateSize` (tuple of " +
"integers, one integer per RNN state)."
);
}
this.cell = cell;
this.returnSequences = args.returnSequences == null ? false : args.returnSequences;
this.returnState = args.returnState == null ? false : args.returnState;
this.goBackwards = args.goBackwards == null ? false : args.goBackwards;
this._stateful = args.stateful == null ? false : args.stateful;
this.unroll = args.unroll == null ? false : args.unroll;
this.supportsMasking = true;
this.inputSpec = [new InputSpec({ ndim: 3 })];
this.stateSpec = null;
this.states_ = null;
// TODO(cais): Add constantsSpec and numConstants.
this.numConstants = null;
// TODO(cais): Look into the use of initial_state in the kwargs of the
// constructor.
this.keptStates = [];
}
// Porting Note: This is the equivalent of `RNN.states` property getter in
// PyKeras.
getStates() {
if (this.states_ == null) {
const numStates = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
return range(0, numStates).map((x) => null);
} else {
return this.states_;
}
}
// Porting Note: This is the equivalent of the `RNN.states` property setter in
// PyKeras.
setStates(states) {
this.states_ = states;
}
computeOutputShape(inputShape) {
if (isArrayOfShapes(inputShape)) {
inputShape = inputShape[0];
}
inputShape = inputShape;
// TODO(cais): Remove the casting once stacked RNN cells become supported.
let stateSize = this.cell.stateSize;
if (!Array.isArray(stateSize)) {
stateSize = [stateSize];
}
const outputDim = stateSize[0];
let outputShape;
if (this.returnSequences) {
outputShape = [inputShape[0], inputShape[1], outputDim];
} else {
outputShape = [inputShape[0], outputDim];
}
if (this.returnState) {
const stateShape = [];
for (const dim of stateSize) {
stateShape.push([inputShape[0], dim]);
}
return [outputShape].concat(stateShape);
} else {
return outputShape;
}
}
computeMask(inputs, mask) {
return dist["tidy"](() => {
if (Array.isArray(mask)) {
mask = mask[0];
}
const outputMask = this.returnSequences ? mask : null;
if (this.returnState) {
const stateMask = this.states.map((s) => null);
return [outputMask].concat(stateMask);
} else {
return outputMask;
}
});
}
/**
* Get the current state tensors of the RNN.
*
* If the state hasn't been set, return an array of `null`s of the correct
* length.
*/
get states() {
if (this.states_ == null) {
const numStates = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
const output = [];
for (let i = 0; i < numStates; ++i) {
output.push(null);
}
return output;
} else {
return this.states_;
}
}
set states(s) {
this.states_ = s;
}
build(inputShape) {
// Note inputShape will be an Array of Shapes of initial states and
// constants if these are passed in apply().
const constantShape = null;
if (this.numConstants != null) {
throw new NotImplementedError("Constants support is not implemented in RNN yet.");
}
if (isArrayOfShapes(inputShape)) {
inputShape = inputShape[0];
}
inputShape = inputShape;
const batchSize = this.stateful ? inputShape[0] : null;
const inputDim = inputShape[inputShape.length - 1];
this.inputSpec[0] = new InputSpec({ shape: [batchSize, null, inputDim] });
// Allow cell (if RNNCell Layer) to build before we set or validate
// stateSpec.
const stepInputShape = [inputShape[0]].concat(inputShape.slice(2));
if (constantShape != null) {
throw new NotImplementedError("Constants support is not implemented in RNN yet.");
} else {
this.cell.build(stepInputShape);
}
// Set or validate stateSpec.
let stateSize;
if (Array.isArray(this.cell.stateSize)) {
stateSize = this.cell.stateSize;
} else {
stateSize = [this.cell.stateSize];
}
if (this.stateSpec != null) {
if (
!dist["util"].arraysEqual(
this.stateSpec.map((spec) => spec.shape[spec.shape.length - 1]),
stateSize
)
) {
throw new ValueError(
`An initialState was passed that is not compatible with ` +
`cell.stateSize. Received stateSpec=${this.stateSpec}; ` +
`However cell.stateSize is ${this.cell.stateSize}`
);
}
} else {
this.stateSpec = stateSize.map((dim) => new InputSpec({ shape: [null, dim] }));
}
if (this.stateful) {
this.resetStates();
}
}
/**
* Reset the state tensors of the RNN.
*
* If the `states` argument is `undefined` or `null`, will set the
* state tensor(s) of the RNN to all-zero tensors of the appropriate
* shape(s).
*
* If `states` is provided, will set the state tensors of the RNN to its
* value.
*
* @param states Optional externally-provided initial states.
* @param training Whether this call is done during training. For stateful
* RNNs, this affects whether the old states are kept or discarded. In
* particular, if `training` is `true`, the old states will be kept so
* that subsequent backpropgataion through time (BPTT) may work properly.
* Else, the old states will be discarded.
*/
resetStates(states, training = false) {
Object(dist["tidy"])(() => {
if (!this.stateful) {
throw new AttributeError(
"Cannot call resetStates() on an RNN Layer that is not stateful."
);
}
const batchSize = this.inputSpec[0].shape[0];
if (batchSize == null) {
throw new ValueError(
"If an RNN is stateful, it needs to know its batch size. Specify " +
"the batch size of your input tensors: \n" +
"- If using a Sequential model, specify the batch size by " +
"passing a `batchInputShape` option to your first layer.\n" +
"- If using the functional API, specify the batch size by " +
"passing a `batchShape` option to your Input layer."
);
}
// Initialize state if null.
if (this.states_ == null) {
if (Array.isArray(this.cell.stateSize)) {
this.states_ = this.cell.stateSize.map((dim) => dist["zeros"]([batchSize, dim]));
} else {
this.states_ = [dist["zeros"]([batchSize, this.cell.stateSize])];
}
} else if (states == null) {
// Dispose old state tensors.
dist["dispose"](this.states_);
// For stateful RNNs, fully dispose kept old states.
if (this.keptStates != null) {
dist["dispose"](this.keptStates);
this.keptStates = [];
}
if (Array.isArray(this.cell.stateSize)) {
this.states_ = this.cell.stateSize.map((dim) => dist["zeros"]([batchSize, dim]));
} else {
this.states_[0] = dist["zeros"]([batchSize, this.cell.stateSize]);
}
} else {
if (!Array.isArray(states)) {
states = [states];
}
if (states.length !== this.states_.length) {
throw new ValueError(
`Layer ${this.name} expects ${this.states_.length} state(s), ` +
`but it received ${states.length} state value(s). Input ` +
`received: ${states}`
);
}
if (training === true) {
// Store old state tensors for complete disposal later, i.e., during
// the next no-arg call to this method. We do not dispose the old
// states immediately because that BPTT (among other things) require
// them.
this.keptStates.push(this.states_.slice());
} else {
dist["dispose"](this.states_);
}
for (let index = 0; index < this.states_.length; ++index) {
const value = states[index];
const dim = Array.isArray(this.cell.stateSize)
? this.cell.stateSize[index]
: this.cell.stateSize;
const expectedShape = [batchSize, dim];
if (!dist["util"].arraysEqual(value.shape, expectedShape)) {
throw new ValueError(
`State ${index} is incompatible with layer ${this.name}: ` +
`expected shape=${expectedShape}, received shape=${value.shape}`
);
}
this.states_[index] = value;
}
}
this.states_ = this.states_.map((state) => dist["keep"](state.clone()));
});
}
apply(inputs, kwargs) {
// TODO(cais): Figure out whether initialState is in kwargs or inputs.
let initialState = kwargs == null ? null : kwargs["initialState"];
let constants = kwargs == null ? null : kwargs["constants"];
if (kwargs == null) {
kwargs = {};
}
const standardized = standardizeArgs(inputs, initialState, constants, this.numConstants);
inputs = standardized.inputs;
initialState = standardized.initialState;
constants = standardized.constants;
// If any of `initial_state` or `constants` are specified and are
// `tf.SymbolicTensor`s, then add them to the inputs and temporarily modify
// the input_spec to include them.
let additionalInputs = [];
let additionalSpecs = [];
if (initialState != null) {
kwargs["initialState"] = initialState;
additionalInputs = additionalInputs.concat(initialState);
this.stateSpec = [];
for (const state of initialState) {
this.stateSpec.push(new InputSpec({ shape: state.shape }));
}
// TODO(cais): Use the following instead.
// this.stateSpec = initialState.map(state => new InputSpec({shape:
// state.shape}));
additionalSpecs = additionalSpecs.concat(this.stateSpec);
}
if (constants != null) {
kwargs["constants"] = constants;
additionalInputs = additionalInputs.concat(constants);
// TODO(cais): Add this.constantsSpec.
this.numConstants = constants.length;
}
const isTensor = additionalInputs[0] instanceof topology_SymbolicTensor;
if (isTensor) {
// Compute full input spec, including state and constants.
const fullInput = [inputs].concat(additionalInputs);
const fullInputSpec = this.inputSpec.concat(additionalSpecs);
// Perform the call with temporarily replaced inputSpec.
const originalInputSpec = this.inputSpec;
this.inputSpec = fullInputSpec;
const output = super.apply(fullInput, kwargs);
this.inputSpec = originalInputSpec;
return output;
} else {
return super.apply(inputs, kwargs);
}
}
// tslint:disable-next-line:no-any
call(inputs, kwargs) {
// Input shape: `[samples, time (padded with zeros), input_dim]`.
// Note that the .build() method of subclasses **must** define
// this.inputSpec and this.stateSpec owith complete input shapes.
return Object(dist["tidy"])(() => {
const mask = kwargs == null ? null : kwargs["mask"];
const training = kwargs == null ? null : kwargs["training"];
let initialState = kwargs == null ? null : kwargs["initialState"];
inputs = getExactlyOneTensor(inputs);
if (initialState == null) {
if (this.stateful) {
initialState = this.states_;
} else {
initialState = this.getInitialState(inputs);
}
}
const numStates = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
if (initialState.length !== numStates) {
throw new ValueError(
`RNN Layer has ${numStates} state(s) but was passed ` +
`${initialState.length} initial state(s).`
);
}
if (this.unroll) {
console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");
}
const cellCallKwargs = { training };
// TODO(cais): Add support for constants.
const step = (inputs, states) => {
// `inputs` and `states` are concatenated to form a single `Array` of
// `tf.Tensor`s as the input to `cell.call()`.
const outputs = this.cell.call([inputs].concat(states), cellCallKwargs);
// Marshall the return value into output and new states.
return [outputs[0], outputs.slice(1)];
};
// TODO(cais): Add support for constants.
const rnnOutputs = rnn(
step,
inputs,
initialState,
this.goBackwards,
mask,
null,
this.unroll,
this.returnSequences
);
const lastOutput = rnnOutputs[0];
const outputs = rnnOutputs[1];
const states = rnnOutputs[2];
if (this.stateful) {
this.resetStates(states, training);
}
const output = this.returnSequences ? outputs : lastOutput;
// TODO(cais): Porperty set learning phase flag.
if (this.returnState) {
return [output].concat(states);
} else {
return output;
}
});
}
getInitialState(inputs) {
return Object(dist["tidy"])(() => {
// Build an all-zero tensor of shape [samples, outputDim].
// [Samples, timeSteps, inputDim].
let initialState = dist["zeros"](inputs.shape);
// [Samples].
initialState = dist["sum"](initialState, [1, 2]);
initialState = expandDims(initialState); // [Samples, 1].
if (Array.isArray(this.cell.stateSize)) {
return this.cell.stateSize.map((dim) =>
dim > 1 ? tile(initialState, [1, dim]) : initialState
);
} else {
return this.cell.stateSize > 1
? [tile(initialState, [1, this.cell.stateSize])]
: [initialState];
}
});
}
get trainableWeights() {
if (!this.trainable) {
return [];
}
// Porting Note: In TypeScript, `this` is always an instance of `Layer`.
return this.cell.trainableWeights;
}
get nonTrainableWeights() {
// Porting Note: In TypeScript, `this` is always an instance of `Layer`.
if (!this.trainable) {
return this.cell.weights;
}
return this.cell.nonTrainableWeights;
}
setFastWeightInitDuringBuild(value) {
super.setFastWeightInitDuringBuild(value);
if (this.cell != null) {
this.cell.setFastWeightInitDuringBuild(value);
}
}
getConfig() {
const config = {
returnSequences: this.returnSequences,
returnState: this.returnState,
goBackwards: this.goBackwards,
stateful: this.stateful,
unroll: this.unroll,
};
if (this.numConstants != null) {
config["numConstants"] = this.numConstants;
}
const cellConfig = this.cell.getConfig();
config["cell"] = {
className: this.cell.getClassName(),
config: cellConfig,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
/** @nocollapse */
static fromConfig(cls, config, customObjects = {}) {
const cellConfig = config["cell"];
const cell = deserialize(cellConfig, customObjects);
return new cls(Object.assign(config, { cell }));
}
}
/** @nocollapse */
recurrent_RNN.className = "RNN";
dist["serialization"].registerClass(recurrent_RNN);
/**
* An RNNCell layer.
*/
// Porting Note: This is a common parent class for RNN cells. There is no
// equivalent of this in PyKeras. Having a common parent class forgoes the
// need for `has_attr(cell, ...)` checks or its TypeScript equivalent.
/** @doc {heading: 'Layers', subheading: 'Classes'} */
class recurrent_RNNCell extends topology_Layer {}
class recurrent_SimpleRNNCell extends recurrent_RNNCell {
constructor(args) {
super(args);
this.DEFAULT_ACTIVATION = "tanh";
this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal";
this.DEFAULT_BIAS_INITIALIZER = "zeros";
this.units = args.units;
assertPositiveInteger(this.units, `units`);
this.activation = getActivation(
args.activation == null ? this.DEFAULT_ACTIVATION : args.activation
);
this.useBias = args.useBias == null ? true : args.useBias;
this.kernelInitializer = getInitializer(
args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER
);
this.recurrentInitializer = getInitializer(
args.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER
);
this.biasInitializer = getInitializer(
args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER
);
this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);
this.biasRegularizer = getRegularizer(args.biasRegularizer);
this.kernelConstraint = getConstraint(args.kernelConstraint);
this.recurrentConstraint = getConstraint(args.recurrentConstraint);
this.biasConstraint = getConstraint(args.biasConstraint);
this.dropout = min([1, max([0, args.dropout == null ? 0 : args.dropout])]);
this.recurrentDropout = min([
1,
max([0, args.recurrentDropout == null ? 0 : args.recurrentDropout]),
]);
this.stateSize = this.units;
this.dropoutMask = null;
this.recurrentDropoutMask = null;
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
// TODO(cais): Use regularizer.
this.kernel = this.addWeight(
"kernel",
[inputShape[inputShape.length - 1], this.units],
null,
this.kernelInitializer,
this.kernelRegularizer,
true,
this.kernelConstraint
);
this.recurrentKernel = this.addWeight(
"recurrent_kernel",
[this.units, this.units],
null,
this.recurrentInitializer,
this.recurrentRegularizer,
true,
this.recurrentConstraint
);
if (this.useBias) {
this.bias = this.addWeight(
"bias",
[this.units],
null,
this.biasInitializer,
this.biasRegularizer,
true,
this.biasConstraint
);
} else {
this.bias = null;
}
this.built = true;
}
// Porting Note: PyKeras' equivalent of this method takes two tensor inputs:
// `inputs` and `states`. Here, the two tensors are combined into an
// `Tensor[]` Array as the first input argument.
// Similarly, PyKeras' equivalent of this method returns two values:
// `output` and `[output]`. Here the two are combined into one length-2
// `Tensor[]`, consisting of `output` repeated.
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = inputs;
if (inputs.length !== 2) {
throw new ValueError(`SimpleRNNCell expects 2 input Tensors, got ${inputs.length}.`);
}
let prevOutput = inputs[1];
inputs = inputs[0];
const training = kwargs["training"] == null ? false : kwargs["training"];
if (0 < this.dropout && this.dropout < 1 && this.dropoutMask == null) {
this.dropoutMask = generateDropoutMask(
() => dist["onesLike"](inputs),
this.dropout,
training
);
}
if (
0 < this.recurrentDropout &&
this.recurrentDropout < 1 &&
this.recurrentDropoutMask == null
) {
this.recurrentDropoutMask = generateDropoutMask(
() => dist["onesLike"](prevOutput),
this.recurrentDropout,
training
);
}
let h;
const dpMask = this.dropoutMask;
const recDpMask = this.recurrentDropoutMask;
if (dpMask != null) {
h = dot(dist["mul"](inputs, dpMask), this.kernel.read());
} else {
h = dot(inputs, this.kernel.read());
}
if (this.bias != null) {
h = biasAdd(h, this.bias.read());
}
if (recDpMask != null) {
prevOutput = dist["mul"](prevOutput, recDpMask);
}
let output = dist["add"](h, dot(prevOutput, this.recurrentKernel.read()));
if (this.activation != null) {
output = this.activation.apply(output);
}
// TODO(cais): Properly set learning phase on output tensor?
return [output, output];
});
}
getConfig() {
const config = {
units: this.units,
activation: serializeActivation(this.activation),
useBias: this.useBias,
kernelInitializer: serializeInitializer(this.kernelInitializer),
recurrentInitializer: serializeInitializer(this.recurrentInitializer),
biasInitializer: serializeInitializer(this.biasInitializer),
kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
biasRegularizer: serializeRegularizer(this.biasRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
kernelConstraint: serializeConstraint(this.kernelConstraint),
recurrentConstraint: serializeConstraint(this.recurrentConstraint),
biasConstraint: serializeConstraint(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
recurrent_SimpleRNNCell.className = "SimpleRNNCell";
dist["serialization"].registerClass(recurrent_SimpleRNNCell);
class recurrent_SimpleRNN extends recurrent_RNN {
constructor(args) {
args.cell = new recurrent_SimpleRNNCell(args);
super(args);
// TODO(cais): Add activityRegularizer.
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
if (this.cell.dropoutMask != null) {
dist["dispose"](this.cell.dropoutMask);
this.cell.dropoutMask = null;
}
if (this.cell.recurrentDropoutMask != null) {
dist["dispose"](this.cell.recurrentDropoutMask);
this.cell.recurrentDropoutMask = null;
}
const mask = kwargs == null ? null : kwargs["mask"];
const training = kwargs == null ? null : kwargs["training"];
const initialState = kwargs == null ? null : kwargs["initialState"];
return super.call(inputs, { mask, training, initialState });
});
}
// TODO(cais): Research possibility of refactoring out the tedious all
// the getters that delegate to `this.cell` below.
get units() {
return this.cell.units;
}
get activation() {
return this.cell.activation;
}
get useBias() {
return this.cell.useBias;
}
get kernelInitializer() {
return this.cell.kernelInitializer;
}
get recurrentInitializer() {
return this.cell.recurrentInitializer;
}
get biasInitializer() {
return this.cell.biasInitializer;
}
get kernelRegularizer() {
return this.cell.kernelRegularizer;
}
get recurrentRegularizer() {
return this.cell.recurrentRegularizer;
}
get biasRegularizer() {
return this.cell.biasRegularizer;
}
get kernelConstraint() {
return this.cell.kernelConstraint;
}
get recurrentConstraint() {
return this.cell.recurrentConstraint;
}
get biasConstraint() {
return this.cell.biasConstraint;
}
get dropout() {
return this.cell.dropout;
}
get recurrentDropout() {
return this.cell.recurrentDropout;
}
getConfig() {
const config = {
units: this.units,
activation: serializeActivation(this.activation),
useBias: this.useBias,
kernelInitializer: serializeInitializer(this.kernelInitializer),
recurrentInitializer: serializeInitializer(this.recurrentInitializer),
biasInitializer: serializeInitializer(this.biasInitializer),
kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
biasRegularizer: serializeRegularizer(this.biasRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
kernelConstraint: serializeConstraint(this.kernelConstraint),
recurrentConstraint: serializeConstraint(this.recurrentConstraint),
biasConstraint: serializeConstraint(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout,
};
const baseConfig = super.getConfig();
delete baseConfig["cell"];
Object.assign(config, baseConfig);
return config;
}
/** @nocollapse */
static fromConfig(cls, config) {
return new cls(config);
}
}
/** @nocollapse */
recurrent_SimpleRNN.className = "SimpleRNN";
dist["serialization"].registerClass(recurrent_SimpleRNN);
class recurrent_GRUCell extends recurrent_RNNCell {
constructor(args) {
super(args);
this.DEFAULT_ACTIVATION = "tanh";
this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid";
this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal";
this.DEFAULT_BIAS_INITIALIZER = "zeros";
if (args.resetAfter) {
throw new ValueError(`GRUCell does not support reset_after parameter set to true.`);
}
this.units = args.units;
assertPositiveInteger(this.units, "units");
this.activation = getActivation(
args.activation === undefined ? this.DEFAULT_ACTIVATION : args.activation
);
this.recurrentActivation = getActivation(
args.recurrentActivation === undefined
? this.DEFAULT_RECURRENT_ACTIVATION
: args.recurrentActivation
);
this.useBias = args.useBias == null ? true : args.useBias;
this.kernelInitializer = getInitializer(
args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER
);
this.recurrentInitializer = getInitializer(
args.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER
);
this.biasInitializer = getInitializer(
args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER
);
this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);
this.biasRegularizer = getRegularizer(args.biasRegularizer);
this.kernelConstraint = getConstraint(args.kernelConstraint);
this.recurrentConstraint = getConstraint(args.recurrentConstraint);
this.biasConstraint = getConstraint(args.biasConstraint);
this.dropout = min([1, max([0, args.dropout == null ? 0 : args.dropout])]);
this.recurrentDropout = min([
1,
max([0, args.recurrentDropout == null ? 0 : args.recurrentDropout]),
]);
this.implementation = args.implementation;
this.stateSize = this.units;
this.dropoutMask = null;
this.recurrentDropoutMask = null;
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const inputDim = inputShape[inputShape.length - 1];
this.kernel = this.addWeight(
"kernel",
[inputDim, this.units * 3],
null,
this.kernelInitializer,
this.kernelRegularizer,
true,
this.kernelConstraint
);
this.recurrentKernel = this.addWeight(
"recurrent_kernel",
[this.units, this.units * 3],
null,
this.recurrentInitializer,
this.recurrentRegularizer,
true,
this.recurrentConstraint
);
if (this.useBias) {
this.bias = this.addWeight(
"bias",
[this.units * 3],
null,
this.biasInitializer,
this.biasRegularizer,
true,
this.biasConstraint
);
} else {
this.bias = null;
}
// Porting Notes: Unlike the PyKeras implementation, we perform slicing
// of the weights and bias in the call() method, at execution time.
this.built = true;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = inputs;
if (inputs.length !== 2) {
throw new ValueError(
`GRUCell expects 2 input Tensors (inputs, h, c), got ` + `${inputs.length}.`
);
}
const training = kwargs["training"] == null ? false : kwargs["training"];
let hTMinus1 = inputs[1]; // Previous memory state.
inputs = inputs[0];
// Note: For superior performance, TensorFlow.js always uses
// implementation 2, regardless of the actual value of
// config.implementation.
if (0 < this.dropout && this.dropout < 1 && this.dropoutMask == null) {
this.dropoutMask = generateDropoutMask(
() => dist["onesLike"](inputs),
this.dropout,
training,
3
);
}
if (
0 < this.recurrentDropout &&
this.recurrentDropout < 1 &&
this.recurrentDropoutMask == null
) {
this.recurrentDropoutMask = generateDropoutMask(
() => dist["onesLike"](hTMinus1),
this.recurrentDropout,
training,
3
);
}
const dpMask = this.dropoutMask;
const recDpMask = this.recurrentDropoutMask;
let z;
let r;
let hh;
if (0 < this.dropout && this.dropout < 1) {
inputs = dist["mul"](inputs, dpMask[0]);
}
let matrixX = dot(inputs, this.kernel.read());
if (this.useBias) {
matrixX = biasAdd(matrixX, this.bias.read());
}
if (0 < this.recurrentDropout && this.recurrentDropout < 1) {
hTMinus1 = dist["mul"](hTMinus1, recDpMask[0]);
}
const recurrentKernelValue = this.recurrentKernel.read();
const [rk1, rk2] = dist["split"](
recurrentKernelValue,
[2 * this.units, this.units],
recurrentKernelValue.rank - 1
);
const matrixInner = dot(hTMinus1, rk1);
const [xZ, xR, xH] = dist["split"](matrixX, 3, matrixX.rank - 1);
const [recurrentZ, recurrentR] = dist["split"](matrixInner, 2, matrixInner.rank - 1);
z = this.recurrentActivation.apply(dist["add"](xZ, recurrentZ));
r = this.recurrentActivation.apply(dist["add"](xR, recurrentR));
const recurrentH = dot(dist["mul"](r, hTMinus1), rk2);
hh = this.activation.apply(dist["add"](xH, recurrentH));
const h = dist["add"](
dist["mul"](z, hTMinus1),
dist["mul"](dist["add"](1, dist["neg"](z)), hh)
);
// TODO(cais): Add use_learning_phase flag properly.
return [h, h];
});
}
getConfig() {
const config = {
units: this.units,
activation: serializeActivation(this.activation),
recurrentActivation: serializeActivation(this.recurrentActivation),
useBias: this.useBias,
kernelInitializer: serializeInitializer(this.kernelInitializer),
recurrentInitializer: serializeInitializer(this.recurrentInitializer),
biasInitializer: serializeInitializer(this.biasInitializer),
kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
biasRegularizer: serializeRegularizer(this.biasRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
kernelConstraint: serializeConstraint(this.kernelConstraint),
recurrentConstraint: serializeConstraint(this.recurrentConstraint),
biasConstraint: serializeConstraint(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout,
implementation: this.implementation,
resetAfter: false,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
recurrent_GRUCell.className = "GRUCell";
dist["serialization"].registerClass(recurrent_GRUCell);
class recurrent_GRU extends recurrent_RNN {
constructor(args) {
if (args.implementation === 0) {
console.warn(
"`implementation=0` has been deprecated, and now defaults to " +
"`implementation=1`. Please update your layer call."
);
}
args.cell = new recurrent_GRUCell(args);
super(args);
// TODO(cais): Add activityRegularizer.
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
if (this.cell.dropoutMask != null) {
dist["dispose"](this.cell.dropoutMask);
this.cell.dropoutMask = null;
}
if (this.cell.recurrentDropoutMask != null) {
dist["dispose"](this.cell.recurrentDropoutMask);
this.cell.recurrentDropoutMask = null;
}
const mask = kwargs == null ? null : kwargs["mask"];
const training = kwargs == null ? null : kwargs["training"];
const initialState = kwargs == null ? null : kwargs["initialState"];
return super.call(inputs, { mask, training, initialState });
});
}
get units() {
return this.cell.units;
}
get activation() {
return this.cell.activation;
}
get recurrentActivation() {
return this.cell.recurrentActivation;
}
get useBias() {
return this.cell.useBias;
}
get kernelInitializer() {
return this.cell.kernelInitializer;
}
get recurrentInitializer() {
return this.cell.recurrentInitializer;
}
get biasInitializer() {
return this.cell.biasInitializer;
}
get kernelRegularizer() {
return this.cell.kernelRegularizer;
}
get recurrentRegularizer() {
return this.cell.recurrentRegularizer;
}
get biasRegularizer() {
return this.cell.biasRegularizer;
}
get kernelConstraint() {
return this.cell.kernelConstraint;
}
get recurrentConstraint() {
return this.cell.recurrentConstraint;
}
get biasConstraint() {
return this.cell.biasConstraint;
}
get dropout() {
return this.cell.dropout;
}
get recurrentDropout() {
return this.cell.recurrentDropout;
}
get implementation() {
return this.cell.implementation;
}
getConfig() {
const config = {
units: this.units,
activation: serializeActivation(this.activation),
recurrentActivation: serializeActivation(this.recurrentActivation),
useBias: this.useBias,
kernelInitializer: serializeInitializer(this.kernelInitializer),
recurrentInitializer: serializeInitializer(this.recurrentInitializer),
biasInitializer: serializeInitializer(this.biasInitializer),
kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
biasRegularizer: serializeRegularizer(this.biasRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
kernelConstraint: serializeConstraint(this.kernelConstraint),
recurrentConstraint: serializeConstraint(this.recurrentConstraint),
biasConstraint: serializeConstraint(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout,
implementation: this.implementation,
resetAfter: false,
};
const baseConfig = super.getConfig();
delete baseConfig["cell"];
Object.assign(config, baseConfig);
return config;
}
/** @nocollapse */
static fromConfig(cls, config) {
if (config["implmentation"] === 0) {
config["implementation"] = 1;
}
return new cls(config);
}
}
/** @nocollapse */
recurrent_GRU.className = "GRU";
dist["serialization"].registerClass(recurrent_GRU);
class recurrent_LSTMCell extends recurrent_RNNCell {
constructor(args) {
super(args);
this.DEFAULT_ACTIVATION = "tanh";
this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid";
this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal";
this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal";
this.DEFAULT_BIAS_INITIALIZER = "zeros";
this.units = args.units;
assertPositiveInteger(this.units, "units");
this.activation = getActivation(
args.activation === undefined ? this.DEFAULT_ACTIVATION : args.activation
);
this.recurrentActivation = getActivation(
args.recurrentActivation === undefined
? this.DEFAULT_RECURRENT_ACTIVATION
: args.recurrentActivation
);
this.useBias = args.useBias == null ? true : args.useBias;
this.kernelInitializer = getInitializer(
args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER
);
this.recurrentInitializer = getInitializer(
args.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER
);
this.biasInitializer = getInitializer(
args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER
);
this.unitForgetBias = args.unitForgetBias;
this.kernelRegularizer = getRegularizer(args.kernelRegularizer);
this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);
this.biasRegularizer = getRegularizer(args.biasRegularizer);
this.kernelConstraint = getConstraint(args.kernelConstraint);
this.recurrentConstraint = getConstraint(args.recurrentConstraint);
this.biasConstraint = getConstraint(args.biasConstraint);
this.dropout = min([1, max([0, args.dropout == null ? 0 : args.dropout])]);
this.recurrentDropout = min([
1,
max([0, args.recurrentDropout == null ? 0 : args.recurrentDropout]),
]);
this.implementation = args.implementation;
this.stateSize = [this.units, this.units];
this.dropoutMask = null;
this.recurrentDropoutMask = null;
}
build(inputShape) {
var _a;
inputShape = getExactlyOneShape(inputShape);
const inputDim = inputShape[inputShape.length - 1];
this.kernel = this.addWeight(
"kernel",
[inputDim, this.units * 4],
null,
this.kernelInitializer,
this.kernelRegularizer,
true,
this.kernelConstraint
);
this.recurrentKernel = this.addWeight(
"recurrent_kernel",
[this.units, this.units * 4],
null,
this.recurrentInitializer,
this.recurrentRegularizer,
true,
this.recurrentConstraint
);
let biasInitializer;
if (this.useBias) {
if (this.unitForgetBias) {
const capturedBiasInit = this.biasInitializer;
const capturedUnits = this.units;
biasInitializer = new ((_a = class CustomInit extends initializers_Initializer {
apply(shape, dtype) {
// TODO(cais): More informative variable names?
const bI = capturedBiasInit.apply([capturedUnits]);
const bF = new initializers_Ones().apply([capturedUnits]);
const bCAndH = capturedBiasInit.apply([capturedUnits * 2]);
return concatAlongFirstAxis(concatAlongFirstAxis(bI, bF), bCAndH);
}
}),
/** @nocollapse */
(_a.className = "CustomInit"),
_a)();
} else {
biasInitializer = this.biasInitializer;
}
this.bias = this.addWeight(
"bias",
[this.units * 4],
null,
biasInitializer,
this.biasRegularizer,
true,
this.biasConstraint
);
} else {
this.bias = null;
}
// Porting Notes: Unlike the PyKeras implementation, we perform slicing
// of the weights and bias in the call() method, at execution time.
this.built = true;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
const training = kwargs["training"] == null ? false : kwargs["training"];
inputs = inputs;
if (inputs.length !== 3) {
throw new ValueError(
`LSTMCell expects 3 input Tensors (inputs, h, c), got ` + `${inputs.length}.`
);
}
let hTMinus1 = inputs[1]; // Previous memory state.
const cTMinus1 = inputs[2]; // Previous carry state.
inputs = inputs[0];
if (0 < this.dropout && this.dropout < 1 && this.dropoutMask == null) {
this.dropoutMask = generateDropoutMask(
() => dist["onesLike"](inputs),
this.dropout,
training,
4
);
}
if (
0 < this.recurrentDropout &&
this.recurrentDropout < 1 &&
this.recurrentDropoutMask == null
) {
this.recurrentDropoutMask = generateDropoutMask(
() => dist["onesLike"](hTMinus1),
this.recurrentDropout,
training,
4
);
}
const dpMask = this.dropoutMask;
const recDpMask = this.recurrentDropoutMask;
// Note: For superior performance, TensorFlow.js always uses
// implementation 2 regardless of the actual value of
// config.implementation.
let i;
let f;
let c;
let o;
if (0 < this.dropout && this.dropout < 1) {
inputs = dist["mul"](inputs, dpMask[0]);
}
let z = dot(inputs, this.kernel.read());
if (0 < this.recurrentDropout && this.recurrentDropout < 1) {
hTMinus1 = dist["mul"](hTMinus1, recDpMask[0]);
}
z = dist["add"](z, dot(hTMinus1, this.recurrentKernel.read()));
if (this.useBias) {
z = biasAdd(z, this.bias.read());
}
const [z0, z1, z2, z3] = dist["split"](z, 4, z.rank - 1);
i = this.recurrentActivation.apply(z0);
f = this.recurrentActivation.apply(z1);
c = dist["add"](dist["mul"](f, cTMinus1), dist["mul"](i, this.activation.apply(z2)));
o = this.recurrentActivation.apply(z3);
const h = dist["mul"](o, this.activation.apply(c));
// TODO(cais): Add use_learning_phase flag properly.
return [h, h, c];
});
}
getConfig() {
const config = {
units: this.units,
activation: serializeActivation(this.activation),
recurrentActivation: serializeActivation(this.recurrentActivation),
useBias: this.useBias,
kernelInitializer: serializeInitializer(this.kernelInitializer),
recurrentInitializer: serializeInitializer(this.recurrentInitializer),
biasInitializer: serializeInitializer(this.biasInitializer),
unitForgetBias: this.unitForgetBias,
kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
biasRegularizer: serializeRegularizer(this.biasRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
kernelConstraint: serializeConstraint(this.kernelConstraint),
recurrentConstraint: serializeConstraint(this.recurrentConstraint),
biasConstraint: serializeConstraint(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout,
implementation: this.implementation,
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
}
/** @nocollapse */
recurrent_LSTMCell.className = "LSTMCell";
dist["serialization"].registerClass(recurrent_LSTMCell);
class recurrent_LSTM extends recurrent_RNN {
constructor(args) {
if (args.implementation === 0) {
console.warn(
"`implementation=0` has been deprecated, and now defaults to " +
"`implementation=1`. Please update your layer call."
);
}
args.cell = new recurrent_LSTMCell(args);
super(args);
// TODO(cais): Add activityRegularizer.
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
if (this.cell.dropoutMask != null) {
dist["dispose"](this.cell.dropoutMask);
this.cell.dropoutMask = null;
}
if (this.cell.recurrentDropoutMask != null) {
dist["dispose"](this.cell.recurrentDropoutMask);
this.cell.recurrentDropoutMask = null;
}
const mask = kwargs == null ? null : kwargs["mask"];
const training = kwargs == null ? null : kwargs["training"];
const initialState = kwargs == null ? null : kwargs["initialState"];
return super.call(inputs, { mask, training, initialState });
});
}
get units() {
return this.cell.units;
}
get activation() {
return this.cell.activation;
}
get recurrentActivation() {
return this.cell.recurrentActivation;
}
get useBias() {
return this.cell.useBias;
}
get kernelInitializer() {
return this.cell.kernelInitializer;
}
get recurrentInitializer() {
return this.cell.recurrentInitializer;
}
get biasInitializer() {
return this.cell.biasInitializer;
}
get unitForgetBias() {
return this.cell.unitForgetBias;
}
get kernelRegularizer() {
return this.cell.kernelRegularizer;
}
get recurrentRegularizer() {
return this.cell.recurrentRegularizer;
}
get biasRegularizer() {
return this.cell.biasRegularizer;
}
get kernelConstraint() {
return this.cell.kernelConstraint;
}
get recurrentConstraint() {
return this.cell.recurrentConstraint;
}
get biasConstraint() {
return this.cell.biasConstraint;
}
get dropout() {
return this.cell.dropout;
}
get recurrentDropout() {
return this.cell.recurrentDropout;
}
get implementation() {
return this.cell.implementation;
}
getConfig() {
const config = {
units: this.units,
activation: serializeActivation(this.activation),
recurrentActivation: serializeActivation(this.recurrentActivation),
useBias: this.useBias,
kernelInitializer: serializeInitializer(this.kernelInitializer),
recurrentInitializer: serializeInitializer(this.recurrentInitializer),
biasInitializer: serializeInitializer(this.biasInitializer),
unitForgetBias: this.unitForgetBias,
kernelRegularizer: serializeRegularizer(this.kernelRegularizer),
recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),
biasRegularizer: serializeRegularizer(this.biasRegularizer),
activityRegularizer: serializeRegularizer(this.activityRegularizer),
kernelConstraint: serializeConstraint(this.kernelConstraint),
recurrentConstraint: serializeConstraint(this.recurrentConstraint),
biasConstraint: serializeConstraint(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout,
implementation: this.implementation,
};
const baseConfig = super.getConfig();
delete baseConfig["cell"];
Object.assign(config, baseConfig);
return config;
}
/** @nocollapse */
static fromConfig(cls, config) {
if (config["implmentation"] === 0) {
config["implementation"] = 1;
}
return new cls(config);
}
}
/** @nocollapse */
recurrent_LSTM.className = "LSTM";
dist["serialization"].registerClass(recurrent_LSTM);
class recurrent_StackedRNNCells extends recurrent_RNNCell {
constructor(args) {
super(args);
this.cells = args.cells;
}
get stateSize() {
// States are a flat list in reverse order of the cell stack.
// This allows perserving the requirement `stack.statesize[0] ===
// outputDim`. E.g., states of a 2-layer LSTM would be `[h2, c2, h1, c1]`,
// assuming one LSTM has states `[h, c]`.
const stateSize = [];
for (const cell of this.cells.slice().reverse()) {
if (Array.isArray(cell.stateSize)) {
stateSize.push(...cell.stateSize);
} else {
stateSize.push(cell.stateSize);
}
}
return stateSize;
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
inputs = inputs;
let states = inputs.slice(1);
// Recover per-cell states.
const nestedStates = [];
for (const cell of this.cells.slice().reverse()) {
if (Array.isArray(cell.stateSize)) {
nestedStates.push(states.splice(0, cell.stateSize.length));
} else {
nestedStates.push(states.splice(0, 1));
}
}
nestedStates.reverse();
// Call the cells in order and store the returned states.
const newNestedStates = [];
let callInputs;
for (let i = 0; i < this.cells.length; ++i) {
const cell = this.cells[i];
states = nestedStates[i];
// TODO(cais): Take care of constants.
if (i === 0) {
callInputs = [inputs[0]].concat(states);
} else {
callInputs = [callInputs[0]].concat(states);
}
callInputs = cell.call(callInputs, kwargs);
newNestedStates.push(callInputs.slice(1));
}
// Format the new states as a flat list in reverse cell order.
states = [];
for (const cellStates of newNestedStates.slice().reverse()) {
states.push(...cellStates);
}
return [callInputs[0]].concat(states);
});
}
build(inputShape) {
if (isArrayOfShapes(inputShape)) {
// TODO(cais): Take care of input constants.
// const constantShape = inputShape.slice(1);
inputShape = inputShape[0];
}
inputShape = inputShape;
let outputDim;
this.cells.forEach((cell, i) => {
nameScope(`RNNCell_${i}`, () => {
// TODO(cais): Take care of input constants.
cell.build(inputShape);
if (Array.isArray(cell.stateSize)) {
outputDim = cell.stateSize[0];
} else {
outputDim = cell.stateSize;
}
inputShape = [inputShape[0], outputDim];
});
});
this.built = true;
}
getConfig() {
const cellConfigs = [];
for (const cell of this.cells) {
cellConfigs.push({
className: cell.getClassName(),
config: cell.getConfig(),
});
}
const config = { cells: cellConfigs };
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
/** @nocollapse */
static fromConfig(cls, config, customObjects = {}) {
const cells = [];
for (const cellConfig of config["cells"]) {
cells.push(deserialize(cellConfig, customObjects));
}
return new cls({ cells });
}
get trainableWeights() {
if (!this.trainable) {
return [];
}
const weights = [];
for (const cell of this.cells) {
weights.push(...cell.trainableWeights);
}
return weights;
}
get nonTrainableWeights() {
const weights = [];
for (const cell of this.cells) {
weights.push(...cell.nonTrainableWeights);
}
if (!this.trainable) {
const trainableWeights = [];
for (const cell of this.cells) {
trainableWeights.push(...cell.trainableWeights);
}
return trainableWeights.concat(weights);
}
return weights;
}
/**
* Retrieve the weights of a the model.
*
* @returns A flat `Array` of `tf.Tensor`s.
*/
getWeights() {
const weights = [];
for (const cell of this.cells) {
weights.push(...cell.weights);
}
return batchGetValue(weights);
}
/**
* Set the weights of the model.
*
* @param weights An `Array` of `tf.Tensor`s with shapes and types matching
* the output of `getWeights()`.
*/
setWeights(weights) {
const tuples = [];
for (const cell of this.cells) {
const numParams = cell.weights.length;
const inputWeights = weights.splice(numParams);
for (let i = 0; i < cell.weights.length; ++i) {
tuples.push([cell.weights[i], inputWeights[i]]);
}
}
batchSetValue(tuples);
}
}
/** @nocollapse */
recurrent_StackedRNNCells.className = "StackedRNNCells";
dist["serialization"].registerClass(recurrent_StackedRNNCells);
function generateDropoutMask(ones, rate, training = null, count = 1) {
function droppedInputs() {
return dropout(ones(), rate);
}
if (count > 1) {
const mask = [];
for (let i = 0; i < count; i++) {
mask.push(inTrainPhase(droppedInputs, ones, training));
}
return mask.map((m) => dist["keep"](m.clone()));
} else {
return dist["keep"](inTrainPhase(droppedInputs, ones, training).clone());
}
}
//# sourceMappingURL=recurrent.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/layers/wrappers.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Layers that augment the functionality of a base layer.
*/
/**
* Abstract wrapper base class.
*
* Wrappers take another layer and augment it in various ways.
* Do not use this class as a layer, it is only an abstract base class.
* Two usable wrappers are the `TimeDistributed` and `Bidirectional` wrappers.
*/
class wrappers_Wrapper extends topology_Layer {
constructor(args) {
// Porting Note: In PyKeras, `self.layer` is set prior to the calling
// `super()`. But we can't do that here due to TypeScript's restriction.
// See: https://github.com/Microsoft/TypeScript/issues/8277
// As a result, we have to add checks in `get trainable()` and
// `set trainable()` below in order to prevent using `this.layer` when
// its value is `undefined`. The super constructor does use the getter
// and the setter of `this.layer`.
super(args);
this.layer = args.layer;
}
build(inputShape) {
this.built = true;
}
// TODO(cais): Implement activityRegularizer getter.
get trainable() {
// Porting Note: the check of `this.layer` here is necessary due to the
// way the `constructor` of this class is written (see Porting Note
// above).
if (this.layer != null) {
return this.layer.trainable;
} else {
return false;
}
}
set trainable(value) {
// Porting Note: the check of `this.layer` here is necessary due to the
// way the `constructor` of this class is written (see Porting Note
// above).
if (this.layer != null) {
this.layer.trainable = value;
}
}
get trainableWeights() {
return this.layer.trainableWeights;
}
// TODO(cais): Implement setter for trainableWeights.
get nonTrainableWeights() {
return this.layer.nonTrainableWeights;
}
// TODO(cais): Implement setter for nonTrainableWeights.
get updates() {
// tslint:disable-next-line:no-any
return this.layer._updates;
}
// TODO(cais): Implement getUpdatesFor().
get losses() {
return this.layer.losses;
}
// TODO(cais): Implement getLossesFor().
getWeights() {
return this.layer.getWeights();
}
setWeights(weights) {
this.layer.setWeights(weights);
}
getConfig() {
const config = {
layer: {
className: this.layer.getClassName(),
config: this.layer.getConfig(),
},
};
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
setFastWeightInitDuringBuild(value) {
super.setFastWeightInitDuringBuild(value);
if (this.layer != null) {
this.layer.setFastWeightInitDuringBuild(value);
}
}
/** @nocollapse */
static fromConfig(cls, config, customObjects = {}) {
const layerConfig = config["layer"];
const layer = deserialize(layerConfig, customObjects);
delete config["layer"];
const newConfig = { layer };
Object.assign(newConfig, config);
return new cls(newConfig);
}
}
class wrappers_TimeDistributed extends wrappers_Wrapper {
constructor(args) {
super(args);
this.supportsMasking = true;
}
build(inputShape) {
inputShape = getExactlyOneShape(inputShape);
if (inputShape.length < 3) {
throw new ValueError(
`TimeDistributed layer expects an input shape >= 3D, but received ` +
`input shape ${JSON.stringify(inputShape)}`
);
}
this.inputSpec = [{ shape: inputShape }];
const childInputShape = [inputShape[0]].concat(inputShape.slice(2));
if (!this.layer.built) {
this.layer.build(childInputShape);
this.layer.built = true;
}
super.build(inputShape);
}
computeOutputShape(inputShape) {
inputShape = getExactlyOneShape(inputShape);
const childInputShape = [inputShape[0]].concat(inputShape.slice(2));
const childOutputShape = this.layer.computeOutputShape(childInputShape);
const timesteps = inputShape[1];
return [childOutputShape[0], timesteps].concat(childOutputShape.slice(1));
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
// TODO(cais): Add 'training' and 'useLearningPhase' to kwargs.
inputs = getExactlyOneTensor(inputs);
// Porting Note: In tfjs-layers, `inputs` are always concrete tensor
// values. Hence the inputs can't have an undetermined first (batch)
// dimension, which is why we always use the K.rnn approach here.
const step = (inputs, states) => {
// TODO(cais): Add useLearningPhase.
// NOTE(cais): `layer.call` may return a length-1 array of Tensor in
// some cases (e.g., `layer` is a `Sequential` instance), which is
// why `getExactlyOneTensor` is used below.
const output = getExactlyOneTensor(this.layer.call(inputs, kwargs));
return [output, []];
};
const rnnOutputs = rnn(
step,
inputs,
[],
false /* goBackwards */,
null /* mask */,
null /* constants */,
false /* unroll */,
true /* needPerStepOutputs */
);
const y = rnnOutputs[1];
// TODO(cais): Add activity regularization.
// TODO(cais): Add useLearningPhase.
return y;
});
}
}
/** @nocollapse */
wrappers_TimeDistributed.className = "TimeDistributed";
dist["serialization"].registerClass(wrappers_TimeDistributed);
function checkBidirectionalMergeMode(value) {
checkStringTypeUnionValue(VALID_BIDIRECTIONAL_MERGE_MODES, "BidirectionalMergeMode", value);
}
const DEFAULT_BIDIRECTIONAL_MERGE_MODE = "concat";
class wrappers_Bidirectional extends wrappers_Wrapper {
constructor(args) {
super(args);
// Note: When creating `this.forwardLayer`, the original Layer object
// (`config.layer`) ought to be cloned. This is why we call
// `getConfig()` followed by `deserialize()`. Without this cloning,
// the layer names saved during serialization will incorrectly contain
// the 'forward_' prefix. In Python Keras, this is done using
// `copy.copy` (shallow copy), which does not have a simple equivalent
// in JavaScript. JavaScript's `Object.assign()` does not copy
// methods.
const layerConfig = args.layer.getConfig();
const forwDict = {};
forwDict["className"] = args.layer.getClassName();
forwDict["config"] = layerConfig;
this.forwardLayer = deserialize(forwDict);
layerConfig["goBackwards"] = layerConfig["goBackwards"] === true ? false : true;
const backDict = {};
backDict["className"] = args.layer.getClassName();
backDict["config"] = layerConfig;
this.backwardLayer = deserialize(backDict);
this.forwardLayer.name = "forward_" + this.forwardLayer.name;
this.backwardLayer.name = "backward_" + this.backwardLayer.name;
this.mergeMode =
args.mergeMode === undefined ? DEFAULT_BIDIRECTIONAL_MERGE_MODE : args.mergeMode;
checkBidirectionalMergeMode(this.mergeMode);
if (args.weights) {
throw new NotImplementedError(
"weights support is not implemented for Bidirectional layer yet."
);
}
this._stateful = args.layer.stateful;
this.returnSequences = args.layer.returnSequences;
this.returnState = args.layer.returnState;
this.supportsMasking = true;
this._trainable = true;
this.inputSpec = args.layer.inputSpec;
this.numConstants = null;
}
get trainable() {
return this._trainable;
}
set trainable(value) {
// Porting Note: the check of `this.layer` here is necessary due to the
// way the `constructor` of this class is written (see Porting Note
// above).
this._trainable = value;
if (this.forwardLayer != null) {
this.forwardLayer.trainable = value;
}
if (this.backwardLayer != null) {
this.backwardLayer.trainable = value;
}
}
getWeights() {
return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights());
}
setWeights(weights) {
const numWeights = weights.length;
const numeightsOver2 = Math.floor(numWeights / 2);
this.forwardLayer.setWeights(weights.slice(0, numeightsOver2));
this.backwardLayer.setWeights(weights.slice(numeightsOver2));
}
computeOutputShape(inputShape) {
let layerShapes = this.forwardLayer.computeOutputShape(inputShape);
if (!(Array.isArray(layerShapes) && Array.isArray(layerShapes[0]))) {
layerShapes = [layerShapes];
}
layerShapes = layerShapes;
let outputShape;
let outputShapes;
let stateShape;
if (this.returnState) {
stateShape = layerShapes.slice(1);
outputShape = layerShapes[0];
} else {
outputShape = layerShapes[0];
}
outputShape = outputShape;
if (this.mergeMode === "concat") {
outputShape[outputShape.length - 1] *= 2;
outputShapes = [outputShape];
} else if (this.mergeMode == null) {
outputShapes = [outputShape, outputShape.slice()];
} else {
outputShapes = [outputShape];
}
if (this.returnState) {
if (this.mergeMode == null) {
return outputShapes.concat(stateShape).concat(stateShape.slice());
}
return [outputShape].concat(stateShape).concat(stateShape.slice());
}
return singletonOrArray(outputShapes);
}
apply(inputs, kwargs) {
let initialState = kwargs == null ? null : kwargs["initialState"];
let constants = kwargs == null ? null : kwargs["constants"];
if (kwargs == null) {
kwargs = {};
}
const standardized = standardizeArgs(inputs, initialState, constants, this.numConstants);
inputs = standardized.inputs;
initialState = standardized.initialState;
constants = standardized.constants;
if (Array.isArray(inputs)) {
initialState = inputs.slice(1);
inputs = inputs[0];
}
if ((initialState == null || initialState.length === 0) && constants == null) {
return super.apply(inputs, kwargs);
}
const additionalInputs = [];
const additionalSpecs = [];
if (initialState != null) {
const numStates = initialState.length;
if (numStates % 2 > 0) {
throw new ValueError(
"When passing `initialState` to a Bidrectional RNN, " +
"the state should be an Array containing the states of " +
"the underlying RNNs."
);
}
kwargs["initialState"] = initialState;
additionalInputs.push(...initialState);
const stateSpecs = initialState.map((state) => new InputSpec({ shape: state.shape }));
this.forwardLayer.stateSpec = stateSpecs.slice(0, numStates / 2);
this.backwardLayer.stateSpec = stateSpecs.slice(numStates / 2);
additionalSpecs.push(...stateSpecs);
}
if (constants != null) {
throw new NotImplementedError(
"Support for constants in Bidirectional layers is not " + "implemented yet."
);
}
const isSymbolicTensor = additionalInputs[0] instanceof topology_SymbolicTensor;
for (const tensor of additionalInputs) {
if (tensor instanceof topology_SymbolicTensor !== isSymbolicTensor) {
throw new ValueError(
"The initial state of a Bidirectional layer cannot be " +
"specified as a mix of symbolic and non-symbolic tensors"
);
}
}
if (isSymbolicTensor) {
// Compute the full input and specs, including the states.
const fullInput = [inputs].concat(additionalInputs);
const fullInputSpec = this.inputSpec.concat(additionalSpecs);
// Perform the call temporarily and replace inputSpec.
// Note: with initial states symbolic calls and non-symbolic calls to
// this method differ in how the initial states are passed. For
// symbolic calls, the initial states are passed in the first arg, as
// an Array of SymbolicTensors; for non-symbolic calls, they are
// passed in the second arg as a part of the kwargs. Hence the need to
// temporarily modify inputSpec here.
// TODO(cais): Make refactoring so that this hacky code below is no
// longer needed.
const originalInputSpec = this.inputSpec;
this.inputSpec = fullInputSpec;
const output = super.apply(fullInput, kwargs);
this.inputSpec = originalInputSpec;
return output;
} else {
return super.apply(inputs, kwargs);
}
}
call(inputs, kwargs) {
return Object(dist["tidy"])(() => {
const initialState = kwargs["initialState"];
let y;
let yRev;
if (initialState == null) {
y = this.forwardLayer.call(inputs, kwargs);
yRev = this.backwardLayer.call(inputs, kwargs);
} else {
const forwardState = initialState.slice(0, initialState.length / 2);
const backwardState = initialState.slice(initialState.length / 2);
y = this.forwardLayer.call(
inputs,
Object.assign(kwargs, { initialState: forwardState })
);
yRev = this.backwardLayer.call(
inputs,
Object.assign(kwargs, { initialState: backwardState })
);
}
let states;
if (this.returnState) {
if (Array.isArray(y)) {
states = y.slice(1).concat(yRev.slice(1));
} else {
}
y = y[0];
yRev = yRev[0];
}
if (this.returnSequences) {
yRev = dist["reverse"](yRev, 1);
}
let output;
if (this.mergeMode === "concat") {
output = concatenate([y, yRev]);
} else if (this.mergeMode === "sum") {
output = dist["add"](y, yRev);
} else if (this.mergeMode === "ave") {
output = dist["mul"](0.5, dist["add"](y, yRev));
} else if (this.mergeMode === "mul") {
output = dist["mul"](y, yRev);
} else if (this.mergeMode == null) {
output = [y, yRev];
}
// TODO(cais): Properly set learning phase.
if (this.returnState) {
if (this.mergeMode == null) {
return output.concat(states);
}
return [output].concat(states);
}
return output;
});
}
resetStates(states) {
this.forwardLayer.resetStates();
this.backwardLayer.resetStates();
}
build(inputShape) {
nameScope(this.forwardLayer.name, () => {
this.forwardLayer.build(inputShape);
});
nameScope(this.backwardLayer.name, () => {
this.backwardLayer.build(inputShape);
});
this.built = true;
}
computeMask(inputs, mask) {
if (Array.isArray(mask)) {
mask = mask[0];
}
let outputMask;
if (this.returnSequences) {
if (this.mergeMode == null) {
outputMask = [mask, mask];
} else {
outputMask = mask;
}
} else {
if (this.mergeMode == null) {
outputMask = [null, null];
} else {
outputMask = null;
}
}
if (this.returnState) {
const states = this.forwardLayer.states;
const stateMask = states.map((state) => null);
if (Array.isArray(outputMask)) {
return outputMask.concat(stateMask).concat(stateMask);
} else {
return [outputMask].concat(stateMask).concat(stateMask);
}
} else {
return outputMask;
}
}
get trainableWeights() {
return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights);
}
get nonTrainableWeights() {
return this.forwardLayer.nonTrainableWeights.concat(
this.backwardLayer.nonTrainableWeights
);
}
// TODO(cais): Implement constraints().
setFastWeightInitDuringBuild(value) {
super.setFastWeightInitDuringBuild(value);
if (this.forwardLayer != null) {
this.forwardLayer.setFastWeightInitDuringBuild(value);
}
if (this.backwardLayer != null) {
this.backwardLayer.setFastWeightInitDuringBuild(value);
}
}
getConfig() {
const config = {
mergeMode: this.mergeMode,
};
// TODO(cais): Add logic for `numConstants` once the property is added.
const baseConfig = super.getConfig();
Object.assign(config, baseConfig);
return config;
}
/** @nocollapse */
static fromConfig(cls, config) {
const rnnLayer = deserialize(config["layer"]);
delete config["layer"];
// TODO(cais): Add logic for `numConstants` once the property is added.
if (config["numConstants"] != null) {
throw new NotImplementedError(
`Deserialization of a Bidirectional layer with numConstants ` +
`present is not supported yet.`
);
}
// tslint:disable-next-line:no-any
const newConfig = config;
newConfig["layer"] = rnnLayer;
return new cls(newConfig);
}
}
/** @nocollapse */
wrappers_Bidirectional.className = "Bidirectional";
dist["serialization"].registerClass(wrappers_Bidirectional);
//# sourceMappingURL=wrappers.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/exports_layers.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// TODO(cais): Add doc string to all the public static functions in this
// class; include exectuable JavaScript code snippets where applicable
// (b/74074458).
// Input Layer.
/**
* An input layer is an entry point into a `tf.LayersModel`.
*
* `InputLayer` is generated automatically for `tf.Sequential`` models by
* specifying the `inputshape` or `batchInputShape` for the first layer. It
* should not be specified explicitly. However, it can be useful sometimes,
* e.g., when constructing a sequential model from a subset of another
* sequential model's layers. Like the code snippet below shows.
*
* ```js
* // Define a model which simply adds two inputs.
* const model1 = tf.sequential();
* model1.add(tf.layers.dense({inputShape: [4], units: 3, activation: 'relu'}));
* model1.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));
* model1.summary();
* model1.predict(tf.zeros([1, 4])).print();
*
* // Construct another model, reusing the second layer of `model1` while
* // not using the first layer of `model1`. Note that you cannot add the second
* // layer of `model` directly as the first layer of the new sequential model,
* // because doing so will lead to an error related to the fact that the layer
* // is not an input layer. Instead, you need to create an `inputLayer` and add
* // it to the new sequential model before adding the reused layer.
* const model2 = tf.sequential();
* // Use an inputShape that matches the input shape of `model1`'s second
* // layer.
* model2.add(tf.layers.inputLayer({inputShape: [3]}));
* model2.add(model1.layers[1]);
* model2.summary();
* model2.predict(tf.zeros([1, 3])).print();
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Inputs', namespace: 'layers'} */
function exports_layers_inputLayer(args) {
return new input_layer_InputLayer(args);
}
// Advanced Activation Layers.
/**
* Exponetial Linear Unit (ELU).
*
* It follows:
* `f(x) = alpha * (exp(x) - 1.) for x < 0`,
* `f(x) = x for x >= 0`.
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*
* References:
* - [Fast and Accurate Deep Network Learning by Exponential Linear Units
* (ELUs)](https://arxiv.org/abs/1511.07289v1)
*/
/**
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
function exports_layers_elu(args) {
return new advanced_activations_ELU(args);
}
/**
* Rectified Linear Unit activation function.
*
* Input shape:
* Arbitrary. Use the config field `inputShape` (Array of integers, does
* not include the sample axis) when using this layer as the first layer
* in a model.
*
* Output shape:
* Same shape as the input.
*/
/**
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
function reLU(args) {
return new advanced_activations_ReLU(args);
}
/**
* Leaky version of a rectified linear unit.
*
* It allows a small gradient when the unit is not active:
* `f(x) = alpha * x for x < 0.`
* `f(x) = x for x >= 0.`
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*/
/**
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
function leakyReLU(args) {
return new advanced_activations_LeakyReLU(args);
}
/**
* Parameterized version of a leaky rectified linear unit.
*
* It follows
* `f(x) = alpha * x for x < 0.`
* `f(x) = x for x >= 0.`
* wherein `alpha` is a trainable weight.
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*/
/**
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
function prelu(args) {
return new advanced_activations_PReLU(args);
}
/**
* Softmax activation layer.
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*/
/**
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
function softmax(args) {
return new advanced_activations_Softmax(args);
}
/**
* Thresholded Rectified Linear Unit.
*
* It follows:
* `f(x) = x for x > theta`,
* `f(x) = 0 otherwise`.
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*
* References:
* - [Zero-Bias Autoencoders and the Benefits of Co-Adapting
* Features](http://arxiv.org/abs/1402.3337)
*/
/**
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
function thresholdedReLU(args) {
return new advanced_activations_ThresholdedReLU(args);
}
// Convolutional Layers.
/**
* 1D convolution layer (e.g., temporal convolution).
*
* This layer creates a convolution kernel that is convolved
* with the layer input over a single spatial (or temporal) dimension
* to produce a tensor of outputs.
*
* If `use_bias` is True, a bias vector is created and added to the outputs.
*
* If `activation` is not `null`, it is applied to the outputs as well.
*
* When using this layer as the first layer in a model, provide an
* `inputShape` argument `Array` or `null`.
*
* For example, `inputShape` would be:
* - `[10, 128]` for sequences of 10 vectors of 128-dimensional vectors
* - `[null, 128]` for variable-length sequences of 128-dimensional vectors.
*/
/**
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
function exports_layers_conv1d(args) {
return new convolutional_Conv1D(args);
}
/**
* 2D convolution layer (e.g. spatial convolution over images).
*
* This layer creates a convolution kernel that is convolved
* with the layer input to produce a tensor of outputs.
*
* If `useBias` is True, a bias vector is created and added to the outputs.
*
* If `activation` is not `null`, it is applied to the outputs as well.
*
* When using this layer as the first layer in a model,
* provide the keyword argument `inputShape`
* (Array of integers, does not include the sample axis),
* e.g. `inputShape=[128, 128, 3]` for 128x128 RGB pictures
* in `dataFormat='channelsLast'`.
*/
/**
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
function exports_layers_conv2d(args) {
return new convolutional_Conv2D(args);
}
/**
* Transposed convolutional layer (sometimes called Deconvolution).
*
* The need for transposed convolutions generally arises
* from the desire to use a transformation going in the opposite direction of
* a normal convolution, i.e., from something that has the shape of the output
* of some convolution to something that has the shape of its input while
* maintaining a connectivity pattern that is compatible with said
* convolution.
*
* When using this layer as the first layer in a model, provide the
* configuration `inputShape` (`Array` of integers, does not include the
* sample axis), e.g., `inputShape: [128, 128, 3]` for 128x128 RGB pictures in
* `dataFormat: 'channelsLast'`.
*
* Input shape:
* 4D tensor with shape:
* `[batch, channels, rows, cols]` if `dataFormat` is `'channelsFirst'`.
* or 4D tensor with shape
* `[batch, rows, cols, channels]` if `dataFormat` is `'channelsLast`.
*
* Output shape:
* 4D tensor with shape:
* `[batch, filters, newRows, newCols]` if `dataFormat` is
* `'channelsFirst'`. or 4D tensor with shape:
* `[batch, newRows, newCols, filters]` if `dataFormat` is `'channelsLast'`.
*
* References:
* - [A guide to convolution arithmetic for deep
* learning](https://arxiv.org/abs/1603.07285v1)
* - [Deconvolutional
* Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf)
*/
/**
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
function conv2dTranspose(args) {
return new convolutional_Conv2DTranspose(args);
}
/**
* 3D convolution layer (e.g. spatial convolution over volumes).
*
* This layer creates a convolution kernel that is convolved
* with the layer input to produce a tensor of outputs.
*
* If `useBias` is True, a bias vector is created and added to the outputs.
*
* If `activation` is not `null`, it is applied to the outputs as well.
*
* When using this layer as the first layer in a model,
* provide the keyword argument `inputShape`
* (Array of integers, does not include the sample axis),
* e.g. `inputShape=[128, 128, 128, 1]` for 128x128x128 grayscale volumes
* in `dataFormat='channelsLast'`.
*/
/**
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
function exports_layers_conv3d(args) {
return new convolutional_Conv3D(args);
}
/**
* Depthwise separable 2D convolution.
*
* Separable convolution consists of first performing
* a depthwise spatial convolution
* (which acts on each input channel separately)
* followed by a pointwise convolution which mixes together the resulting
* output channels. The `depthMultiplier` argument controls how many
* output channels are generated per input channel in the depthwise step.
*
* Intuitively, separable convolutions can be understood as
* a way to factorize a convolution kernel into two smaller kernels,
* or as an extreme version of an Inception block.
*
* Input shape:
* 4D tensor with shape:
* `[batch, channels, rows, cols]` if data_format='channelsFirst'
* or 4D tensor with shape:
* `[batch, rows, cols, channels]` if data_format='channelsLast'.
*
* Output shape:
* 4D tensor with shape:
* `[batch, filters, newRows, newCols]` if data_format='channelsFirst'
* or 4D tensor with shape:
* `[batch, newRows, newCols, filters]` if data_format='channelsLast'.
* `rows` and `cols` values might have changed due to padding.
*/
/**
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
function separableConv2d(args) {
return new SeparableConv2D(args);
}
/**
* Cropping layer for 2D input (e.g., image).
*
* This layer can crop an input
* at the top, bottom, left and right side of an image tensor.
*
* Input shape:
* 4D tensor with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, rows, cols, channels]`
* - If `data_format` is `"channels_first"`:
* `[batch, channels, rows, cols]`.
*
* Output shape:
* 4D with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, croppedRows, croppedCols, channels]`
* - If `dataFormat` is `"channelsFirst"`:
* `[batch, channels, croppedRows, croppedCols]`.
*
* Examples
* ```js
*
* const model = tf.sequential();
* model.add(tf.layers.cropping2D({cropping:[[2, 2], [2, 2]],
* inputShape: [128, 128, 3]}));
* //now output shape is [batch, 124, 124, 3]
* ```
*/
/**
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
function cropping2D(args) {
return new convolutional_Cropping2D(args);
}
/**
* Upsampling layer for 2D inputs.
*
* Repeats the rows and columns of the data
* by size[0] and size[1] respectively.
*
*
* Input shape:
* 4D tensor with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, rows, cols, channels]`
* - If `dataFormat` is `"channelsFirst"`:
* `[batch, channels, rows, cols]`
*
* Output shape:
* 4D tensor with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, upsampledRows, upsampledCols, channels]`
* - If `dataFormat` is `"channelsFirst"`:
* `[batch, channels, upsampledRows, upsampledCols]`
*
*/
/**
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
function upSampling2d(args) {
return new convolutional_UpSampling2D(args);
}
// Convolutional(depthwise) Layers.
/**
* Depthwise separable 2D convolution.
*
* Depthwise Separable convolutions consists in performing just the first step
* in a depthwise spatial convolution (which acts on each input channel
* separately). The `depthMultplier` argument controls how many output channels
* are generated per input channel in the depthwise step.
*/
/**
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
function exports_layers_depthwiseConv2d(args) {
return new convolutional_depthwise_DepthwiseConv2D(args);
}
// Basic Layers.
/**
* Applies an activation function to an output.
*
* This layer applies element-wise activation function. Other layers, notably
* `dense` can also apply activation functions. Use this isolated activation
* function to extract the values before and after the
* activation. For instance:
*
* ```js
* const input = tf.input({shape: [5]});
* const denseLayer = tf.layers.dense({units: 1});
* const activationLayer = tf.layers.activation({activation: 'relu6'});
*
* // Obtain the output symbolic tensors by applying the layers in order.
* const denseOutput = denseLayer.apply(input);
* const activationOutput = activationLayer.apply(denseOutput);
*
* // Create the model based on the inputs.
* const model = tf.model({
* inputs: input,
* outputs: [denseOutput, activationOutput]
* });
*
* // Collect both outputs and print separately.
* const [denseOut, activationOut] = model.predict(tf.randomNormal([6, 5]));
* denseOut.print();
* activationOut.print();
* ```
*/
/**
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
function exports_layers_activation(args) {
return new core_Activation(args);
}
/**
* Creates a dense (fully connected) layer.
*
* This layer implements the operation:
* `output = activation(dot(input, kernel) + bias)`
*
* `activation` is the element-wise activation function
* passed as the `activation` argument.
*
* `kernel` is a weights matrix created by the layer.
*
* `bias` is a bias vector created by the layer (only applicable if `useBias`
* is `true`).
*
* **Input shape:**
*
* nD `tf.Tensor` with shape: `(batchSize, ..., inputDim)`.
*
* The most common situation would be
* a 2D input with shape `(batchSize, inputDim)`.
*
* **Output shape:**
*
* nD tensor with shape: `(batchSize, ..., units)`.
*
* For instance, for a 2D input with shape `(batchSize, inputDim)`,
* the output would have shape `(batchSize, units)`.
*
* Note: if the input to the layer has a rank greater than 2, then it is
* flattened prior to the initial dot product with the kernel.
*/
/** @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'} */
function dense(args) {
return new core_Dense(args);
}
/**
* Applies
* [dropout](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) to
* the input.
*
* Dropout consists in randomly setting a fraction `rate` of input units to 0 at
* each update during training time, which helps prevent overfitting.
*/
/** @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'} */
function exports_layers_dropout(args) {
return new core_Dropout(args);
}
/**
* Spatial 1D version of Dropout.
*
* This Layer type performs the same function as the Dropout layer, but it drops
* entire 1D feature maps instead of individual elements. For example, if an
* input example consists of 3 timesteps and the feature map for each timestep
* has a size of 4, a `spatialDropout1d` layer may zero out the feature maps
* of the 1st timesteps and 2nd timesteps completely while sparing all feature
* elements of the 3rd timestep.
*
* If adjacent frames (timesteps) are strongly correlated (as is normally the
* case in early convolution layers), regular dropout will not regularize the
* activation and will otherwise just result in merely an effective learning
* rate decrease. In this case, `spatialDropout1d` will help promote
* independence among feature maps and should be used instead.
*
* **Arguments:**
* rate: A floating-point number >=0 and <=1. Fraction of the input elements
* to drop.
*
* **Input shape:**
* 3D tensor with shape `(samples, timesteps, channels)`.
*
* **Output shape:**
* Same as the input shape.
*
* References:
* - [Efficient Object Localization Using Convolutional
* Networks](https://arxiv.org/abs/1411.4280)
*/
/** @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'} */
function spatialDropout1d(args) {
return new SpatialDropout1D(args);
}
/**
* Flattens the input. Does not affect the batch size.
*
* A `Flatten` layer flattens each batch in its inputs to 1D (making the output
* 2D).
*
* For example:
*
* ```js
* const input = tf.input({shape: [4, 3]});
* const flattenLayer = tf.layers.flatten();
* // Inspect the inferred output shape of the flatten layer, which
* // equals `[null, 12]`. The 2nd dimension is 4 * 3, i.e., the result of the
* // flattening. (The 1st dimension is the undermined batch size.)
* console.log(JSON.stringify(flattenLayer.apply(input).shape));
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'} */
function exports_layers_flatten(args) {
return new core_Flatten(args);
}
/**
* Repeats the input n times in a new dimension.
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.repeatVector({n: 4, inputShape: [2]}));
* const x = tf.tensor2d([[10, 20]]);
* // Use the model to do inference on a data point the model hasn't see
* model.predict(x).print();
* // output shape is now [batch, 2, 4]
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'} */
function repeatVector(args) {
return new core_RepeatVector(args);
}
/**
* Reshapes an input to a certain shape.
*
* ```js
* const input = tf.input({shape: [4, 3]});
* const reshapeLayer = tf.layers.reshape({targetShape: [2, 6]});
* // Inspect the inferred output shape of the Reshape layer, which
* // equals `[null, 2, 6]`. (The 1st dimension is the undermined batch size.)
* console.log(JSON.stringify(reshapeLayer.apply(input).shape));
* ```
*
* Input shape:
* Arbitrary, although all dimensions in the input shape must be fixed.
* Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
*
* Output shape:
* [batchSize, targetShape[0], targetShape[1], ...,
* targetShape[targetShape.length - 1]].
*/
/** @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'} */
function reshape(args) {
return new core_Reshape(args);
}
/**
* Permutes the dimensions of the input according to a given pattern.
*
* Useful for, e.g., connecting RNNs and convnets together.
*
* Example:
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.permute({
* dims: [2, 1],
* inputShape: [10, 64]
* }));
* console.log(model.outputShape);
* // Now model's output shape is [null, 64, 10], where null is the
* // unpermuted sample (batch) dimension.
* ```
*
* Input shape:
* Arbitrary. Use the configuration field `inputShape` when using this
* layer as the first layer in a model.
*
* Output shape:
* Same rank as the input shape, but with the dimensions re-ordered (i.e.,
* permuted) according to the `dims` configuration of this layer.
*/
/** @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'} */
function permute(args) {
return new core_Permute(args);
}
/**
* Maps positive integers (indices) into dense vectors of fixed size.
* eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]
*
* **Input shape:** 2D tensor with shape: `[batchSize, sequenceLength]`.
*
* **Output shape:** 3D tensor with shape: `[batchSize, sequenceLength,
* outputDim]`.
*/
/** @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'} */
function embedding(args) {
return new embeddings_Embedding(args);
}
// Merge Layers.
/**
* Layer that performs element-wise addition on an `Array` of inputs.
*
* It takes as input a list of tensors, all of the same shape, and returns a
* single tensor (also of the same shape). The inputs are specified as an
* `Array` when the `apply` method of the `Add` layer instance is called. For
* example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const addLayer = tf.layers.add();
* const sum = addLayer.apply([input1, input2]);
* console.log(JSON.stringify(sum.shape));
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'} */
function exports_layers_add(args) {
return new merge_Add(args);
}
/**
* Layer that performs element-wise averaging on an `Array` of inputs.
*
* It takes as input a list of tensors, all of the same shape, and returns a
* single tensor (also of the same shape). For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const averageLayer = tf.layers.average();
* const average = averageLayer.apply([input1, input2]);
* console.log(JSON.stringify(average.shape));
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'} */
function exports_layers_average(args) {
return new merge_Average(args);
}
/**
* Layer that concatenates an `Array` of inputs.
*
* It takes a list of tensors, all of the same shape except for the
* concatenation axis, and returns a single tensor, the concatenation
* of all inputs. For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 3]});
* const concatLayer = tf.layers.concatenate();
* const output = concatLayer.apply([input1, input2]);
* console.log(JSON.stringify(output.shape));
* // You get [null, 2, 5], with the first dimension as the undetermined batch
* // dimension. The last dimension (5) is the result of concatenating the
* // last dimensions of the inputs (2 and 3).
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'} */
function exports_layers_concatenate(args) {
return new merge_Concatenate(args);
}
/**
* Layer that computes the element-wise maximum an `Array` of inputs.
*
* It takes as input a list of tensors, all of the same shape and returns a
* single tensor (also of the same shape). For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const maxLayer = tf.layers.maximum();
* const max = maxLayer.apply([input1, input2]);
* console.log(JSON.stringify(max.shape));
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'} */
function exports_layers_maximum(args) {
return new merge_Maximum(args);
}
/**
* Layer that computes the element-wise minimum of an `Array` of inputs.
*
* It takes as input a list of tensors, all of the same shape and returns a
* single tensor (also of the same shape). For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const minLayer = tf.layers.minimum();
* const min = minLayer.apply([input1, input2]);
* console.log(JSON.stringify(min.shape));
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'} */
function exports_layers_minimum(args) {
return new merge_Minimum(args);
}
/**
* Layer that multiplies (element-wise) an `Array` of inputs.
*
* It takes as input an Array of tensors, all of the same
* shape, and returns a single tensor (also of the same shape).
* For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const input3 = tf.input({shape: [2, 2]});
* const multiplyLayer = tf.layers.multiply();
* const product = multiplyLayer.apply([input1, input2, input3]);
* console.log(product.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
*/
/** @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'} */
function exports_layers_multiply(args) {
return new merge_Multiply(args);
}
/**
* Layer that computes a dot product between samples in two tensors.
*
* E.g., if applied to a list of two tensors `a` and `b` both of shape
* `[batchSize, n]`, the output will be a tensor of shape `[batchSize, 1]`,
* where each entry at index `[i, 0]` will be the dot product between
* `a[i, :]` and `b[i, :]`.
*
* Example:
*
* ```js
* const dotLayer = tf.layers.dot({axes: -1});
* const x1 = tf.tensor2d([[10, 20], [30, 40]]);
* const x2 = tf.tensor2d([[-1, -2], [-3, -4]]);
*
* // Invoke the layer's apply() method in eager (imperative) mode.
* const y = dotLayer.apply([x1, x2]);
* y.print();
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'} */
function exports_layers_dot(args) {
return new merge_Dot(args);
}
// Normalization Layers.
/**
* Batch normalization layer (Ioffe and Szegedy, 2014).
*
* Normalize the activations of the previous layer at each batch,
* i.e. applies a transformation that maintains the mean activation
* close to 0 and the activation standard deviation close to 1.
*
* Input shape:
* Arbitrary. Use the keyword argument `inputShape` (Array of integers, does
* not include the sample axis) when calling the constructor of this class,
* if this layer is used as a first layer in a model.
*
* Output shape:
* Same shape as input.
*
* References:
* - [Batch Normalization: Accelerating Deep Network Training by Reducing
* Internal Covariate Shift](https://arxiv.org/abs/1502.03167)
*/
/**
* @doc {heading: 'Layers', subheading: 'Normalization', namespace: 'layers'}
*/
function exports_layers_batchNormalization(args) {
return new normalization_BatchNormalization(args);
}
/**
* Layer-normalization layer (Ba et al., 2016).
*
* Normalizes the activations of the previous layer for each given example in a
* batch independently, instead of across a batch like in `batchNormalization`.
* In other words, this layer applies a transformation that maintanis the mean
* activation within each example close to0 and activation variance close to 1.
*
* Input shape:
* Arbitrary. Use the argument `inputShape` when using this layer as the first
* layer in a model.
*
* Output shape:
* Same as input.
*
* References:
* - [Layer Normalization](https://arxiv.org/abs/1607.06450)
*/
/**
* @doc {heading: 'Layers', subheading: 'Normalization', namespace: 'layers'}
*/
function layerNormalization(args) {
return new normalization_LayerNormalization(args);
}
// Padding Layers.
/**
* Zero-padding layer for 2D input (e.g., image).
*
* This layer can add rows and columns of zeros
* at the top, bottom, left and right side of an image tensor.
*
* Input shape:
* 4D tensor with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, rows, cols, channels]`
* - If `data_format` is `"channels_first"`:
* `[batch, channels, rows, cols]`.
*
* Output shape:
* 4D with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, paddedRows, paddedCols, channels]`
* - If `dataFormat` is `"channelsFirst"`:
* `[batch, channels, paddedRows, paddedCols]`.
*/
/** @doc {heading: 'Layers', subheading: 'Padding', namespace: 'layers'} */
function zeroPadding2d(args) {
return new padding_ZeroPadding2D(args);
}
// Pooling Layers.
/**
* Average pooling operation for spatial data.
*
* Input shape: `[batchSize, inLength, channels]`
*
* Output shape: `[batchSize, pooledLength, channels]`
*
* `tf.avgPool1d` is an alias.
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function averagePooling1d(args) {
return new pooling_AveragePooling1D(args);
}
function avgPool1d(args) {
return averagePooling1d(args);
}
// For backwards compatibility.
// See https://github.com/tensorflow/tfjs/issues/152
function avgPooling1d(args) {
return averagePooling1d(args);
}
/**
* Average pooling operation for spatial data.
*
* Input shape:
* - If `dataFormat === CHANNEL_LAST`:
* 4D tensor with shape:
* `[batchSize, rows, cols, channels]`
* - If `dataFormat === CHANNEL_FIRST`:
* 4D tensor with shape:
* `[batchSize, channels, rows, cols]`
*
* Output shape
* - If `dataFormat === CHANNEL_LAST`:
* 4D tensor with shape:
* `[batchSize, pooleRows, pooledCols, channels]`
* - If `dataFormat === CHANNEL_FIRST`:
* 4D tensor with shape:
* `[batchSize, channels, pooleRows, pooledCols]`
*
* `tf.avgPool2d` is an alias.
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function averagePooling2d(args) {
return new pooling_AveragePooling2D(args);
}
function avgPool2d(args) {
return averagePooling2d(args);
}
// For backwards compatibility.
// See https://github.com/tensorflow/tfjs/issues/152
function avgPooling2d(args) {
return averagePooling2d(args);
}
/**
* Average pooling operation for 3D data.
*
* Input shape
* - If `dataFormat === channelsLast`:
* 5D tensor with shape:
* `[batchSize, depths, rows, cols, channels]`
* - If `dataFormat === channelsFirst`:
* 4D tensor with shape:
* `[batchSize, channels, depths, rows, cols]`
*
* Output shape
* - If `dataFormat=channelsLast`:
* 5D tensor with shape:
* `[batchSize, pooledDepths, pooledRows, pooledCols, channels]`
* - If `dataFormat=channelsFirst`:
* 5D tensor with shape:
* `[batchSize, channels, pooledDepths, pooledRows, pooledCols]`
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function averagePooling3d(args) {
return new pooling_AveragePooling3D(args);
}
function avgPool3d(args) {
return averagePooling3d(args);
}
// For backwards compatibility.
// See https://github.com/tensorflow/tfjs/issues/152
function avgPooling3d(args) {
return averagePooling3d(args);
}
/**
* Global average pooling operation for temporal data.
*
* Input Shape: 3D tensor with shape: `[batchSize, steps, features]`.
*
* Output Shape:2D tensor with shape: `[batchSize, features]`.
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function globalAveragePooling1d(args) {
return new pooling_GlobalAveragePooling1D(args);
}
/**
* Global average pooling operation for spatial data.
*
* Input shape:
* - If `dataFormat` is `CHANNEL_LAST`:
* 4D tensor with shape: `[batchSize, rows, cols, channels]`.
* - If `dataFormat` is `CHANNEL_FIRST`:
* 4D tensor with shape: `[batchSize, channels, rows, cols]`.
*
* Output shape:
* 2D tensor with shape: `[batchSize, channels]`.
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function globalAveragePooling2d(args) {
return new pooling_GlobalAveragePooling2D(args);
}
/**
* Global max pooling operation for temporal data.
*
* Input Shape: 3D tensor with shape: `[batchSize, steps, features]`.
*
* Output Shape:2D tensor with shape: `[batchSize, features]`.
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function globalMaxPooling1d(args) {
return new pooling_GlobalMaxPooling1D(args);
}
/**
* Global max pooling operation for spatial data.
*
* Input shape:
* - If `dataFormat` is `CHANNEL_LAST`:
* 4D tensor with shape: `[batchSize, rows, cols, channels]`.
* - If `dataFormat` is `CHANNEL_FIRST`:
* 4D tensor with shape: `[batchSize, channels, rows, cols]`.
*
* Output shape:
* 2D tensor with shape: `[batchSize, channels]`.
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function globalMaxPooling2d(args) {
return new pooling_GlobalMaxPooling2D(args);
}
/**
* Max pooling operation for temporal data.
*
* Input shape: `[batchSize, inLength, channels]`
*
* Output shape: `[batchSize, pooledLength, channels]`
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function maxPooling1d(args) {
return new pooling_MaxPooling1D(args);
}
/**
* Max pooling operation for spatial data.
*
* Input shape
* - If `dataFormat === CHANNEL_LAST`:
* 4D tensor with shape:
* `[batchSize, rows, cols, channels]`
* - If `dataFormat === CHANNEL_FIRST`:
* 4D tensor with shape:
* `[batchSize, channels, rows, cols]`
*
* Output shape
* - If `dataFormat=CHANNEL_LAST`:
* 4D tensor with shape:
* `[batchSize, pooleRows, pooledCols, channels]`
* - If `dataFormat=CHANNEL_FIRST`:
* 4D tensor with shape:
* `[batchSize, channels, pooleRows, pooledCols]`
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function maxPooling2d(args) {
return new pooling_MaxPooling2D(args);
}
/**
* Max pooling operation for 3D data.
*
* Input shape
* - If `dataFormat === channelsLast`:
* 5D tensor with shape:
* `[batchSize, depths, rows, cols, channels]`
* - If `dataFormat === channelsFirst`:
* 5D tensor with shape:
* `[batchSize, channels, depths, rows, cols]`
*
* Output shape
* - If `dataFormat=channelsLast`:
* 5D tensor with shape:
* `[batchSize, pooledDepths, pooledRows, pooledCols, channels]`
* - If `dataFormat=channelsFirst`:
* 5D tensor with shape:
* `[batchSize, channels, pooledDepths, pooledRows, pooledCols]`
*/
/** @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'} */
function maxPooling3d(args) {
return new pooling_MaxPooling3D(args);
}
// Recurrent Layers.
/**
* Gated Recurrent Unit - Cho et al. 2014.
*
* This is an `RNN` layer consisting of one `GRUCell`. However, unlike
* the underlying `GRUCell`, the `apply` method of `SimpleRNN` operates
* on a sequence of inputs. The shape of the input (not including the first,
* batch dimension) needs to be at least 2-D, with the first dimension being
* time steps. For example:
*
* ```js
* const rnn = tf.layers.gru({units: 8, returnSequences: true});
*
* // Create an input with 10 time steps.
* const input = tf.input({shape: [10, 20]});
* const output = rnn.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the
* // same as the sequence length of `input`, due to `returnSequences`: `true`;
* // 3rd dimension is the `GRUCell`'s number of units.
*/
/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */
function gru(args) {
return new recurrent_GRU(args);
}
/**
* Cell class for `GRU`.
*
* `GRUCell` is distinct from the `RNN` subclass `GRU` in that its
* `apply` method takes the input data of only a single time step and returns
* the cell's output at the time step, while `GRU` takes the input data
* over a number of time steps. For example:
*
* ```js
* const cell = tf.layers.gruCell({units: 2});
* const input = tf.input({shape: [10]});
* const output = cell.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10]: This is the cell's output at a single time step. The 1st
* // dimension is the unknown batch size.
* ```
*
* Instance(s) of `GRUCell` can be used to construct `RNN` layers. The
* most typical use of this workflow is to combine a number of cells into a
* stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an
* RNN. For example:
*
* ```js
* const cells = [
* tf.layers.gruCell({units: 4}),
* tf.layers.gruCell({units: 8}),
* ];
* const rnn = tf.layers.rnn({cell: cells, returnSequences: true});
*
* // Create an input with 10 time steps and a length-20 vector at each step.
* const input = tf.input({shape: [10, 20]});
* const output = rnn.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the
* // same as the sequence length of `input`, due to `returnSequences`: `true`;
* // 3rd dimension is the last `gruCell`'s number of units.
* ```
*
* To create an `RNN` consisting of only *one* `GRUCell`, use the
* `tf.layers.gru`.
*/
/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */
function gruCell(args) {
return new recurrent_GRUCell(args);
}
/**
* Long-Short Term Memory layer - Hochreiter 1997.
*
* This is an `RNN` layer consisting of one `LSTMCell`. However, unlike
* the underlying `LSTMCell`, the `apply` method of `LSTM` operates
* on a sequence of inputs. The shape of the input (not including the first,
* batch dimension) needs to be at least 2-D, with the first dimension being
* time steps. For example:
*
* ```js
* const lstm = tf.layers.lstm({units: 8, returnSequences: true});
*
* // Create an input with 10 time steps.
* const input = tf.input({shape: [10, 20]});
* const output = lstm.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the
* // same as the sequence length of `input`, due to `returnSequences`: `true`;
* // 3rd dimension is the `LSTMCell`'s number of units.
*/
/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */
function lstm(args) {
return new recurrent_LSTM(args);
}
/**
* Cell class for `LSTM`.
*
* `LSTMCell` is distinct from the `RNN` subclass `LSTM` in that its
* `apply` method takes the input data of only a single time step and returns
* the cell's output at the time step, while `LSTM` takes the input data
* over a number of time steps. For example:
*
* ```js
* const cell = tf.layers.lstmCell({units: 2});
* const input = tf.input({shape: [10]});
* const output = cell.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10]: This is the cell's output at a single time step. The 1st
* // dimension is the unknown batch size.
* ```
*
* Instance(s) of `LSTMCell` can be used to construct `RNN` layers. The
* most typical use of this workflow is to combine a number of cells into a
* stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an
* RNN. For example:
*
* ```js
* const cells = [
* tf.layers.lstmCell({units: 4}),
* tf.layers.lstmCell({units: 8}),
* ];
* const rnn = tf.layers.rnn({cell: cells, returnSequences: true});
*
* // Create an input with 10 time steps and a length-20 vector at each step.
* const input = tf.input({shape: [10, 20]});
* const output = rnn.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the
* // same as the sequence length of `input`, due to `returnSequences`: `true`;
* // 3rd dimension is the last `lstmCell`'s number of units.
* ```
*
* To create an `RNN` consisting of only *one* `LSTMCell`, use the
* `tf.layers.lstm`.
*/
/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */
function lstmCell(args) {
return new recurrent_LSTMCell(args);
}
/**
* Fully-connected RNN where the output is to be fed back to input.
*
* This is an `RNN` layer consisting of one `SimpleRNNCell`. However, unlike
* the underlying `SimpleRNNCell`, the `apply` method of `SimpleRNN` operates
* on a sequence of inputs. The shape of the input (not including the first,
* batch dimension) needs to be at least 2-D, with the first dimension being
* time steps. For example:
*
* ```js
* const rnn = tf.layers.simpleRNN({units: 8, returnSequences: true});
*
* // Create an input with 10 time steps.
* const input = tf.input({shape: [10, 20]});
* const output = rnn.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the
* // same as the sequence length of `input`, due to `returnSequences`: `true`;
* // 3rd dimension is the `SimpleRNNCell`'s number of units.
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */
function simpleRNN(args) {
return new recurrent_SimpleRNN(args);
}
/**
* Cell class for `SimpleRNN`.
*
* `SimpleRNNCell` is distinct from the `RNN` subclass `SimpleRNN` in that its
* `apply` method takes the input data of only a single time step and returns
* the cell's output at the time step, while `SimpleRNN` takes the input data
* over a number of time steps. For example:
*
* ```js
* const cell = tf.layers.simpleRNNCell({units: 2});
* const input = tf.input({shape: [10]});
* const output = cell.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10]: This is the cell's output at a single time step. The 1st
* // dimension is the unknown batch size.
* ```
*
* Instance(s) of `SimpleRNNCell` can be used to construct `RNN` layers. The
* most typical use of this workflow is to combine a number of cells into a
* stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an
* RNN. For example:
*
* ```js
* const cells = [
* tf.layers.simpleRNNCell({units: 4}),
* tf.layers.simpleRNNCell({units: 8}),
* ];
* const rnn = tf.layers.rnn({cell: cells, returnSequences: true});
*
* // Create an input with 10 time steps and a length-20 vector at each step.
* const input = tf.input({shape: [10, 20]});
* const output = rnn.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the
* // same as the sequence length of `input`, due to `returnSequences`: `true`;
* // 3rd dimension is the last `SimpleRNNCell`'s number of units.
* ```
*
* To create an `RNN` consisting of only *one* `SimpleRNNCell`, use the
* `tf.layers.simpleRNN`.
*/
/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */
function simpleRNNCell(args) {
return new recurrent_SimpleRNNCell(args);
}
/**
* Base class for recurrent layers.
*
* Input shape:
* 3D tensor with shape `[batchSize, timeSteps, inputDim]`.
*
* Output shape:
* - if `returnState`, an Array of tensors (i.e., `tf.Tensor`s). The first
* tensor is the output. The remaining tensors are the states at the
* last time step, each with shape `[batchSize, units]`.
* - if `returnSequences`, the output will have shape
* `[batchSize, timeSteps, units]`.
* - else, the output will have shape `[batchSize, units]`.
*
* Masking:
* This layer supports masking for input data with a variable number
* of timesteps. To introduce masks to your data,
* use an embedding layer with the `mask_zero` parameter
* set to `True`.
*
* Notes on using statefulness in RNNs:
* You can set RNN layers to be 'stateful', which means that the states
* computed for the samples in one batch will be reused as initial states
* for the samples in the next batch. This assumes a one-to-one mapping
* between samples in different successive batches.
*
* To enable statefulness:
* - specify `stateful: true` in the layer constructor.
* - specify a fixed batch size for your model, by passing
* if sequential model:
* `batchInputShape=[...]` to the first layer in your model.
* else for functional model with 1 or more Input layers:
* `batchShape=[...]` to all the first layers in your model.
* This is the expected shape of your inputs *including the batch size*.
* It should be a tuple of integers, e.g. `(32, 10, 100)`.
* - specify `shuffle=False` when calling fit().
*
* To reset the states of your model, call `.resetStates()` on either
* a specific layer, or on your entire model.
*
* Note on specifying the initial state of RNNs
* You can specify the initial state of RNN layers symbolically by
* calling them with the option `initialState`. The value of
* `initialState` should be a tensor or list of tensors representing
* the initial state of the RNN layer.
*
* You can specify the initial state of RNN layers numerically by
* calling `resetStates` with the keyword argument `states`. The value of
* `states` should be a numpy array or list of numpy arrays representing
* the initial state of the RNN layer.
*
* Note on passing external constants to RNNs
* You can pass "external" constants to the cell using the `constants`
* keyword argument of `RNN.call` method. This requires that the `cell.call`
* method accepts the same keyword argument `constants`. Such constants
* can be used to conditon the cell transformation on additional static inputs
* (not changing over time), a.k.a an attention mechanism.
*/
/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */
function exports_layers_rnn(args) {
return new recurrent_RNN(args);
}
/**
* Wrapper allowing a stack of RNN cells to behave as a single cell.
*
* Used to implement efficient stacked RNNs.
*/
/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */
function stackedRNNCells(args) {
return new recurrent_StackedRNNCells(args);
}
// Wrapper Layers.
/** @doc {heading: 'Layers', subheading: 'Wrapper', namespace: 'layers'} */
function bidirectional(args) {
return new wrappers_Bidirectional(args);
}
/**
* This wrapper applies a layer to every temporal slice of an input.
*
* The input should be at least 3D, and the dimension of the index `1` will be
* considered to be the temporal dimension.
*
* Consider a batch of 32 samples, where each sample is a sequence of 10 vectors
* of 16 dimensions. The batch input shape of the layer is then `[32, 10,
* 16]`, and the `inputShape`, not including the sample dimension, is
* `[10, 16]`.
*
* You can then use `TimeDistributed` to apply a `Dense` layer to each of the 10
* timesteps, independently:
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.timeDistributed({
* layer: tf.layers.dense({units: 8}),
* inputShape: [10, 16],
* }));
*
* // Now model.outputShape = [null, 10, 8].
* // The output will then have shape `[32, 10, 8]`.
*
* // In subsequent layers, there is no need for `inputShape`:
* model.add(tf.layers.timeDistributed({layer: tf.layers.dense({units: 32})}));
* console.log(JSON.stringify(model.outputs[0].shape));
* // Now model.outputShape = [null, 10, 32].
* ```
*
* The output will then have shape `[32, 10, 32]`.
*
* `TimeDistributed` can be used with arbitrary layers, not just `Dense`, for
* instance a `Conv2D` layer.
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.timeDistributed({
* layer: tf.layers.conv2d({filters: 64, kernelSize: [3, 3]}),
* inputShape: [10, 299, 299, 3],
* }));
* console.log(JSON.stringify(model.outputs[0].shape));
* ```
*/
/** @doc {heading: 'Layers', subheading: 'Wrapper', namespace: 'layers'} */
function timeDistributed(args) {
return new wrappers_TimeDistributed(args);
}
// Aliases for pooling.
const globalMaxPool1d = globalMaxPooling1d;
const globalMaxPool2d = globalMaxPooling2d;
const maxPool1d = maxPooling1d;
const maxPool2d = maxPooling2d;
/**
* Apply additive zero-centered Gaussian noise.
*
* As it is a regularization layer, it is only active at training time.
*
* This is useful to mitigate overfitting
* (you could see it as a form of random data augmentation).
* Gaussian Noise (GS) is a natural choice as corruption process
* for real valued inputs.
*
* # Arguments
* stddev: float, standard deviation of the noise distribution.
*
* # Input shape
* Arbitrary. Use the keyword argument `input_shape`
* (tuple of integers, does not include the samples axis)
* when using this layer as the first layer in a model.
*
* # Output shape
* Same shape as input.
*/
/** @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'} */
function gaussianNoise(args) {
return new noise_GaussianNoise(args);
}
/**
* Apply multiplicative 1-centered Gaussian noise.
*
* As it is a regularization layer, it is only active at training time.
*
* Arguments:
* - `rate`: float, drop probability (as with `Dropout`).
* The multiplicative noise will have
* standard deviation `sqrt(rate / (1 - rate))`.
*
* Input shape:
* Arbitrary. Use the keyword argument `inputShape`
* (tuple of integers, does not include the samples axis)
* when using this layer as the first layer in a model.
*
* Output shape:
* Same shape as input.
*
* References:
* - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](
* http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf)
*
*/
/** @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'} */
function gaussianDropout(args) {
return new noise_GaussianDropout(args);
}
/**
* Applies Alpha Dropout to the input.
*
* As it is a regularization layer, it is only active at training time.
*
* Alpha Dropout is a `Dropout` that keeps mean and variance of inputs
* to their original values, in order to ensure the self-normalizing property
* even after this dropout.
* Alpha Dropout fits well to Scaled Exponential Linear Units
* by randomly setting activations to the negative saturation value.
*
* Arguments:
* - `rate`: float, drop probability (as with `Dropout`).
* The multiplicative noise will have
* standard deviation `sqrt(rate / (1 - rate))`.
* - `noise_shape`: A 1-D `Tensor` of type `int32`, representing the
* shape for randomly generated keep/drop flags.
*
* Input shape:
* Arbitrary. Use the keyword argument `inputShape`
* (tuple of integers, does not include the samples axis)
* when using this layer as the first layer in a model.
*
* Output shape:
* Same shape as input.
*
* References:
* - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
*/
/** @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'} */
function alphaDropout(args) {
return new noise_AlphaDropout(args);
}
/**
* Masks a sequence by using a mask value to skip timesteps.
*
* If all features for a given sample timestep are equal to `mask_value`,
* then the sample timestep will be masked (skipped) in all downstream layers
* (as long as they support masking).
*
* If any downstream layer does not support masking yet receives such
* an input mask, an exception will be raised.
*
* Arguments:
* - `maskValue`: Either None or mask value to skip.
*
* Input shape:
* Arbitrary. Use the keyword argument `inputShape`
* (tuple of integers, does not include the samples axis)
* when using this layer as the first layer in a model.
*
* Output shape:
* Same shape as input.
*/
/** @doc {heading: 'Layers', subheading: 'Mask', namespace: 'layers'} */
function masking(args) {
return new core_Masking(args);
}
//# sourceMappingURL=exports_layers.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/exports_metrics.js
/**
* Binary accuracy metric function.
*
* `yTrue` and `yPred` can have 0-1 values. Example:
* ```js
* const x = tf.tensor2d([[1, 1, 1, 1], [0, 0, 0, 0]], [2, 4]);
* const y = tf.tensor2d([[1, 0, 1, 0], [0, 0, 0, 1]], [2, 4]);
* const accuracy = tf.metrics.binaryAccuracy(x, y);
* accuracy.print();
* ```
*
* `yTrue` and `yPred` can also have floating-number values between 0 and 1, in
* which case the values will be thresholded at 0.5 to yield 0-1 values (i.e.,
* a value >= 0.5 and <= 1.0 is interpreted as 1.
* )
* Example:
* ```js
* const x = tf.tensor1d([1, 1, 1, 1, 0, 0, 0, 0]);
* const y = tf.tensor1d([0.2, 0.4, 0.6, 0.8, 0.2, 0.3, 0.4, 0.7]);
* const accuracy = tf.metrics.binaryAccuracy(x, y);
* accuracy.print();
* ```
*
* @param yTrue Binary Tensor of truth.
* @param yPred Binary Tensor of prediction.
* @return Accuracy Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_binaryAccuracy(yTrue, yPred) {
return binaryAccuracy(yTrue, yPred);
}
/**
* Binary crossentropy metric function.
*
* Example:
* ```js
* const x = tf.tensor2d([[0], [1], [1], [1]]);
* const y = tf.tensor2d([[0], [0], [0.5], [1]]);
* const crossentropy = tf.metrics.binaryCrossentropy(x, y);
* crossentropy.print();
* ```
*
* @param yTrue Binary Tensor of truth.
* @param yPred Binary Tensor of prediction, probabilities for the `1` case.
* @return Accuracy Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_binaryCrossentropy(yTrue, yPred) {
return metrics_binaryCrossentropy(yTrue, yPred);
}
/**
* Sparse categorical accuracy metric function.
*
* Example:
* ```js
*
* const yTrue = tf.tensor1d([1, 1, 2, 2, 0]);
* const yPred = tf.tensor2d(
* [[0, 1, 0], [1, 0, 0], [0, 0.4, 0.6], [0, 0.6, 0.4], [0.7, 0.3, 0]]);
* const crossentropy = tf.metrics.sparseCategoricalAccuracy(yTrue, yPred);
* crossentropy.print();
* ```
*
* @param yTrue True labels: indices.
* @param yPred Predicted probabilities or logits.
* @returns Accuracy tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_sparseCategoricalAccuracy(yTrue, yPred) {
return sparseCategoricalAccuracy(yTrue, yPred);
}
/**
* Categorical accuracy metric function.
*
* Example:
* ```js
* const x = tf.tensor2d([[0, 0, 0, 1], [0, 0, 0, 1]]);
* const y = tf.tensor2d([[0.1, 0.8, 0.05, 0.05], [0.1, 0.05, 0.05, 0.8]]);
* const accuracy = tf.metrics.categoricalAccuracy(x, y);
* accuracy.print();
* ```
*
* @param yTrue Binary Tensor of truth: one-hot encoding of categories.
* @param yPred Binary Tensor of prediction: probabilities or logits for the
* same categories as in `yTrue`.
* @return Accuracy Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_categoricalAccuracy(yTrue, yPred) {
return categoricalAccuracy(yTrue, yPred);
}
/**
* Categorical crossentropy between an output tensor and a target tensor.
*
* @param target A tensor of the same shape as `output`.
* @param output A tensor resulting from a softmax (unless `fromLogits` is
* `true`, in which case `output` is expected to be the logits).
* @param fromLogits Boolean, whether `output` is the result of a softmax, or is
* a tensor of logits.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_categoricalCrossentropy(yTrue, yPred) {
return metrics_categoricalCrossentropy(yTrue, yPred);
}
/**
* Computes the precision of the predictions with respect to the labels.
*
* Example:
* ```js
* const x = tf.tensor2d(
* [
* [0, 0, 0, 1],
* [0, 1, 0, 0],
* [0, 0, 0, 1],
* [1, 0, 0, 0],
* [0, 0, 1, 0]
* ]
* );
*
* const y = tf.tensor2d(
* [
* [0, 0, 1, 0],
* [0, 1, 0, 0],
* [0, 0, 0, 1],
* [0, 1, 0, 0],
* [0, 1, 0, 0]
* ]
* );
*
* const precision = tf.metrics.precision(x, y);
* precision.print();
* ```
*
* @param yTrue The ground truth values. Expected to be contain only 0-1 values.
* @param yPred The predicted values. Expected to be contain only 0-1 values.
* @return Precision Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_precision(yTrue, yPred) {
return precision(yTrue, yPred);
}
/**
* Computes the recall of the predictions with respect to the labels.
*
* Example:
* ```js
* const x = tf.tensor2d(
* [
* [0, 0, 0, 1],
* [0, 1, 0, 0],
* [0, 0, 0, 1],
* [1, 0, 0, 0],
* [0, 0, 1, 0]
* ]
* );
*
* const y = tf.tensor2d(
* [
* [0, 0, 1, 0],
* [0, 1, 0, 0],
* [0, 0, 0, 1],
* [0, 1, 0, 0],
* [0, 1, 0, 0]
* ]
* );
*
* const recall = tf.metrics.recall(x, y);
* recall.print();
* ```
*
* @param yTrue The ground truth values. Expected to be contain only 0-1 values.
* @param yPred The predicted values. Expected to be contain only 0-1 values.
* @return Recall Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_recall(yTrue, yPred) {
return recall(yTrue, yPred);
}
/**
* Loss or metric function: Cosine proximity.
*
* Mathematically, cosine proximity is defined as:
* `-sum(l2Normalize(yTrue) * l2Normalize(yPred))`,
* wherein `l2Normalize()` normalizes the L2 norm of the input to 1 and `*`
* represents element-wise multiplication.
*
* ```js
* const yTrue = tf.tensor2d([[1, 0], [1, 0]]);
* const yPred = tf.tensor2d([[1 / Math.sqrt(2), 1 / Math.sqrt(2)], [0, 1]]);
* const proximity = tf.metrics.cosineProximity(yTrue, yPred);
* proximity.print();
* ```
*
* @param yTrue Truth Tensor.
* @param yPred Prediction Tensor.
* @return Cosine proximity Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_cosineProximity(yTrue, yPred) {
return cosineProximity(yTrue, yPred);
}
/**
* Loss or metric function: Mean absolute error.
*
* Mathematically, mean absolute error is defined as:
* `mean(abs(yPred - yTrue))`,
* wherein the `mean` is applied over feature dimensions.
*
* ```js
* const yTrue = tf.tensor2d([[0, 1], [0, 0], [2, 3]]);
* const yPred = tf.tensor2d([[0, 1], [0, 1], [-2, -3]]);
* const mse = tf.metrics.meanAbsoluteError(yTrue, yPred);
* mse.print();
* ```
*
* @param yTrue Truth Tensor.
* @param yPred Prediction Tensor.
* @return Mean absolute error Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_meanAbsoluteError(yTrue, yPred) {
return meanAbsoluteError(yTrue, yPred);
}
/**
* Loss or metric function: Mean absolute percentage error.
*
* ```js
* const yTrue = tf.tensor2d([[0, 1], [10, 20]]);
* const yPred = tf.tensor2d([[0, 1], [11, 24]]);
* const mse = tf.metrics.meanAbsolutePercentageError(yTrue, yPred);
* mse.print();
* ```
*
* Aliases: `tf.metrics.MAPE`, `tf.metrics.mape`.
*
* @param yTrue Truth Tensor.
* @param yPred Prediction Tensor.
* @return Mean absolute percentage error Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_meanAbsolutePercentageError(yTrue, yPred) {
return meanAbsolutePercentageError(yTrue, yPred);
}
function exports_metrics_MAPE(yTrue, yPred) {
return meanAbsolutePercentageError(yTrue, yPred);
}
function exports_metrics_mape(yTrue, yPred) {
return meanAbsolutePercentageError(yTrue, yPred);
}
/**
* Loss or metric function: Mean squared error.
*
* ```js
* const yTrue = tf.tensor2d([[0, 1], [3, 4]]);
* const yPred = tf.tensor2d([[0, 1], [-3, -4]]);
* const mse = tf.metrics.meanSquaredError(yTrue, yPred);
* mse.print();
* ```
*
* Aliases: `tf.metrics.MSE`, `tf.metrics.mse`.
*
* @param yTrue Truth Tensor.
* @param yPred Prediction Tensor.
* @return Mean squared error Tensor.
*/
/** @doc {heading: 'Metrics', namespace: 'metrics'} */
function exports_metrics_meanSquaredError(yTrue, yPred) {
return meanSquaredError(yTrue, yPred);
}
function exports_metrics_MSE(yTrue, yPred) {
return meanSquaredError(yTrue, yPred);
}
function exports_metrics_mse(yTrue, yPred) {
return meanSquaredError(yTrue, yPred);
}
//# sourceMappingURL=exports_metrics.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/exports_models.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
//# sourceMappingURL=exports_models.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/exports_regularizers.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// tslint:disable-next-line:max-line-length
/**
* Regularizer for L1 and L2 regularization.
*
* Adds a term to the loss to penalize large weights:
* loss += sum(l1 * abs(x)) + sum(l2 * x^2)
*/
/** @doc {heading: 'Regularizers', namespace: 'regularizers'} */
function l1l2(config) {
return new regularizers_L1L2(config);
}
/**
* Regularizer for L1 regularization.
*
* Adds a term to the loss to penalize large weights:
* loss += sum(l1 * abs(x))
* @param args l1 config.
*/
/** @doc {heading: 'Regularizers', namespace: 'regularizers'} */
function exports_regularizers_l1(config) {
return l1(config);
}
/**
* Regularizer for L2 regularization.
*
* Adds a term to the loss to penalize large weights:
* loss += sum(l2 * x^2)
* @param args l2 config.
*/
/** @doc {heading: 'Regularizers', namespace: 'regularizers'} */
function exports_regularizers_l2(config) {
return l2(config);
}
//# sourceMappingURL=exports_regularizers.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/callbacks.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/* Original source: keras/callbacks.py */
class callbacks_Callback extends BaseCallback {
constructor() {
super(...arguments);
/** Instance of `keras.models.Model`. Reference of the model being trained. */
this.model = null;
}
setModel(model) {
if (!(model instanceof training_LayersModel)) {
throw new Error("model must be a LayersModel, not some other Container");
}
this.model = model;
}
}
function less(currVal, prevVal) {
return currVal < prevVal;
}
function greater(currVal, prevVal) {
return currVal > prevVal;
}
/**
* A Callback that stops training when a monitored quantity has stopped
* improving.
*/
class callbacks_EarlyStopping extends callbacks_Callback {
constructor(args) {
super();
if (args == null) {
args = {};
}
if (args.restoreBestWeights) {
throw new NotImplementedError(
"restoreBestWeights = True is not implemented in EarlyStopping yet."
);
}
this.monitor = args.monitor || "val_loss";
this.minDelta = Math.abs(args.minDelta || 0);
this.patience = args.patience || 0;
this.verbose = args.verbose || 0;
this.mode = args.mode || "auto";
this.baseline = args.baseline;
if (["auto", "min", "max"].indexOf(this.mode) === -1) {
console.warn(
`EarlyStopping mode '${this.mode}' is invalid. ` + `Falling back to mode 'auto'.`
);
this.mode = "auto";
}
if (this.mode === "min") {
this.monitorFunc = less;
} else if (this.mode === "max") {
this.monitorFunc = greater;
} else {
// For mode === 'auto'.
if (this.monitor.indexOf("acc") !== -1) {
this.monitorFunc = greater;
} else {
this.monitorFunc = less;
}
}
if (this.monitorFunc === less) {
this.minDelta *= -1;
}
}
async onTrainBegin(logs) {
this.wait = 0;
this.stoppedEpoch = 0;
if (this.baseline != null) {
this.best = this.baseline;
} else {
this.best = this.monitorFunc === less ? Infinity : -Infinity;
}
}
async onEpochEnd(epoch, logs) {
await resolveScalarsInLogs(logs);
const current = this.getMonitorValue(logs);
if (current == null) {
return;
}
if (this.monitorFunc(current - this.minDelta, this.best)) {
this.best = current;
this.wait = 0;
// TODO(cais): Logic for restoreBestWeights.
} else {
this.wait++;
if (this.wait >= this.patience) {
this.stoppedEpoch = epoch;
this.model.stopTraining = true;
}
// TODO(cais): Logic for restoreBestWeights.
}
}
async onTrainEnd(logs) {
if (this.stoppedEpoch > 0 && this.verbose) {
console.log(`Epoch ${this.stoppedEpoch}: early stopping.`);
}
}
getMonitorValue(logs) {
if (logs == null) {
logs = {};
}
const monitorValue = logs[this.monitor];
if (monitorValue == null) {
console.warn(
`Metric for EarlyStopping ${this.monitor} is not available. ` +
`Available metrics are: ${Object.keys(logs)}`
);
}
return monitorValue;
}
}
/**
* Factory function for a Callback that stops training when a monitored
* quantity has stopped improving.
*
* Early stopping is a type of regularization, and protects model against
* overfitting.
*
* The following example based on fake data illustrates how this callback
* can be used during `tf.LayersModel.fit()`:
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.dense({
* units: 3,
* activation: 'softmax',
* kernelInitializer: 'ones',
* inputShape: [2]
* }));
* const xs = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const ys = tf.tensor2d([[1, 0, 0], [0, 1, 0]], [2, 3]);
* const xsVal = tf.tensor2d([4, 3, 2, 1], [2, 2]);
* const ysVal = tf.tensor2d([[0, 0, 1], [0, 1, 0]], [2, 3]);
* model.compile(
* {loss: 'categoricalCrossentropy', optimizer: 'sgd', metrics: ['acc']});
*
* // Without the EarlyStopping callback, the val_acc value would be:
* // 0.5, 0.5, 0.5, 0.5, ...
* // With val_acc being monitored, training should stop after the 2nd epoch.
* const history = await model.fit(xs, ys, {
* epochs: 10,
* validationData: [xsVal, ysVal],
* callbacks: tf.callbacks.earlyStopping({monitor: 'val_acc'})
* });
*
* // Expect to see a length-2 array.
* console.log(history.history.val_acc);
* ```
*/
/**
* @doc {
* heading: 'Callbacks',
* namespace: 'callbacks'
* }
*/
function earlyStopping(args) {
return new callbacks_EarlyStopping(args);
}
const callbacks_callbacks = { earlyStopping };
//# sourceMappingURL=callbacks.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/index.js
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
// This file lists all exports of TensorFlow.js Layers
//# sourceMappingURL=index.js.map
/***/
},
/* 88 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "array", function () {
return /* reexport */ array;
});
__webpack_require__.d(__webpack_exports__, "Dataset", function () {
return /* reexport */ dataset_Dataset;
});
__webpack_require__.d(__webpack_exports__, "zip", function () {
return /* reexport */ zip;
});
__webpack_require__.d(__webpack_exports__, "CSVDataset", function () {
return /* reexport */ csv_dataset_CSVDataset;
});
__webpack_require__.d(__webpack_exports__, "TextLineDataset", function () {
return /* reexport */ text_line_dataset_TextLineDataset;
});
__webpack_require__.d(__webpack_exports__, "csv", function () {
return /* reexport */ csv;
});
__webpack_require__.d(__webpack_exports__, "func", function () {
return /* reexport */ func;
});
__webpack_require__.d(__webpack_exports__, "generator", function () {
return /* reexport */ readers_generator;
});
__webpack_require__.d(__webpack_exports__, "microphone", function () {
return /* reexport */ microphone;
});
__webpack_require__.d(__webpack_exports__, "webcam", function () {
return /* reexport */ webcam;
});
__webpack_require__.d(__webpack_exports__, "FileDataSource", function () {
return /* reexport */ file_data_source_FileDataSource;
});
__webpack_require__.d(__webpack_exports__, "URLDataSource", function () {
return /* reexport */ url_data_source_URLDataSource;
});
__webpack_require__.d(__webpack_exports__, "version_data", function () {
return /* reexport */ version;
});
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js + 269 modules
var dist = __webpack_require__(0);
// EXTERNAL MODULE: ./node_modules/seedrandom/index.js
var seedrandom = __webpack_require__(20);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-data/dist/iterators/lazy_iterator.js + 3 modules
var lazy_iterator = __webpack_require__(14);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-data/dist/util/deep_map.js
var deep_map = __webpack_require__(19);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/dataset.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
// TODO(soergel): consider vectorized operations within the pipeline.
/**
* Represents a potentially large list of independent data elements (typically
* 'samples' or 'examples').
*
* A 'data example' may be a primitive, an array, a map from string keys to
* values, or any nested structure of these.
*
* A `Dataset` represents an ordered collection of elements, together with a
* chain of transformations to be performed on those elements. Each
* transformation is a method of `Dataset` that returns another `Dataset`, so
* these may be chained, e.g.
* `const processedDataset = rawDataset.filter(...).map(...).batch(...)`.
*
* Data loading and transformation is done in a lazy, streaming fashion. The
* dataset may be iterated over multiple times; each iteration starts the data
* loading anew and recapitulates the transformations.
*
* A `Dataset` is typically processed as a stream of unbatched examples --i.e.,
* its transformations are applied one example at a time. Batching produces a
* new `Dataset` where each element is a batch. Batching should usually come
* last in a pipeline, because data transformations are easier to express on a
* per-example basis than on a per-batch basis.
*
* The following code examples are calling `await dataset.forEachAsync(...)` to
* iterate once over the entire dataset in order to print out the data.
*/
/** @doc {heading: 'Data', subheading: 'Classes', namespace: 'data'} */
class dataset_Dataset {
constructor() {
this.size = null;
}
// TODO(soergel): Make Datasets report whether repeated iterator() calls
// produce the same result (e.g., reading from a file) or different results
// (e.g., from the webcam). Currently we don't make this distinction but it
// could be important for the user to know.
// abstract isDeterministic(): boolean;
/**
* Groups elements into batches.
*
* It is assumed that each of the incoming dataset elements has the same
* structure-- i.e. the same set of keys at each location in an object
* hierarchy. For each key, the resulting `Dataset` provides a batched
* element collecting all of the incoming values for that key.
*
* * Incoming primitives are grouped into a 1-D Tensor.
* * Incoming Tensors are grouped into a new Tensor where the 0'th axis is
* the batch dimension.
* * Incoming arrays are converted to Tensor and then batched.
* * A nested array is interpreted as an n-D Tensor, so the batched result
* has n+1 dimensions.
* * An array that cannot be converted to Tensor produces an error.
*
* If an array should not be batched as a unit, it should first be converted
* to an object with integer keys.
*
* Here are a few examples:
*
* Batch a dataset of numbers:
* ```js
* const a = tf.data.array([1, 2, 3, 4, 5, 6, 7, 8]).batch(4);
* await a.forEachAsync(e => e.print());
* ```
*
* Batch a dataset of arrays:
* ```js
* const b = tf.data.array([[1], [2], [3], [4], [5], [6], [7], [8]]).batch(4);
* await b.forEachAsync(e => e.print());
* ```
*
* Batch a dataset of objects:
* ```js
* const c = tf.data.array([{a: 1, b: 11}, {a: 2, b: 12}, {a: 3, b: 13},
* {a: 4, b: 14}, {a: 5, b: 15}, {a: 6, b: 16}, {a: 7, b: 17},
* {a: 8, b: 18}]).batch(4);
* await c.forEachAsync(e => {
* console.log('{');
* for(var key in e) {
* console.log(key+':');
* e[key].print();
* }
* console.log('}');
* })
* ```
*
* @param batchSize The number of elements desired per batch.
* @param smallLastBatch Whether to emit the final batch when it has fewer
* than batchSize elements. Default true.
* @returns A `Dataset`, from which a stream of batches can be obtained.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
batch(batchSize, smallLastBatch = true) {
const base = this;
dist["util"].assert(
batchSize > 0,
() => `batchSize needs to be positive, but it is
${batchSize}`
);
let size;
if (this.size === Infinity || this.size == null) {
// If the size of this dataset is infinity or null, the new size keeps the
// same.
size = this.size;
} else if (smallLastBatch) {
// If the size of this dataset is known and include small last batch, the
// new size is full batch count plus last batch.
size = Math.ceil(this.size / batchSize);
} else {
// If the size of this dataset is known and not include small last batch,
// the new size is full batch count.
size = Math.floor(this.size / batchSize);
}
return datasetFromIteratorFn(async () => {
return (await base.iterator()).columnMajorBatch(
batchSize,
smallLastBatch,
deepBatchConcat
);
}, size);
}
/**
* Concatenates this `Dataset` with another.
*
* ```js
* const a = tf.data.array([1, 2, 3]);
* const b = tf.data.array([4, 5, 6]);
* const c = a.concatenate(b);
* await c.forEachAsync(e => console.log(e));
* ```
*
* @param dataset A `Dataset` to be concatenated onto this one.
* @returns A `Dataset`.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
concatenate(dataset) {
const base = this;
let size;
if (this.size === Infinity || dataset.size === Infinity) {
// If the size of any of these two dataset is infinity, new size is
// infinity.
size = Infinity;
} else if (this.size != null && dataset.size != null) {
// If the size of both datasets are known and not infinity, new size is
// sum the size of these two datasets.
size = this.size + dataset.size;
} else {
// If neither of these two datasets has infinite size and any of these two
// datasets' size is null, the new size is null.
size = null;
}
return datasetFromIteratorFn(
async () => (await base.iterator()).concatenate(await dataset.iterator()),
size
);
}
/**
* Filters this dataset according to `predicate`.
*
* ```js
* const a = tf.data.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
* .filter(x => x%2 === 0);
* await a.forEachAsync(e => console.log(e));
* ```
*
* @param predicate A function mapping a dataset element to a boolean or a
* `Promise` for one.
*
* @returns A `Dataset` of elements for which the predicate was true.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
filter(predicate) {
const base = this;
let size;
if (this.size === Infinity) {
// If the size of this dataset is infinity, new size is infinity
size = Infinity;
} else {
// If this dataset has limited elements, new size is null because it might
// exhausted randomly.
size = null;
}
return datasetFromIteratorFn(async () => {
return (await base.iterator()).filter((x) => dist["tidy"](() => predicate(x)));
}, size);
}
/**
* Apply a function to every element of the dataset.
*
* After the function is applied to a dataset element, any Tensors contained
* within that element are disposed.
*
* ```js
* const a = tf.data.array([1, 2, 3]);
* await a.forEachAsync(e => console.log(e));
* ```
*
* @param f A function to apply to each dataset element.
* @returns A `Promise` that resolves after all elements have been processed.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
async forEachAsync(f) {
return (await this.iterator()).forEachAsync(f);
}
/**
* Maps this dataset through a 1-to-1 transform.
*
* ```js
* const a = tf.data.array([1, 2, 3]).map(x => x*x);
* await a.forEachAsync(e => console.log(e));
* ```
*
* @param transform A function mapping a dataset element to a transformed
* dataset element.
*
* @returns A `Dataset` of transformed elements.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
map(transform) {
const base = this;
return datasetFromIteratorFn(async () => {
return (await base.iterator()).map((x) => dist["tidy"](() => transform(x)));
}, this.size);
}
/**
* Maps this dataset through an async 1-to-1 transform.
*
* ```js
* const a =
* tf.data.array([1, 2, 3]).mapAsync(x => new Promise(function(resolve){
* setTimeout(() => {
* resolve(x * x);
* }, Math.random()*1000 + 500);
* }));
* console.log(await a.toArray());
* ```
*
* @param transform A function mapping a dataset element to a `Promise` for a
* transformed dataset element. This transform is responsible for disposing
* any intermediate `Tensor`s, i.e. by wrapping its computation in
* `tf.tidy()`; that cannot be automated here (as it is in the synchronous
* `map()` case).
*
* @returns A `Dataset` of transformed elements.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
mapAsync(transform) {
const base = this;
return datasetFromIteratorFn(async () => {
return (await base.iterator()).mapAsync(transform);
}, this.size);
}
/**
* Creates a `Dataset` that prefetches elements from this dataset.
*
* @param bufferSize: An integer specifying the number of elements to be
* prefetched.
* @returns A `Dataset`.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
prefetch(bufferSize) {
if (bufferSize == null) {
throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");
}
const base = this;
return datasetFromIteratorFn(
async () => (await base.iterator()).prefetch(bufferSize),
this.size
);
}
/**
* Repeats this dataset `count` times.
*
* NOTE: If this dataset is a function of global state (e.g. a random number
* generator), then different repetitions may produce different elements.
*
* ```js
* const a = tf.data.array([1, 2, 3]).repeat(3);
* await a.forEachAsync(e => console.log(e));
* ```
*
* @param count: (Optional) An integer, representing the number of times
* the dataset should be repeated. The default behavior (if `count` is
* `undefined` or negative) is for the dataset be repeated indefinitely.
* @returns A `Dataset`.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
repeat(count) {
const base = this;
let size;
if (this.size != null && count > 0) {
// If this dataset has size and count is positive, new size is current
// size multiply count. This also covers the case that current size is
// infinity.
size = this.size * count;
} else if (count === 0) {
// If count is 0, new size is 0.
size = 0;
} else if (this.size != null && (count === undefined || count < 0)) {
// If this dataset has size and count is undefined or negative, the
// dataset will be repeated indefinitely and new size is infinity.
size = Infinity;
} else {
// If the size of this dataset is null, the new dataset's size is null.
size = null;
}
return datasetFromIteratorFn(async () => {
const iteratorIterator = Object(lazy_iterator["e" /* iteratorFromFunction */])(
async () => ({ value: await base.iterator(), done: false })
);
return Object(lazy_iterator["d" /* iteratorFromConcatenated */])(
iteratorIterator.take(count)
);
}, size);
}
/**
* Creates a `Dataset` that skips `count` initial elements from this dataset.
*
* ```js
* const a = tf.data.array([1, 2, 3, 4, 5, 6]).skip(3);
* await a.forEachAsync(e => console.log(e));
* ```
*
* @param count: The number of elements of this dataset that should be skipped
* to form the new dataset. If `count` is greater than the size of this
* dataset, the new dataset will contain no elements. If `count`
* is `undefined` or negative, skips the entire dataset.
*
* @returns A `Dataset`.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
skip(count) {
const base = this;
let size;
if (this.size != null && count >= 0 && this.size >= count) {
// If the size of this dataset is greater than count, the new dataset's
// size is current size minus skipped size.This also covers the case that
// current size is infinity.
size = this.size - count;
} else if (this.size != null && (this.size < count || count === undefined || count < 0)) {
// If the size of this dataset is smaller than count, or count is
// undefined or negative, skips the entire dataset and the new size is 0.
size = 0;
} else {
// If the size of this dataset is null, the new dataset's size is null.
size = null;
}
return datasetFromIteratorFn(async () => (await base.iterator()).skip(count), size);
}
/**
* Pseudorandomly shuffles the elements of this dataset. This is done in a
* streaming manner, by sampling from a given number of prefetched elements.
*
* ```js
* const a = tf.data.array([1, 2, 3, 4, 5, 6]).shuffle(3);
* await a.forEachAsync(e => console.log(e));
* ```
*
* @param bufferSize: An integer specifying the number of elements from this
* dataset from which the new dataset will sample.
* @param seed: (Optional) An integer specifying the random seed that will
* be used to create the distribution.
* @param reshuffleEachIteration: (Optional) A boolean, which if true
* indicates that the dataset should be pseudorandomly reshuffled each time
* it is iterated over. If false, elements will be returned in the same
* shuffled order on each iteration. (Defaults to `true`.)
* @returns A `Dataset`.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
shuffle(bufferSize, seed, reshuffleEachIteration = true) {
if (bufferSize == null || bufferSize < 0) {
if (this.size == null) {
throw new RangeError("`Dataset.shuffle()` requires bufferSize to be specified.");
} else {
throw new RangeError(
"`Dataset.shuffle()` requires bufferSize to be specified. " +
"If your data fits in main memory (for regular JS objects), " +
"and/or GPU memory (for `tf.Tensor`s), consider setting " +
`bufferSize to the dataset size (${this.size} elements)`
);
}
}
const base = this;
const random = seedrandom["alea"](seed || dist["util"].now().toString());
return datasetFromIteratorFn(async () => {
let seed2 = random.int32();
if (reshuffleEachIteration) {
seed2 += random.int32();
}
return (await base.iterator()).shuffle(bufferSize, seed2.toString());
}, this.size);
}
/**
* Creates a `Dataset` with at most `count` initial elements from this
* dataset.
*
* ```js
* const a = tf.data.array([1, 2, 3, 4, 5, 6]).take(3);
* await a.forEachAsync(e => console.log(e));
* ```
*
* @param count: The number of elements of this dataset that should be taken
* to form the new dataset. If `count` is `undefined` or negative, or if
* `count` is greater than the size of this dataset, the new dataset will
* contain all elements of this dataset.
* @returns A `Dataset`.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
take(count) {
const base = this;
let size;
if (this.size != null && this.size > count) {
// If the size of this dataset is greater than count, the new dataset's
// size is count.
size = count;
} else if (this.size != null && this.size <= count) {
// If the size of this dataset is equal or smaller than count, the new
// dataset's size is the size of this dataset.
size = this.size;
} else {
// If the size of this dataset is null, the new dataset's size is null.
size = null;
}
return datasetFromIteratorFn(async () => (await base.iterator()).take(count), size);
}
/**
* Collect all elements of this dataset into an array.
*
* Obviously this will succeed only for small datasets that fit in memory.
* Useful for testing and generally should be avoided if possible.
*
* ```js
* const a = tf.data.array([1, 2, 3, 4, 5, 6]);
* console.log(await a.toArray());
* ```
*
* @returns A Promise for an array of elements, which will resolve
* when a new stream has been obtained and fully consumed.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
async toArray() {
if (this.size === Infinity) {
throw new Error("Can not convert infinite data stream to array.");
}
return (await this.iterator()).toArray();
}
/**
* Collect all elements of this dataset into an array with prefetching 100
* elements. This is useful for testing, because the prefetch changes the
* order in which the Promises are resolved along the processing pipeline.
* This may help expose bugs where results are dependent on the order of
* Promise resolution rather than on the logical order of the stream (i.e.,
* due to hidden mutable state).
*
* @returns A Promise for an array of elements, which will resolve
* when a new stream has been obtained and fully consumed.
*/
async toArrayForTest() {
if (this.size === Infinity) {
throw new Error("Can not convert infinite data stream to array.");
}
return (await this.iterator()).toArrayForTest();
}
}
// TODO(soergel): deep sharded shuffle, where supported
dataset_Dataset.MAX_BUFFER_SIZE = 10000;
/**
* Create a `Dataset` defined by a provided iterator() function.
*
* ```js
* let i = -1;
* const func = () =>
* ++i < 5 ? {value: i, done: false} : {value: null, done: true};
* const iter = tf.data.iteratorFromFunction(func);
* const ds = tf.data.datasetFromIteratorFn(iter);
* await ds.forEachAsync(e => console.log(e));
* ```
*/
function datasetFromIteratorFn(iteratorFn, size = null) {
return new (class extends dataset_Dataset {
constructor() {
super(...arguments);
this.size = size;
}
/*
* Provide a new stream of elements. Note this will also start new streams
* from any underlying `Dataset`s.
*/
async iterator() {
return iteratorFn();
}
})();
}
/**
* Create a `Dataset` from an array of elements.
*
* Create a Dataset from an array of objects:
* ```js
* const a = tf.data.array([{'item': 1}, {'item': 2}, {'item': 3}]);
* await a.forEachAsync(e => console.log(e));
* ```
*
* Create a Dataset from an array of numbers:
* ```js
* const a = tf.data.array([4, 5, 6]);
* await a.forEachAsync(e => console.log(e));
* ```
* @param items An array of elements that will be parsed as items in a dataset.
*/
/** @doc {heading: 'Data', subheading: 'Creation', namespace: 'data'} */
function array(items) {
return datasetFromIteratorFn(
async () => Object(lazy_iterator["f" /* iteratorFromItems */])(items),
items.length
);
}
/**
* Create a `Dataset` by zipping together an array, dict, or nested
* structure of `Dataset`s (and perhaps additional constants).
* The underlying datasets must provide elements in a consistent order such that
* they correspond.
*
* The number of elements in the resulting dataset is the same as the size of
* the smallest dataset in datasets.
*
* The nested structure of the `datasets` argument determines the
* structure of elements in the resulting iterator.
*
* Note this means that, given an array of two datasets that produce dict
* elements, the result is a dataset that produces elements that are arrays
* of two dicts:
*
* Zip an array of datasets:
* ```js
* console.log('Zip two datasets of objects:');
* const ds1 = tf.data.array([{a: 1}, {a: 2}, {a: 3}]);
* const ds2 = tf.data.array([{b: 4}, {b: 5}, {b: 6}]);
* const ds3 = tf.data.zip([ds1, ds2]);
* await ds3.forEachAsync(e => console.log(JSON.stringify(e)));
*
* // If the goal is to merge the dicts in order to produce elements like
* // {a: ..., b: ...}, this requires a second step such as:
* console.log('Merge the objects:');
* const ds4 = ds3.map(x => {return {a: x[0].a, b: x[1].b}});
* await ds4.forEachAsync(e => console.log(e));
* ```
*
* Zip a dict of datasets:
* ```js
* const a = tf.data.array([{a: 1}, {a: 2}, {a: 3}]);
* const b = tf.data.array([{b: 4}, {b: 5}, {b: 6}]);
* const c = tf.data.zip({c: a, d: b});
* await c.forEachAsync(e => console.log(JSON.stringify(e)));
* ```
*/
/** @doc {heading: 'Data', subheading: 'Operations', namespace: 'data'} */
function zip(datasets) {
// manually type-check the argument for JS users
if (!Object(deep_map["e" /* isIterable */])(datasets)) {
throw new Error("The argument to zip() must be an object or array.");
}
let size;
if (Array.isArray(datasets)) {
for (let i = 0; i < datasets.length; i++) {
size = size == null ? datasets[i].size : Math.min(size, datasets[i].size);
}
} else if (datasets instanceof Object) {
for (const ds in datasets) {
size = size == null ? datasets[ds].size : Math.min(size, datasets[ds].size);
}
}
return datasetFromIteratorFn(async () => {
const streams = await Object(deep_map["c" /* deepMapAndAwaitAll */])(datasets, (d) => {
if (d instanceof dataset_Dataset) {
return { value: d.iterator(), recurse: false };
} else if (Object(deep_map["e" /* isIterable */])(d)) {
return { value: null, recurse: true };
} else {
throw new Error(
"Leaves of the structure passed to zip() must be Datasets, " + "not primitives."
);
}
});
return Object(lazy_iterator["g" /* iteratorFromZipped */])(
streams,
lazy_iterator["c" /* ZipMismatchMode */].SHORTEST
);
}, size);
}
/**
* A zip function for use with deepZip, passed via the columnMajorBatch call.
*
* Accepts an array of identically-structured nested elements and either batches
* them (if they are primitives, numeric arrays, or Tensors) or requests
* recursion (if not).
*/
// tslint:disable-next-line:no-any
function deepBatchConcat(rows) {
if (rows === null) {
return null;
}
// use the first item to decide whether to recurse or batch here.
const exampleRow = rows[0];
if (Object(deep_map["a" /* canTensorify */])(exampleRow)) {
// rows is an array of primitives, Tensors, or arrays. Batch them.
const value = batchConcat(rows);
return { value, recurse: false };
}
// the example row is an object, so recurse into it.
return { value: null, recurse: true };
}
/**
* Assembles a list of same-shaped numbers, number arrays, or Tensors
* into a single new Tensor where axis 0 is the batch dimension.
*/
function batchConcat(arrays) {
if (arrays.length === 0) {
// We can't return an empty Tensor because we don't know the element shape.
throw new Error("Can't make a batch of zero elements.");
}
if (arrays[0] instanceof dist["Tensor"]) {
// Input is an array of Tensors
return dist["stack"](arrays);
} else {
// Input is a possibly-nested array of numbers.
return dist["tensor"](arrays);
}
}
//# sourceMappingURL=dataset.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/datasets/text_line_dataset.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* Represents a potentially large collection of text lines.
*
* The results are not batched.
*/
class text_line_dataset_TextLineDataset extends dataset_Dataset {
/**
* Create a `TextLineDataset`.
*
* @param input A `DataSource` providing a chunked, UTF8-encoded byte stream.
*/
constructor(input) {
super();
this.input = input;
}
async iterator() {
const inputIterator = await this.input.iterator();
const utf8Iterator = inputIterator.decodeUTF8();
const lineIterator = utf8Iterator.split("\n").map((line) => {
// Windows/DOS format text file has extra line breaker at the end of line.
if (line.endsWith("\r")) {
line = line.slice(0, -1);
}
return line;
});
return lineIterator;
}
}
//# sourceMappingURL=text_line_dataset.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/datasets/csv_dataset.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
const CODE_QUOTE = '"';
const STATE_OUT = Symbol("out");
const STATE_FIELD = Symbol("field");
const STATE_QUOTE = Symbol("quote");
const STATE_QUOTE_AFTER_QUOTE = Symbol("quoteafterquote");
const STATE_WITHIN_QUOTE_IN_QUOTE = Symbol("quoteinquote");
/**
* Represents a potentially large collection of delimited text records.
*
* The produced `TensorContainer`s each contain one key-value pair for
* every column of the table. When a field is empty in the incoming data, the
* resulting value is `undefined`, or throw error if it is required. Values
* that can be parsed as numbers are emitted as type `number`, other values
* are parsed as `string`.
*
* The results are not batched.
*/
/** @doc {heading: 'Data', subheading: 'Classes', namespace: 'data'} */
class csv_dataset_CSVDataset extends dataset_Dataset {
/**
* Create a `CSVDataset`.
*
* @param input A `DataSource` providing a chunked, UTF8-encoded byte stream.
* @param csvConfig (Optional) A CSVConfig object that contains configurations
* of reading and decoding from CSV file(s).
*
* hasHeader: (Optional) A boolean value that indicates whether the first
* row of provided CSV file is a header line with column names, and should
* not be included in the data. Defaults to `true`.
*
* columnNames: (Optional) A list of strings that corresponds to
* the CSV column names, in order. If provided, it ignores the column
* names inferred from the header row. If not provided, infers the column
* names from the first row of the records. If hasHeader is false and
* columnNames is not provided, this method throws an error.
*
* columnConfigs: (Optional) A dictionary whose key is column names, value
* is an object stating if this column is required, column's data type,
* default value, and if this column is label. If provided, keys must
* correspond to names provided in columnNames or inferred from the file
* header lines. If isLabel is true any column, returns an array of two
* items: the first item is a dict of features key/value pairs, the second
* item is a dict of labels key/value pairs. If no feature is marked as
* label, returns a dict of features only.
*
* configuredColumnsOnly (Optional) If true, only columns provided in
* columnConfigs will be parsed and provided during iteration.
*
* delimiter (Optional) The string used to parse each line of the input
* file. Defaults to `,`.
*/
constructor(input, csvConfig) {
super();
this.input = input;
this.hasHeader = true;
this.fullColumnNames = null;
this.columnNamesValidated = false;
this.columnConfigs = null;
this.configuredColumnsOnly = false;
this.delimiter = ",";
this.delimWhitespace = false;
this.base = new text_line_dataset_TextLineDataset(input);
if (!csvConfig) {
csvConfig = {};
}
this.hasHeader = csvConfig.hasHeader === false ? false : true;
this.fullColumnNames = csvConfig.columnNames;
this.columnConfigs = csvConfig.columnConfigs;
this.configuredColumnsOnly = csvConfig.configuredColumnsOnly;
if (csvConfig.delimWhitespace) {
dist["util"].assert(
csvConfig.delimiter == null,
() => "Delimiter should not be provided when delimWhitespace is true."
);
this.delimWhitespace = true;
this.delimiter = " ";
} else {
this.delimiter = csvConfig.delimiter ? csvConfig.delimiter : ",";
}
}
/**
* Returns column names of the csv dataset. If `configuredColumnsOnly` is
* true, return column names in `columnConfigs`. If `configuredColumnsOnly` is
* false and `columnNames` is provided, `columnNames`. If
* `configuredColumnsOnly` is false and `columnNames` is not provided, return
* all column names parsed from the csv file. For example usage please go to
* `tf.data.csv`.
*/
/** @doc {heading: 'Data', subheading: 'Classes'} */
async columnNames() {
if (!this.columnNamesValidated) {
await this.setColumnNames();
}
return this.configuredColumnsOnly
? Object.keys(this.columnConfigs)
: this.fullColumnNames;
}
/* 1) If `columnNames` is provided as string[], use this string[] as output
* keys in corresponding order. The length must match the number of inferred
* columns if `hasHeader` is true .
* 2) If `columnNames` is not provided, parse header line as `columnNames` if
* hasHeader is true. If `hasHeader` is false, throw an error.
* 3) If `columnConfigs` is provided, all the keys in `columnConfigs` must
* exist in parsed `columnNames`.
*/
async setColumnNames() {
const columnNamesFromFile = await this.maybeReadHeaderLine();
if (!this.fullColumnNames && !columnNamesFromFile) {
// Throw an error if columnNames is not provided and no header line.
throw new Error("Column names must be provided if there is no header line.");
} else if (this.fullColumnNames && columnNamesFromFile) {
// Check provided columnNames match header line.
dist["util"].assert(
columnNamesFromFile.length === this.fullColumnNames.length,
() =>
"The length of provided columnNames (" +
this.fullColumnNames.length.toString() +
") does not match the length of the header line read from " +
"file (" +
columnNamesFromFile.length.toString() +
")."
);
}
if (!this.fullColumnNames) {
this.fullColumnNames = columnNamesFromFile;
}
// Check if there are duplicate column names.
const counts = this.fullColumnNames.reduce((countAcc, name) => {
countAcc[name] = countAcc[name] + 1 || 1;
return countAcc;
}, {});
const duplicateNames = Object.keys(counts).filter((name) => counts[name] > 1);
dist["util"].assert(
duplicateNames.length === 0,
() => "Duplicate column names found: " + duplicateNames.toString()
);
// Check if keys in columnConfigs match columnNames.
if (this.columnConfigs) {
for (const key of Object.keys(this.columnConfigs)) {
const index = this.fullColumnNames.indexOf(key);
if (index === -1) {
throw new Error(
'The key "' +
key +
'" provided in columnConfigs does not match any of the column ' +
"names (" +
this.fullColumnNames.toString() +
")."
);
}
}
}
this.columnNamesValidated = true;
}
async maybeReadHeaderLine() {
if (this.hasHeader) {
const iter = await this.base.iterator();
const firstElement = await iter.next();
if (firstElement.done) {
throw new Error("No data was found for CSV parsing.");
}
const firstLine = firstElement.value;
const headers = this.parseRow(firstLine, false);
return headers;
} else {
return null;
}
}
async iterator() {
if (!this.columnNamesValidated) {
await this.setColumnNames();
}
let lines = await this.base.iterator();
if (this.hasHeader) {
// We previously read the first line to get the columnNames.
// Now that we're providing data, skip it.
lines = lines.skip(1);
}
return lines.map((x) => this.makeDataElement(x));
}
makeDataElement(line) {
const values = this.parseRow(line);
const features = {};
const labels = {};
for (let i = 0; i < this.fullColumnNames.length; i++) {
const key = this.fullColumnNames[i];
const config = this.columnConfigs ? this.columnConfigs[key] : null;
if (this.configuredColumnsOnly && !config) {
// This column is not selected.
continue;
} else {
const value = values[i];
let parsedValue = null;
if (value === "") {
// If default value is provided, use it. If default value is not
// provided, set as undefined.
if (config && config.default !== undefined) {
parsedValue = config.default;
} else if (config && (config.required || config.isLabel)) {
throw new Error(`Required column ${key} is empty in this line: ${line}`);
} else {
parsedValue = undefined;
}
} else {
// A value is present, so parse it based on type
const valueAsNum = Number(value);
if (isNaN(valueAsNum)) {
// The value is a string and this column is declared as boolean
// in config, parse it as boolean.
if (config && config.dtype === "bool") {
parsedValue = this.getBoolean(value);
} else {
// Set value as string
parsedValue = value;
}
} else if (!config || !config.dtype) {
// If this value is a number and no type config is provided, return
// it as number.
parsedValue = valueAsNum;
} else {
// If this value is a number and data type is provided, parse it
// according to provided data type.
switch (config.dtype) {
case "float32":
parsedValue = valueAsNum;
break;
case "int32":
parsedValue = Math.floor(valueAsNum);
break;
case "bool":
parsedValue = this.getBoolean(value);
break;
default:
parsedValue = valueAsNum;
}
}
}
// Check if this column is label.
config && config.isLabel
? (labels[key] = parsedValue)
: (features[key] = parsedValue);
}
}
// If label exists, return an object of features and labels as {xs:features,
// ys:labels}, otherwise return features only.
if (Object.keys(labels).length === 0) {
return features;
} else {
return { xs: features, ys: labels };
}
}
getBoolean(value) {
if (value === "1" || value.toLowerCase() === "true") {
return 1;
} else {
return 0;
}
}
// adapted from https://beta.observablehq.com/@mbostock/streaming-csv
parseRow(line, validateElementCount = true) {
const result = [];
let readOffset = 0;
const readLength = line.length;
let currentState = STATE_OUT;
// Goes through the line to parse quote.
for (let i = 0; i < readLength; i++) {
switch (currentState) {
// Before enter a new field
case STATE_OUT:
switch (line.charAt(i)) {
// Enter a quoted field
case CODE_QUOTE:
readOffset = i + 1;
currentState = STATE_QUOTE;
break;
// Read an empty field
case this.delimiter:
readOffset = i + 1;
// If delimiter is white space and configured to collapse
// multiple white spaces, ignore this white space.
if (this.delimiter === " " && this.delimWhitespace) {
break;
}
result.push("");
currentState = STATE_OUT;
break;
// Enter an unquoted field
default:
currentState = STATE_FIELD;
readOffset = i;
break;
}
break;
// In an unquoted field
case STATE_FIELD:
switch (line.charAt(i)) {
// Exit an unquoted field, add it to result
case this.delimiter:
result.push(line.substring(readOffset, i));
currentState = STATE_OUT;
readOffset = i + 1;
break;
default:
}
break;
// In a quoted field
case STATE_QUOTE:
switch (line.charAt(i)) {
// Read a quote after a quote
case CODE_QUOTE:
currentState = STATE_QUOTE_AFTER_QUOTE;
break;
default:
}
break;
// This state means it's right after a second quote in a field
case STATE_QUOTE_AFTER_QUOTE:
switch (line.charAt(i)) {
// Finished a quoted field
case this.delimiter:
result.push(line.substring(readOffset, i - 1));
currentState = STATE_OUT;
readOffset = i + 1;
break;
// Finished a quoted part in a quoted field
case CODE_QUOTE:
currentState = STATE_QUOTE;
break;
// In a quoted part in a quoted field
default:
currentState = STATE_WITHIN_QUOTE_IN_QUOTE;
break;
}
break;
case STATE_WITHIN_QUOTE_IN_QUOTE:
switch (line.charAt(i)) {
// Exit a quoted part in a quoted field
case CODE_QUOTE:
currentState = STATE_QUOTE;
break;
default:
}
break;
default:
}
}
// Adds last item based on if it is quoted.
if (currentState === STATE_QUOTE_AFTER_QUOTE) {
result.push(line.substring(readOffset, readLength - 1));
} else {
result.push(line.substring(readOffset));
}
// Check if each row has the same number of elements as column names.
if (validateElementCount && result.length !== this.fullColumnNames.length) {
throw new Error(
`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${result}`
);
}
return result;
}
}
// TODO(soergel): add more basic datasets for parity with tf.data
// tf.data.FixedLengthRecordDataset()
// tf.data.TFRecordDataset()
//# sourceMappingURL=csv_dataset.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/iterators/microphone_iterator.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.
*
* =============================================================================
*/
/**
* Provide a stream of tensors from microphone audio stream. The tensors are
* representing audio data as frequency-domain spectrogram generated with
* browser's native FFT. Tensors representing time-domain waveform is available
* based on configuration. Only works in browser environment.
*/
class microphone_iterator_MicrophoneIterator extends lazy_iterator["a" /* LazyIterator */] {
constructor(microphoneConfig) {
super();
this.microphoneConfig = microphoneConfig;
this.isClosed = false;
this.fftSize = microphoneConfig.fftSize || 1024;
const fftSizeLog2 = Math.log2(this.fftSize);
if (
this.fftSize < 0 ||
fftSizeLog2 < 4 ||
fftSizeLog2 > 14 ||
!Number.isInteger(fftSizeLog2)
) {
throw new Error(
`Invalid fftSize: it must be a power of 2 between ` +
`2 to 4 and 2 to 14, but got ${this.fftSize}`
);
}
this.numFrames = microphoneConfig.numFramesPerSpectrogram || 43;
this.sampleRateHz = microphoneConfig.sampleRateHz;
this.columnTruncateLength = microphoneConfig.columnTruncateLength || this.fftSize;
this.audioTrackConstraints = microphoneConfig.audioTrackConstraints;
this.smoothingTimeConstant = microphoneConfig.smoothingTimeConstant || 0;
this.includeSpectrogram = microphoneConfig.includeSpectrogram === false ? false : true;
this.includeWaveform = microphoneConfig.includeWaveform === true ? true : false;
if (!this.includeSpectrogram && !this.includeWaveform) {
throw new Error(
"Both includeSpectrogram and includeWaveform are false. " +
"At least one type of data should be returned."
);
}
}
summary() {
return `microphone`;
}
// Construct a MicrophoneIterator and start the audio stream.
static async create(microphoneConfig = {}) {
if (Object(dist["env"])().get("IS_NODE")) {
throw new Error("microphone API is only supported in browser environment.");
}
const microphoneIterator = new microphone_iterator_MicrophoneIterator(microphoneConfig);
// Call async function start() to initialize the audio stream.
await microphoneIterator.start();
return microphoneIterator;
}
// Start the audio stream and FFT.
async start() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({
audio: this.audioTrackConstraints == null ? true : this.audioTrackConstraints,
video: false,
});
} catch (e) {
throw new Error(`Error thrown while initializing video stream: ${e.message}`);
}
if (!this.stream) {
throw new Error("Could not obtain audio from microphone.");
}
const ctxConstructor =
// tslint:disable-next-line:no-any
window.AudioContext || window.webkitAudioContext;
this.audioContext = new ctxConstructor();
if (!this.sampleRateHz) {
// If sample rate is not provided, use the available sample rate on
// device.
this.sampleRateHz = this.audioContext.sampleRate;
} else if (this.audioContext.sampleRate !== this.sampleRateHz) {
throw new Error(
`Mismatch in sampling rate: ` +
`Expected: ${this.sampleRateHz}; ` +
`Actual: ${this.audioContext.sampleRate}`
);
}
const streamSource = this.audioContext.createMediaStreamSource(this.stream);
this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = this.fftSize * 2;
this.analyser.smoothingTimeConstant = this.smoothingTimeConstant;
streamSource.connect(this.analyser);
this.freqData = new Float32Array(this.fftSize);
this.timeData = new Float32Array(this.fftSize);
return;
}
async next() {
if (this.isClosed) {
return { value: null, done: true };
}
let spectrogramTensor;
let waveformTensor;
const audioDataQueue = await this.getAudioData();
if (this.includeSpectrogram) {
const freqData = this.flattenQueue(audioDataQueue.freqDataQueue);
spectrogramTensor = this.getTensorFromAudioDataArray(freqData, [
this.numFrames,
this.columnTruncateLength,
1,
]);
}
if (this.includeWaveform) {
const timeData = this.flattenQueue(audioDataQueue.timeDataQueue);
waveformTensor = this.getTensorFromAudioDataArray(timeData, [
this.numFrames * this.fftSize,
1,
]);
}
return {
value: { spectrogram: spectrogramTensor, waveform: waveformTensor },
done: false,
};
}
// Capture one result from the audio stream, and extract the value from
// iterator.next() result.
async capture() {
return (await this.next()).value;
}
async getAudioData() {
const freqDataQueue = [];
const timeDataQueue = [];
let currentFrames = 0;
return new Promise((resolve) => {
const intervalID = setInterval(() => {
if (this.includeSpectrogram) {
this.analyser.getFloatFrequencyData(this.freqData);
// If the audio stream is initializing, return empty queue.
if (this.freqData[0] === -Infinity) {
resolve({ freqDataQueue, timeDataQueue });
}
freqDataQueue.push(this.freqData.slice(0, this.columnTruncateLength));
}
if (this.includeWaveform) {
this.analyser.getFloatTimeDomainData(this.timeData);
timeDataQueue.push(this.timeData.slice());
}
// Clean interval and return when all frames have been collected
if (++currentFrames === this.numFrames) {
clearInterval(intervalID);
resolve({ freqDataQueue, timeDataQueue });
}
}, (this.fftSize / this.sampleRateHz) * 1e3);
});
}
// Stop the audio stream and pause the iterator.
stop() {
if (!this.isClosed) {
this.isClosed = true;
this.analyser.disconnect();
this.audioContext.close();
if (this.stream != null && this.stream.getTracks().length > 0) {
this.stream.getTracks()[0].stop();
}
}
}
// Override toArray() function to prevent collecting.
toArray() {
throw new Error("Can not convert infinite audio stream to array.");
}
// Return audio sampling rate in Hz
getSampleRate() {
return this.sampleRateHz;
}
flattenQueue(queue) {
const frameSize = queue[0].length;
const freqData = new Float32Array(queue.length * frameSize);
queue.forEach((data, i) => freqData.set(data, i * frameSize));
return freqData;
}
getTensorFromAudioDataArray(freqData, shape) {
const vals = new Float32Array(dist["util"].sizeFromShape(shape));
// If the data is less than the output shape, the rest is padded with zeros.
vals.set(freqData, vals.length - freqData.length);
return Object(dist["tensor"])(vals, shape);
}
}
//# sourceMappingURL=microphone_iterator.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/iterators/webcam_iterator.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* Provide a stream of image tensors from webcam video stream. Only works in
* browser environment.
*/
class webcam_iterator_WebcamIterator extends lazy_iterator["a" /* LazyIterator */] {
constructor(webcamVideoElement, webcamConfig) {
super();
this.webcamVideoElement = webcamVideoElement;
this.webcamConfig = webcamConfig;
this.isClosed = true;
this.resize = false;
if (this.needToResize()) {
this.resize = true;
this.cropSize = [this.webcamConfig.resizeHeight, this.webcamConfig.resizeWidth];
this.cropBoxInd = Object(dist["tensor1d"])([0], "int32");
if (this.webcamConfig.centerCrop) {
// Calculate the box based on resizing shape.
const widthCroppingRatio =
(this.webcamConfig.resizeWidth * 1.0) / this.webcamVideoElement.width;
const heightCroppingRatio =
(this.webcamConfig.resizeHeight * 1.0) / this.webcamVideoElement.height;
const widthCropStart = (1 - widthCroppingRatio) / 2;
const heightCropStart = (1 - heightCroppingRatio) / 2;
const widthCropEnd = widthCropStart + widthCroppingRatio;
const heightCropEnd = heightCroppingRatio + heightCropStart;
this.cropBox = Object(dist["tensor2d"])(
[heightCropStart, widthCropStart, heightCropEnd, widthCropEnd],
[1, 4]
);
} else {
this.cropBox = Object(dist["tensor2d"])([0, 0, 1, 1], [1, 4]);
}
}
}
summary() {
return `webcam`;
}
// Construct a WebcamIterator and start it's video stream.
static async create(webcamVideoElement, webcamConfig = {}) {
if (Object(dist["env"])().get("IS_NODE")) {
throw new Error("tf.data.webcam is only supported in browser environment.");
}
if (!webcamVideoElement) {
// If webcam video element is not provided, create a hidden video element
// with provided width and height.
webcamVideoElement = document.createElement("video");
if (!webcamConfig.resizeWidth || !webcamConfig.resizeHeight) {
throw new Error(
"Please provide webcam video element, or resizeWidth and " +
"resizeHeight to create a hidden video element."
);
}
webcamVideoElement.width = webcamConfig.resizeWidth;
webcamVideoElement.height = webcamConfig.resizeHeight;
}
const webcamIterator = new webcam_iterator_WebcamIterator(
webcamVideoElement,
webcamConfig
);
// Call async function to initialize the video stream.
await webcamIterator.start();
return webcamIterator;
}
// Async function to start video stream.
async start() {
if (this.webcamConfig.facingMode) {
dist["util"].assert(
this.webcamConfig.facingMode === "user" ||
this.webcamConfig.facingMode === "environment",
() =>
`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. ` +
`Please provide 'user' or 'environment'`
);
}
try {
this.stream = await navigator.mediaDevices.getUserMedia({
video: {
deviceId: this.webcamConfig.deviceId,
facingMode: this.webcamConfig.facingMode ? this.webcamConfig.facingMode : "user",
width: this.webcamVideoElement.width,
height: this.webcamVideoElement.height,
},
});
} catch (e) {
// Modify the error message but leave the stack trace intact
e.message = `Error thrown while initializing video stream: ${e.message}`;
throw e;
}
if (!this.stream) {
throw new Error("Could not obtain video from webcam.");
}
// Older browsers may not have srcObject
try {
this.webcamVideoElement.srcObject = this.stream;
} catch (error) {
console.log(error);
this.webcamVideoElement.src = window.URL.createObjectURL(this.stream);
}
// Start the webcam video stream
this.webcamVideoElement.play();
this.isClosed = false;
return new Promise((resolve) => {
// Add event listener to make sure the webcam has been fully initialized.
this.webcamVideoElement.onloadedmetadata = () => {
resolve();
};
});
}
async next() {
if (this.isClosed) {
return { value: null, done: true };
}
let img;
try {
img = dist["browser"].fromPixels(this.webcamVideoElement);
} catch (e) {
throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(e)}`);
}
if (this.resize) {
try {
return { value: this.cropAndResizeFrame(img), done: false };
} catch (e) {
throw new Error(`Error thrown cropping the video: ${e.message}`);
} finally {
img.dispose();
}
} else {
return { value: img, done: false };
}
}
needToResize() {
// If resizeWidth and resizeHeight are provided, and different from the
// width and height of original HTMLVideoElement, then resizing and cropping
// is required.
if (
this.webcamConfig.resizeWidth &&
this.webcamConfig.resizeHeight &&
(this.webcamVideoElement.width !== this.webcamConfig.resizeWidth ||
this.webcamVideoElement.height !== this.webcamConfig.resizeHeight)
) {
return true;
}
return false;
}
// Cropping and resizing each frame based on config
cropAndResizeFrame(img) {
return Object(dist["tidy"])(() => {
const expandedImage = img.toFloat().expandDims(0);
let resizedImage;
resizedImage = dist["image"].cropAndResize(
expandedImage,
this.cropBox,
this.cropBoxInd,
this.cropSize,
"bilinear"
);
// Extract image from batch cropping.
const shape = resizedImage.shape;
return resizedImage.reshape(shape.slice(1));
});
}
// Capture one frame from the video stream, and extract the value from
// iterator.next() result.
async capture() {
return (await this.next()).value;
}
// Stop the video stream and pause webcam iterator.
stop() {
const tracks = this.stream.getTracks();
tracks.forEach((track) => track.stop());
try {
this.webcamVideoElement.srcObject = null;
} catch (error) {
console.log(error);
this.webcamVideoElement.src = null;
}
this.isClosed = true;
}
// Override toArray() function to prevent collecting.
toArray() {
throw new Error("Can not convert infinite video stream to array.");
}
}
//# sourceMappingURL=webcam_iterator.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/datasource.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* Represents a data source readable as a stream of binary data chunks.
*
* Because `Dataset`s can be read repeatedly (via `Dataset.iterator()`), this
* provides a means to repeatedly create streams from the underlying data
* sources.
*/
class DataSource {}
// TODO(soergel): consider convenience factory functions here
// in combination with chainable source->dataset above, e.g.:
// tf.data.url(...).asCsvDataset().shuffle().batch()
//# sourceMappingURL=datasource.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-data/dist/iterators/byte_chunk_iterator.js
var byte_chunk_iterator = __webpack_require__(57);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/iterators/file_chunk_iterator.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
// inspired by https://github.com/maxogden/filereader-stream
/**
* Provide a stream of chunks from a File, Blob, or Uint8Array.
* @param file The source File, Blob or Uint8Array.
* @param options Optional settings controlling file reading.
* @returns a lazy Iterator of Uint8Arrays containing sequential chunks of the
* input File, Blob or Uint8Array.
*/
class file_chunk_iterator_FileChunkIterator extends byte_chunk_iterator[
"a" /* ByteChunkIterator */
] {
constructor(file, options = {}) {
super();
this.file = file;
this.options = options;
dist["util"].assert(
file instanceof Uint8Array ||
(Object(dist["env"])().get("IS_BROWSER")
? file instanceof File || file instanceof Blob
: false),
() => "FileChunkIterator only supports File, Blob and Uint8Array " + "right now."
);
this.offset = options.offset || 0;
// default 1MB chunk has tolerable perf on large files
this.chunkSize = options.chunkSize || 1024 * 1024;
}
summary() {
return `FileChunks ${this.file}`;
}
async next() {
if (
this.offset >= (this.file instanceof Uint8Array ? this.file.byteLength : this.file.size)
) {
return { value: null, done: true };
}
const chunk = new Promise((resolve, reject) => {
const end = this.offset + this.chunkSize;
if (this.file instanceof Uint8Array) {
// Note if end > this.uint8Array.byteLength, we just get a small last
// chunk.
resolve(new Uint8Array(this.file.slice(this.offset, end)));
} else {
// This branch assumes that this.file type is File or Blob, which
// means it is in the browser environment.
// TODO(soergel): is this a performance issue?
const fileReader = new FileReader();
fileReader.onload = (event) => {
let data = fileReader.result;
// Not sure we can trust the return type of
// FileReader.readAsArrayBuffer See e.g.
// https://github.com/node-file-api/FileReader/issues/2
if (data instanceof ArrayBuffer) {
data = new Uint8Array(data);
}
if (!(data instanceof Uint8Array)) {
return reject(new TypeError("FileReader returned unknown type."));
}
resolve(data);
};
fileReader.onabort = (event) => {
return reject(new Error("Aborted"));
};
fileReader.onerror = (event) => {
return reject(new Error(event.type));
};
// TODO(soergel): better handle onabort, onerror
// Note if end > this.file.size, we just get a small last chunk.
const slice = this.file.slice(this.offset, end);
// We can't use readAsText here (even if we know the file is text)
// because the slice boundary may fall within a multi-byte character.
fileReader.readAsArrayBuffer(slice);
}
this.offset = end;
});
return { value: await chunk, done: false };
}
}
//# sourceMappingURL=file_chunk_iterator.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/iterators/url_chunk_iterator.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* Provide a stream of chunks from a URL.
*
* Note this class first downloads the entire file into memory before providing
* the first element from the stream. This is because the Fetch API does not
* yet reliably provide a reader stream for the response body.
*/
async function urlChunkIterator(url, options = {}) {
let urlString;
let requestInit;
if (typeof url === "string") {
urlString = url;
} else {
urlString = url.url;
requestInit = getRequestInitFromRequest(url);
}
const response = await dist["util"].fetch(urlString, requestInit);
if (response.ok) {
const uint8Array = new Uint8Array(await response.arrayBuffer());
return new file_chunk_iterator_FileChunkIterator(uint8Array, options);
} else {
throw new Error(response.statusText);
}
}
// Generate RequestInit from Request to match tf.util.fetch signature.
const getRequestInitFromRequest = (request) => {
const init = {
method: request.method,
headers: request.headers,
body: request.body,
mode: request.mode,
credentials: request.credentials,
cache: request.cache,
redirect: request.redirect,
referrer: request.referrer,
integrity: request.integrity,
};
return init;
};
//# sourceMappingURL=url_chunk_iterator.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/util/source_util.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
// Skip tslint any type check cause this method is aiming to check type of
// input.
// tslint:disable-next-line:no-any
function isLocalPath(source) {
return typeof source === "string" && source.substr(0, 7) === "file://";
}
//# sourceMappingURL=source_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/sources/file_data_source.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* Represents a file, blob, or Uint8Array readable as a stream of binary data
* chunks.
*/
class file_data_source_FileDataSource extends DataSource {
/**
* Create a `FileDataSource`.
*
* @param input Local file path, or `File`/`Blob`/`Uint8Array` object to
* read. Local file only works in node environment.
* @param options Options passed to the underlying `FileChunkIterator`s,
* such as {chunksize: 1024}.
*/
constructor(input, options = {}) {
super();
this.input = input;
this.options = options;
}
async iterator() {
if (isLocalPath(this.input) && Object(dist["env"])().get("IS_NODE")) {
// tslint:disable-next-line:no-require-imports
const fs = __webpack_require__(79);
this.input = fs.readFileSync(this.input.substr(7));
}
// TODO(kangyizhang): Add LocalFileChunkIterator to split local streaming
// with file in browser.
return new file_chunk_iterator_FileChunkIterator(this.input, this.options);
}
}
//# sourceMappingURL=file_data_source.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/sources/url_data_source.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/*
* Represents a URL readable as a stream of binary data chunks.
*/
class url_data_source_URLDataSource extends DataSource {
/**
* Create a `URLDataSource`.
*
* @param url A source URL string, or a `Request` object.
* @param options Options passed to the underlying `FileChunkIterator`s,
* such as {chunksize: 1024}.
*/
constructor(url, fileOptions = {}) {
super();
this.url = url;
this.fileOptions = fileOptions;
}
// TODO(soergel): provide appropriate caching options. Currently this
// will download the URL anew for each call to iterator(). Since we have
// to treat the downloaded file as a blob/buffer anyway, we may as well retain
// it-- but that raises GC issues. Also we may want a persistent disk cache.
async iterator() {
if (isLocalPath(this.url)) {
return new file_data_source_FileDataSource(this.url, this.fileOptions).iterator();
} else {
return urlChunkIterator(this.url, this.fileOptions);
}
}
}
//# sourceMappingURL=url_data_source.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/readers.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* Create a `CSVDataset` by reading and decoding CSV file(s) from provided URL
* or local path if it's in Node environment.
*
* Note: If isLabel in columnConfigs is `true` for at least one column, the
* element in returned `CSVDataset` will be an object of
* `{xs:features, ys:labels}`: xs is a dict of features key/value pairs, ys
* is a dict of labels key/value pairs. If no column is marked as label,
* returns a dict of features only.
*
* ```js
* const csvUrl =
* 'https://storage.googleapis.com/tfjs-examples/multivariate-linear-regression/data/boston-housing-train.csv';
*
* async function run() {
* // We want to predict the column "medv", which represents a median value of
* // a home (in $1000s), so we mark it as a label.
* const csvDataset = tf.data.csv(
* csvUrl, {
* columnConfigs: {
* medv: {
* isLabel: true
* }
* }
* });
*
* // Number of features is the number of column names minus one for the label
* // column.
* const numOfFeatures = (await csvDataset.columnNames()).length - 1;
*
* // Prepare the Dataset for training.
* const flattenedDataset =
* csvDataset
* .map(({xs, ys}) =>
* {
* // Convert xs(features) and ys(labels) from object form (keyed by
* // column name) to array form.
* return {xs:Object.values(xs), ys:Object.values(ys)};
* })
* .batch(10);
*
* // Define the model.
* const model = tf.sequential();
* model.add(tf.layers.dense({
* inputShape: [numOfFeatures],
* units: 1
* }));
* model.compile({
* optimizer: tf.train.sgd(0.000001),
* loss: 'meanSquaredError'
* });
*
* // Fit the model using the prepared Dataset
* return model.fitDataset(flattenedDataset, {
* epochs: 10,
* callbacks: {
* onEpochEnd: async (epoch, logs) => {
* console.log(epoch + ':' + logs.loss);
* }
* }
* });
* }
*
* await run();
* ```
*
* @param source URL or local path to get CSV file. If it's a local path, it
* must have prefix `file://` and it only works in node environment.
* @param csvConfig (Optional) A CSVConfig object that contains configurations
* of reading and decoding from CSV file(s).
*/
/**
* @doc {
* heading: 'Data',
* subheading: 'Creation',
* namespace: 'data',
* configParamIndices: [1]
* }
*/
function csv(source, csvConfig = {}) {
return new csv_dataset_CSVDataset(new url_data_source_URLDataSource(source), csvConfig);
}
/**
* Create a `Dataset` that produces each element by calling a provided function.
*
* Note that repeated iterations over this `Dataset` may produce different
* results, because the function will be called anew for each element of each
* iteration.
*
* Also, beware that the sequence of calls to this function may be out of order
* in time with respect to the logical order of the Dataset. This is due to the
* asynchronous lazy nature of stream processing, and depends on downstream
* transformations (e.g. .shuffle()). If the provided function is pure, this is
* no problem, but if it is a closure over a mutable state (e.g., a traversal
* pointer), then the order of the produced elements may be scrambled.
*
* ```js
* let i = -1;
* const func = () =>
* ++i < 5 ? {value: i, done: false} : {value: null, done: true};
* const ds = tf.data.func(func);
* await ds.forEachAsync(e => console.log(e));
* ```
*
* @param f A function that produces one data element on each call.
*/
function func(f) {
const iter = Object(lazy_iterator["e" /* iteratorFromFunction */])(f);
return datasetFromIteratorFn(async () => iter);
}
/**
* Create a `Dataset` that produces each element from provided JavaScript
* generator, which is a function*
* (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generator_functions),
* or a function that returns an
* iterator
* (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generator_functions).
*
* The returned iterator should have `.next()` function that returns element in
* format of `{value: TensorContainer, done:boolean}`.
*
* Example of creating a dataset from an iterator factory:
* ```js
* function makeIterator() {
* const numElements = 10;
* let index = 0;
*
* const iterator = {
* next: () => {
* let result;
* if (index < numElements) {
* result = {value: index, done: false};
* index++;
* return result;
* }
* return {value: index, done: true};
* }
* };
* return iterator;
* }
* const ds = tf.data.generator(makeIterator);
* await ds.forEachAsync(e => console.log(e));
* ```
*
* Example of creating a dataset from a generator:
* ```js
* function* dataGenerator() {
* const numElements = 10;
* let index = 0;
* while (index < numElements) {
* const x = index;
* index++;
* yield x;
* }
* }
*
* const ds = tf.data.generator(dataGenerator);
* await ds.forEachAsync(e => console.log(e));
* ```
*
* @param generator A Javascript generator function that returns a JavaScript
* iterator.
*/
/**
* @doc {
* heading: 'Data',
* subheading: 'Creation',
* namespace: 'data',
* configParamIndices: [1]
* }
*/
function readers_generator(generator) {
return datasetFromIteratorFn(async () => {
const gen = await generator();
return Object(lazy_iterator["e" /* iteratorFromFunction */])(() => gen.next());
});
}
/**
* Create an iterator that generate `Tensor`s from webcam video stream. This API
* only works in Browser environment when the device has webcam.
*
* Note: this code snippet only works when the device has a webcam. It will
* request permission to open the webcam when running.
* ```js
* const videoElement = document.createElement('video');
* videoElement.width = 100;
* videoElement.height = 100;
* const cam = await tf.data.webcam(videoElement);
* const img = await cam.capture();
* img.print();
* cam.stop();
* ```
*
* @param webcamVideoElement A `HTMLVideoElement` used to play video from
* webcam. If this element is not provided, a hidden `HTMLVideoElement` will
* be created. In that case, `resizeWidth` and `resizeHeight` must be
* provided to set the generated tensor shape.
* @param webcamConfig A `WebcamConfig` object that contains configurations of
* reading and manipulating data from webcam video stream.
*/
/**
* @doc {
* heading: 'Data',
* subheading: 'Creation',
* namespace: 'data',
* ignoreCI: true
* }
*/
async function webcam(webcamVideoElement, webcamConfig) {
return webcam_iterator_WebcamIterator.create(webcamVideoElement, webcamConfig);
}
/**
* Create an iterator that generate frequency-domain spectrogram `Tensor`s from
* microphone audio stream with browser's native FFT. This API only works in
* browser environment when the device has microphone.
*
* Note: this code snippet only works when the device has a microphone. It will
* request permission to open the microphone when running.
* ```js
* const mic = await tf.data.microphone({
* fftSize: 1024,
* columnTruncateLength: 232,
* numFramesPerSpectrogram: 43,
* sampleRateHz:44100,
* includeSpectrogram: true,
* includeWaveform: true
* });
* const audioData = await mic.capture();
* const spectrogramTensor = audioData.spectrogram;
* spectrogramTensor.print();
* const waveformTensor = audioData.waveform;
* waveformTensor.print();
* mic.stop();
* ```
*
* @param microphoneConfig A `MicrophoneConfig` object that contains
* configurations of reading audio data from microphone.
*/
/**
* @doc {
* heading: 'Data',
* subheading: 'Creation',
* namespace: 'data',
* ignoreCI: true
* }
*/
async function microphone(microphoneConfig) {
return microphone_iterator_MicrophoneIterator.create(microphoneConfig);
}
//# sourceMappingURL=readers.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/version.js
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
const version = "2.0.1";
//# sourceMappingURL=version.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-data/dist/index.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
//# sourceMappingURL=index.js.map
/***/
},
/* 89 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "MathBackendCPU", function () {
return /* reexport */ base["a" /* MathBackendCPU */];
});
__webpack_require__.d(__webpack_exports__, "version_cpu", function () {
return /* reexport */ base["c" /* version_cpu */];
});
__webpack_require__.d(__webpack_exports__, "shared", function () {
return /* reexport */ base["b" /* shared */];
});
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js + 269 modules
var dist = __webpack_require__(0);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/base.js + 3 modules
var base = __webpack_require__(31);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/cpu_util.js
var cpu_util = __webpack_require__(9);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/kernel_utils.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function createBinaryKernelConfig(name, op) {
return {
kernelName: name,
backendName: "cpu",
kernelFunc: ({ inputs, backend }) => {
const { a, b } = inputs;
const cpuBackend = backend;
Object(cpu_util["a" /* assertNotComplex */])([a, b], name);
const aVals = cpuBackend.data.get(a.dataId).values;
const bVals = cpuBackend.data.get(b.dataId).values;
const [resultData, resultShape] = op(a.shape, b.shape, aVals, bVals, a.dtype);
const dataId = cpuBackend.write(resultData, resultShape, a.dtype);
return { dataId, shape: resultShape, dtype: a.dtype };
},
};
}
function createBinaryKernelImpl(op) {
return (aShape, bShape, aVals, bVals, dtype) => {
const newShape = dist["backend_util"].assertAndGetBroadcastShape(aShape, bShape);
const resultRank = newShape.length;
const resultStrides = dist["util"].computeStrides(newShape);
const resultSize = dist["util"].sizeFromShape(newShape);
const result = dist["util"].getTypedArrayFromDType(dtype, resultSize);
const aRank = aShape.length;
const bRank = bShape.length;
const aStrides = dist["util"].computeStrides(aShape);
const bStrides = dist["util"].computeStrides(bShape);
const aBroadcastDims = dist["backend_util"].getBroadcastDims(aShape, newShape);
const bBroadcastDims = dist["backend_util"].getBroadcastDims(bShape, newShape);
if (aBroadcastDims.length + bBroadcastDims.length === 0) {
for (let i = 0; i < result.length; ++i) {
result[i] = op(aVals[i % aVals.length], bVals[i % bVals.length]);
}
} else {
for (let i = 0; i < result.length; ++i) {
const loc = dist["util"].indexToLoc(i, resultRank, resultStrides);
const aLoc = loc.slice(-aRank);
aBroadcastDims.forEach((d) => (aLoc[d] = 0));
const aIndex = dist["util"].locToIndex(aLoc, aRank, aStrides);
const bLoc = loc.slice(-bRank);
bBroadcastDims.forEach((d) => (bLoc[d] = 0));
const bIndex = dist["util"].locToIndex(bLoc, bRank, bStrides);
result[i] = op(aVals[aIndex], bVals[bIndex]);
}
}
return [result, newShape];
};
}
//# sourceMappingURL=kernel_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Div_impl.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const divImpl = createBinaryKernelImpl((a, b) => a / b);
//# sourceMappingURL=Div_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Div.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const divConfig = createBinaryKernelConfig(dist["Div"], divImpl);
//# sourceMappingURL=Div.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Max_impl.js
var Max_impl = __webpack_require__(37);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Transpose_impl.js
var Transpose_impl = __webpack_require__(30);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Max.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxConfig = {
kernelName: dist["Max"],
backendName: "cpu",
kernelFunc: ({ inputs, attrs, backend }) => {
const { x } = inputs;
const { reductionIndices } = attrs;
const cpuBackend = backend;
let xShape = x.shape;
const xRank = xShape.length;
const origAxes = dist["util"].parseAxisParam(reductionIndices, xShape);
let axes = origAxes;
const permutedAxes = dist["backend_util"].getAxesPermutation(axes, xRank);
let xVals = cpuBackend.data.get(x.dataId).values;
if (permutedAxes != null) {
const newShape = new Array(xRank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = xShape[permutedAxes[i]];
}
xVals = Object(Transpose_impl["a" /* transposeImpl */])(
xVals,
xShape,
x.dtype,
permutedAxes,
newShape
);
axes = dist["backend_util"].getInnerMostAxes(axes.length, xRank);
xShape = newShape;
}
Object(cpu_util["a" /* assertNotComplex */])(x, "max");
dist["backend_util"].assertAxesAreInnerMostDims("max", axes, xRank);
const [maxOutShape, reduceShape] = dist["backend_util"].computeOutAndReduceShapes(
xShape,
axes
);
const reduceSize = dist["util"].sizeFromShape(reduceShape);
const result = Object(Max_impl["a" /* maxImpl */])(
xVals,
reduceSize,
maxOutShape,
x.dtype
);
const dataId = cpuBackend.write(result, maxOutShape, x.dtype);
return { dataId, shape: maxOutShape, dtype: x.dtype };
},
};
//# sourceMappingURL=Max.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/pool_utils.js
var pool_utils = __webpack_require__(26);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/MaxPoolWithArgmax_impl.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function maxPoolWithArgmaxImpl(xValues, xShape, dtype, includeBatchInIndex, convInfo) {
const strides = dist["util"].computeStrides(xShape);
const maxPools = Object(pool_utils["b" /* pool */])(
xValues,
xShape,
dtype,
strides,
convInfo,
"max"
);
const maxPositions = Object(pool_utils["a" /* maxPoolPositions */])(
xValues,
xShape,
dtype,
convInfo,
true,
includeBatchInIndex
);
return [maxPools.values, maxPositions.values];
}
//# sourceMappingURL=MaxPoolWithArgmax_impl.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/MaxPoolWithArgmax.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxPoolWithArgmaxConfig = {
kernelName: dist["MaxPoolWithArgmax"],
backendName: "cpu",
kernelFunc: ({ inputs, attrs, backend }) => {
const { x } = inputs;
const { filterSize, strides, pad, includeBatchInIndex } = attrs;
const cpuBackend = backend;
Object(cpu_util["a" /* assertNotComplex */])(x, "MaxPoolWithArgmax");
const values = cpuBackend.data.get(x.dataId).values;
const convInfo = dist["backend_util"].computePool2DInfo(
x.shape,
filterSize,
strides,
[1, 1],
pad
);
const [pooled, indexes] = maxPoolWithArgmaxImpl(
values,
x.shape,
x.dtype,
includeBatchInIndex,
convInfo
);
const pooledDataId = cpuBackend.write(pooled, convInfo.outShape, x.dtype);
const indexesDataId = cpuBackend.write(indexes, convInfo.outShape, x.dtype);
return [
{ dataId: pooledDataId, shape: convInfo.outShape, dtype: x.dtype },
{ dataId: indexesDataId, shape: convInfo.outShape, dtype: "int32" },
];
},
};
//# sourceMappingURL=MaxPoolWithArgmax.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/NonMaxSuppressionV5.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.
* =============================================================================
*/
const nonMaxSuppressionV5 = dist["kernel_impls"].nonMaxSuppressionV5;
const nonMaxSuppressionV5Config = {
kernelName: dist["NonMaxSuppressionV5"],
backendName: "cpu",
kernelFunc: ({ inputs, backend, attrs }) => {
const { boxes, scores } = inputs;
const { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma } = attrs;
const cpuBackend = backend;
Object(cpu_util["a" /* assertNotComplex */])(boxes, "NonMaxSuppressionWithScore");
const boxesVals = cpuBackend.data.get(boxes.dataId).values;
const scoresVals = cpuBackend.data.get(scores.dataId).values;
const maxOutputSizeVal = maxOutputSize;
const iouThresholdVal = iouThreshold;
const scoreThresholdVal = scoreThreshold;
const softNmsSigmaVal = softNmsSigma;
const { selectedIndices, selectedScores } = nonMaxSuppressionV5(
boxesVals,
scoresVals,
maxOutputSizeVal,
iouThresholdVal,
scoreThresholdVal,
softNmsSigmaVal
);
return [selectedIndices, selectedScores];
},
};
//# sourceMappingURL=NonMaxSuppressionV5.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Square.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.
* =============================================================================
*/
const squareConfig = {
kernelName: dist["Square"],
backendName: "cpu",
kernelFunc: ({ inputs, backend }) => {
const { x } = inputs;
const cpuBackend = backend;
Object(cpu_util["a" /* assertNotComplex */])(x, "square");
const values = cpuBackend.data.get(x.dataId).values;
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = value * value;
}
const dataId = cpuBackend.write(newValues, x.shape, x.dtype);
return { dataId, shape: x.shape, dtype: x.dtype };
},
};
//# sourceMappingURL=Square.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/SquaredDifference.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const squaredDifferenceImpl = createBinaryKernelImpl((aVal, bVal) => {
const diff = aVal - bVal;
return diff * diff;
});
const squaredDifferenceConfig = createBinaryKernelConfig(
dist["SquaredDifference"],
squaredDifferenceImpl
);
//# sourceMappingURL=SquaredDifference.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Transpose.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const transposeConfig = {
kernelName: dist["Transpose"],
backendName: "cpu",
kernelFunc: ({ inputs, attrs, backend }) => {
const { x } = inputs;
const { perm } = attrs;
const cpuBackend = backend;
Object(cpu_util["a" /* assertNotComplex */])(x, "transpose");
const xRank = x.shape.length;
const newShape = new Array(xRank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = x.shape[perm[i]];
}
const values = cpuBackend.data.get(x.dataId).values;
const result = Object(Transpose_impl["a" /* transposeImpl */])(
values,
x.shape,
x.dtype,
perm,
newShape
);
const dataId = cpuBackend.write(result, newShape, x.dtype);
return { dataId, shape: newShape, dtype: x.dtype };
},
};
//# sourceMappingURL=Transpose.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/register_all_kernels.js
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// We explicitly import the modular kernels so they get registered in the
// global registry when we compile the library. A modular build would replace
// the contents of this file and import only the kernels that are needed.
// List all kernel configs here
const kernelConfigs = [
nonMaxSuppressionV5Config,
squareConfig,
squaredDifferenceConfig,
divConfig,
transposeConfig,
maxPoolWithArgmaxConfig,
maxConfig,
];
for (const kernelConfig of kernelConfigs) {
Object(dist["registerKernel"])(kernelConfig);
}
//# sourceMappingURL=register_all_kernels.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-backend-cpu/dist/index.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Side effects for default initialization of MathBackendCPU
Object(dist["registerBackend"])(
"cpu",
() => new base["a" /* MathBackendCPU */](),
1 /* priority */
);
// All exports from this package should be in base.
//# sourceMappingURL=index.js.map
/***/
},
/* 90 */
/***/ function (__webpack_module__, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs/dist/tf.node.js
var tf_node = __webpack_require__(60);
// EXTERNAL MODULE: ./node_modules/regression/dist/regression.js
var regression = __webpack_require__(80);
// CONCATENATED MODULE: ./src/params.mjs
const params = {
moveTickSize: 50,
videoContainerId: "webgazerVideoContainer",
videoElementId: "webgazerVideoFeed",
videoElementCanvasId: "webgazerVideoCanvas",
faceOverlayId: "webgazerFaceOverlay",
faceFeedbackBoxId: "webgazerFaceFeedbackBox",
gazeDotId: "webgazerGazeDot",
videoViewerWidth: 320,
videoViewerHeight: 240,
faceFeedbackBoxRatio: 0.66,
// View options
showVideo: true,
mirrorVideo: true,
showFaceOverlay: true,
showFaceFeedbackBox: true,
showGazeDot: true,
camConstraints: {
video: {
width: { min: 320, ideal: 640, max: 1920 },
height: { min: 240, ideal: 480, max: 1080 },
facingMode: "user",
},
},
dataTimestep: 50,
showVideoPreview: true,
applyKalmanFilter: true,
// Whether or not to store accuracy eigenValues, used by the calibration example file
storingPoints: false,
};
/* harmony default export */ var src_params = params;
// CONCATENATED MODULE: ./src/dom_util.mjs
// helper functions
/**
* Provides requestAnimationFrame in a cross browser way.
*/
window.requestAnimFrame = (function () {
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (
/* function FrameRequestCallback */ callback,
/* DOMElement Element */ element
) {
return window.setTimeout(callback, 1000 / 60);
}
);
})();
/**
* Provides cancelRequestAnimationFrame in a cross browser way.
*/
window.cancelRequestAnimFrame = (function () {
return (
window.cancelCancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.clearTimeout
);
})();
// EXTERNAL MODULE: ./node_modules/localforage/dist/localforage.js
var localforage = __webpack_require__(32);
// EXTERNAL MODULE: ./node_modules/@tensorflow-models/facemesh/dist/index.js
var dist = __webpack_require__(59);
// CONCATENATED MODULE: ./src/facemesh.mjs
/**
* Constructor of TFFaceMesh object
* @constructor
* */
const TFFaceMesh = function () {
//Backend options are webgl, wasm, and CPU.
//For recent laptops WASM is better than WebGL.
//TODO: This hack makes loading the model block the UI. We should fix that
// this.model = (async () => { return await facemesh.load({"maxFaces":1}) })();
this.model = dist.load({ maxFaces: 1 });
this.predictionReady = false;
};
// Global variable for face landmark positions array
TFFaceMesh.prototype.positionsArray = null;
/**
* Isolates the two patches that correspond to the user's eyes
* @param {Canvas} imageCanvas - canvas corresponding to the webcam stream
* @param {Number} width - of imageCanvas
* @param {Number} height - of imageCanvas
* @return {Object} the two eye-patches, first left, then right eye
*/
TFFaceMesh.prototype.getEyePatches = async function (imageCanvas, width, height) {
if (imageCanvas.width === 0) {
return null;
}
// Load the MediaPipe facemesh model.
const model = await this.model;
// Pass in a video stream (or an image, canvas, or 3D tensor) to obtain an
// array of detected faces from the MediaPipe graph.
const predictions = await model.estimateFaces(imageCanvas);
if (predictions.length == 0) {
return false;
}
// Save positions to global variable
this.positionsArray = predictions[0].scaledMesh;
const positions = this.positionsArray;
// Fit the detected eye in a rectangle. [20200626 xk] not clear which approach is better
// https://raw.githubusercontent.com/tensorflow/tfjs-models/master/facemesh/mesh_map.jpg
// // Maintains a relatively stable shape of the bounding box at the cost of cutting off parts of
// // the eye when the eye is tilted.
// var leftOriginX = Math.round(positions[130][0]);
// var leftOriginY = Math.round(positions[27][1]);
// var leftWidth = Math.round(positions[243][0] - leftOriginX);
// var leftHeight = Math.round(positions[23][1] - leftOriginY);
// var rightOriginX = Math.round(positions[463][0]);
// var rightOriginY = Math.round(positions[257][1]);
// var rightWidth = Math.round(positions[359][0] - rightOriginX);
// var rightHeight = Math.round(positions[253][1] - rightOriginY);
// Won't really cut off any parts of the eye, at the cost of warping the shape (i.e. height/
// width ratio) of the bounding box.
var leftOriginX = Math.round(
Math.min(positions[247][0], positions[130][0], positions[25][0])
);
var leftOriginY = Math.round(
Math.min(positions[247][1], positions[27][1], positions[190][1])
);
var leftWidth = Math.round(
Math.max(positions[190][0], positions[243][0], positions[233][0]) - leftOriginX
);
var leftHeight = Math.round(
Math.max(positions[25][1], positions[23][1], positions[112][1]) - leftOriginY
);
var rightOriginX = Math.round(
Math.min(positions[414][0], positions[463][0], positions[453][0])
);
var rightOriginY = Math.round(
Math.min(positions[414][1], positions[257][1], positions[467][1])
);
var rightWidth = Math.round(
Math.max(positions[467][0], positions[359][0], positions[255][0]) - rightOriginX
);
var rightHeight = Math.round(
Math.max(positions[341][1], positions[253][1], positions[255][1]) - rightOriginY
);
if (leftWidth === 0 || rightWidth === 0) {
console.log("an eye patch had zero width");
return null;
}
if (leftHeight === 0 || rightHeight === 0) {
console.log("an eye patch had zero height");
return null;
}
// Start building object to be returned
var eyeObjs = {};
var leftImageData = imageCanvas
.getContext("2d")
.getImageData(leftOriginX, leftOriginY, leftWidth, leftHeight);
eyeObjs.left = {
patch: leftImageData,
imagex: leftOriginX,
imagey: leftOriginY,
width: leftWidth,
height: leftHeight,
};
var rightImageData = imageCanvas
.getContext("2d")
.getImageData(rightOriginX, rightOriginY, rightWidth, rightHeight);
eyeObjs.right = {
patch: rightImageData,
imagex: rightOriginX,
imagey: rightOriginY,
width: rightWidth,
height: rightHeight,
};
this.predictionReady = true;
return eyeObjs;
};
/**
* Returns the positions array corresponding to the last call to getEyePatches.
* Requires that getEyePatches() was called previously, else returns null.
*/
TFFaceMesh.prototype.getPositions = function () {
return this.positionsArray;
};
/**
* Reset the tracker to default values
*/
TFFaceMesh.prototype.reset = function () {
console.log("Unimplemented; Tracking.js has no obvious reset function");
};
/**
* Draw TF_FaceMesh_Overlay
*/
TFFaceMesh.prototype.drawFaceOverlay = function (ctx, keypoints) {
// If keypoints is falsy, don't do anything
if (keypoints) {
ctx.fillStyle = "#32EEDB";
ctx.strokeStyle = "#32EEDB";
ctx.lineWidth = 0.5;
for (let i = 0; i < keypoints.length; i++) {
const x = keypoints[i][0];
const y = keypoints[i][1];
ctx.beginPath();
ctx.arc(x, y, 1 /* radius */, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
}
}
};
/**
* The TFFaceMesh object name
* @type {string}
*/
TFFaceMesh.prototype.name = "TFFaceMesh";
/* harmony default export */ var facemesh = TFFaceMesh;
// EXTERNAL MODULE: ./node_modules/numeric/numeric-1.2.6.js
var numeric_1_2_6 = __webpack_require__(12);
// CONCATENATED MODULE: ./src/mat.mjs
const mat = {};
/**
* Transposes an mxn array
* @param {Array.<Array.<Number>>} matrix - of 'M x N' dimensionality
* @return {Array.<Array.<Number>>} transposed matrix
*/
mat.transpose = function (matrix) {
var m = matrix.length;
var n = matrix[0].length;
var transposedMatrix = new Array(n);
for (var i = 0; i < m; i++) {
for (var j = 0; j < n; j++) {
if (i === 0) transposedMatrix[j] = new Array(m);
transposedMatrix[j][i] = matrix[i][j];
}
}
return transposedMatrix;
};
/**
* Get a sub-matrix of matrix
* @param {Array.<Array.<Number>>} matrix - original matrix
* @param {Array.<Number>} r - Array of row indices
* @param {Number} j0 - Initial column index
* @param {Number} j1 - Final column index
* @returns {Array} The sub-matrix matrix(r(:),j0:j1)
*/
mat.getMatrix = function (matrix, r, j0, j1) {
var X = new Array(r.length),
m = j1 - j0 + 1;
for (var i = 0; i < r.length; i++) {
X[i] = new Array(m);
for (var j = j0; j <= j1; j++) {
X[i][j - j0] = matrix[r[i]][j];
}
}
return X;
};
/**
* Get a submatrix of matrix
* @param {Array.<Array.<Number>>} matrix - original matrix
* @param {Number} i0 - Initial row index
* @param {Number} i1 - Final row index
* @param {Number} j0 - Initial column index
* @param {Number} j1 - Final column index
* @return {Array} The sub-matrix matrix(i0:i1,j0:j1)
*/
mat.getSubMatrix = function (matrix, i0, i1, j0, j1) {
var size = j1 - j0 + 1,
X = new Array(i1 - i0 + 1);
for (var i = i0; i <= i1; i++) {
var subI = i - i0;
X[subI] = new Array(size);
for (var j = j0; j <= j1; j++) {
X[subI][j - j0] = matrix[i][j];
}
}
return X;
};
/**
* Linear algebraic matrix multiplication, matrix1 * matrix2
* @param {Array.<Array.<Number>>} matrix1
* @param {Array.<Array.<Number>>} matrix2
* @return {Array.<Array.<Number>>} Matrix product, matrix1 * matrix2
*/
mat.mult = function (matrix1, matrix2) {
if (matrix2.length != matrix1[0].length) {
console.log("Matrix inner dimensions must agree:");
}
var X = new Array(matrix1.length),
Bcolj = new Array(matrix1[0].length);
for (var j = 0; j < matrix2[0].length; j++) {
for (var k = 0; k < matrix1[0].length; k++) {
Bcolj[k] = matrix2[k][j];
}
for (var i = 0; i < matrix1.length; i++) {
if (j === 0) X[i] = new Array(matrix2[0].length);
var Arowi = matrix1[i];
var s = 0;
for (var k = 0; k < matrix1[0].length; k++) {
s += Arowi[k] * Bcolj[k];
}
X[i][j] = s;
}
}
return X;
};
/**
* LUDecomposition to solve A*X = B, based on WEKA code
* @param {Array.<Array.<Number>>} A - left matrix of equation to be solved
* @param {Array.<Array.<Number>>} B - right matrix of equation to be solved
* @return {Array.<Array.<Number>>} X so that L*U*X = B(piv,:)
*/
mat.LUDecomposition = function (A, B) {
var LU = new Array(A.length);
for (var i = 0; i < A.length; i++) {
LU[i] = new Array(A[0].length);
for (var j = 0; j < A[0].length; j++) {
LU[i][j] = A[i][j];
}
}
var m = A.length;
var n = A[0].length;
var piv = new Array(m);
for (var i = 0; i < m; i++) {
piv[i] = i;
}
var pivsign = 1;
var LUrowi = new Array();
var LUcolj = new Array(m);
// Outer loop.
for (var j = 0; j < n; j++) {
// Make a copy of the j-th column to localize references.
for (var i = 0; i < m; i++) {
LUcolj[i] = LU[i][j];
}
// Apply previous transformations.
for (var i = 0; i < m; i++) {
LUrowi = LU[i];
// Most of the time is spent in the following dot product.
var kmax = Math.min(i, j);
var s = 0;
for (var k = 0; k < kmax; k++) {
s += LUrowi[k] * LUcolj[k];
}
LUrowi[j] = LUcolj[i] -= s;
}
// Find pivot and exchange if necessary.
var p = j;
for (var i = j + 1; i < m; i++) {
if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {
p = i;
}
}
if (p != j) {
for (var k = 0; k < n; k++) {
var t = LU[p][k];
LU[p][k] = LU[j][k];
LU[j][k] = t;
}
var k = piv[p];
piv[p] = piv[j];
piv[j] = k;
pivsign = -pivsign;
}
// Compute multipliers.
if ((j < m) & (LU[j][j] != 0)) {
for (var i = j + 1; i < m; i++) {
LU[i][j] /= LU[j][j];
}
}
}
if (B.length != m) {
console.log("Matrix row dimensions must agree.");
}
for (var j = 0; j < n; j++) {
if (LU[j][j] === 0) {
console.log("Matrix is singular.");
}
}
var nx = B[0].length;
var X = self.webgazer.mat.getMatrix(B, piv, 0, nx - 1);
// Solve L*Y = B(piv,:)
for (var k = 0; k < n; k++) {
for (var i = k + 1; i < n; i++) {
for (var j = 0; j < nx; j++) {
X[i][j] -= X[k][j] * LU[i][k];
}
}
}
// Solve U*X = Y;
for (var k = n - 1; k >= 0; k--) {
for (var j = 0; j < nx; j++) {
X[k][j] /= LU[k][k];
}
for (var i = 0; i < k; i++) {
for (var j = 0; j < nx; j++) {
X[i][j] -= X[k][j] * LU[i][k];
}
}
}
return X;
};
/**
* Least squares solution of A*X = B, based on WEKA code
* @param {Array.<Array.<Number>>} A - left side matrix to be solved
* @param {Array.<Array.<Number>>} B - a matrix with as many rows as A and any number of columns.
* @return {Array.<Array.<Number>>} X - that minimizes the two norms of QR*X-B.
*/
mat.QRDecomposition = function (A, B) {
// Initialize.
var QR = new Array(A.length);
for (var i = 0; i < A.length; i++) {
QR[i] = new Array(A[0].length);
for (var j = 0; j < A[0].length; j++) {
QR[i][j] = A[i][j];
}
}
var m = A.length;
var n = A[0].length;
var Rdiag = new Array(n);
var nrm;
// Main loop.
for (var k = 0; k < n; k++) {
// Compute 2-norm of k-th column without under/overflow.
nrm = 0;
for (var i = k; i < m; i++) {
nrm = Math.hypot(nrm, QR[i][k]);
}
if (nrm != 0) {
// Form k-th Householder vector.
if (QR[k][k] < 0) {
nrm = -nrm;
}
for (var i = k; i < m; i++) {
QR[i][k] /= nrm;
}
QR[k][k] += 1;
// Apply transformation to remaining columns.
for (var j = k + 1; j < n; j++) {
var s = 0;
for (var i = k; i < m; i++) {
s += QR[i][k] * QR[i][j];
}
s = -s / QR[k][k];
for (var i = k; i < m; i++) {
QR[i][j] += s * QR[i][k];
}
}
}
Rdiag[k] = -nrm;
}
if (B.length != m) {
console.log("Matrix row dimensions must agree.");
}
for (var j = 0; j < n; j++) {
if (Rdiag[j] === 0) console.log("Matrix is rank deficient");
}
// Copy right hand side
var nx = B[0].length;
var X = new Array(B.length);
for (var i = 0; i < B.length; i++) {
X[i] = new Array(B[0].length);
}
for (var i = 0; i < B.length; i++) {
for (var j = 0; j < B[0].length; j++) {
X[i][j] = B[i][j];
}
}
// Compute Y = transpose(Q)*B
for (var k = 0; k < n; k++) {
for (var j = 0; j < nx; j++) {
var s = 0.0;
for (var i = k; i < m; i++) {
s += QR[i][k] * X[i][j];
}
s = -s / QR[k][k];
for (var i = k; i < m; i++) {
X[i][j] += s * QR[i][k];
}
}
}
// Solve R*X = Y;
for (var k = n - 1; k >= 0; k--) {
for (var j = 0; j < nx; j++) {
X[k][j] /= Rdiag[k];
}
for (var i = 0; i < k; i++) {
for (var j = 0; j < nx; j++) {
X[i][j] -= X[k][j] * QR[i][k];
}
}
}
return mat.getSubMatrix(X, 0, n - 1, 0, nx - 1);
};
/* harmony default export */ var src_mat = mat;
// CONCATENATED MODULE: ./src/util.mjs
const util = {};
/**
* Eye class, represents an eye patch detected in the video stream
* @param {ImageData} patch - the image data corresponding to an eye
* @param {Number} imagex - x-axis offset from the top-left corner of the video canvas
* @param {Number} imagey - y-axis offset from the top-left corner of the video canvas
* @param {Number} width - width of the eye patch
* @param {Number} height - height of the eye patch
*/
var resizeWidth = 10;
var resizeHeight = 6;
util.Eye = function (patch, imagex, imagey, width, height) {
this.patch = patch;
this.imagex = imagex;
this.imagey = imagey;
this.width = width;
this.height = height;
};
util.getEyeFeats = function (eyes) {
var resizedLeft = this.resizeEye(eyes.left, resizeHeight, resizeHeight);
var resizedright = this.resizeEye(eyes.right, resizeHeight, resizeHeight);
var leftGray = this.grayscale(resizedLeft.data, resizedLeft.width, resizedLeft.height);
var rightGray = this.grayscale(resizedright.data, resizedright.width, resizedright.height);
var histLeft = [];
this.equalizeHistogram(leftGray, 5, histLeft);
var histRight = [];
this.equalizeHistogram(rightGray, 5, histRight);
var leftGrayArray = Array.prototype.slice.call(histLeft);
var rightGrayArray = Array.prototype.slice.call(histRight);
return leftGrayArray.concat(rightGrayArray);
};
//Data Window class
//operates like an array but 'wraps' data around to keep the array at a fixed windowSize
/**
* DataWindow class - Operates like an array, but 'wraps' data around to keep the array at a fixed windowSize
* @param {Number} windowSize - defines the maximum size of the window
* @param {Array} data - optional data to seed the DataWindow with
**/
util.DataWindow = function (windowSize, data) {
this.data = [];
this.windowSize = windowSize;
this.index = 0;
this.length = 0;
if (data) {
this.data = data.slice(data.length - windowSize, data.length);
this.length = this.data.length;
}
};
/**
* [push description]
* @param {*} entry - item to be inserted. It either grows the DataWindow or replaces the oldest item
* @return {DataWindow} this
*/
util.DataWindow.prototype.push = function (entry) {
if (this.data.length < this.windowSize) {
this.data.push(entry);
this.length = this.data.length;
return this;
}
//replace oldest entry by wrapping around the DataWindow
this.data[this.index] = entry;
this.index = (this.index + 1) % this.windowSize;
return this;
};
/**
* Get the element at the ind position by wrapping around the DataWindow
* @param {Number} ind index of desired entry
* @return {*}
*/
util.DataWindow.prototype.get = function (ind) {
return this.data[this.getTrueIndex(ind)];
};
/**
* Gets the true this.data array index given an index for a desired element
* @param {Number} ind - index of desired entry
* @return {Number} index of desired entry in this.data
*/
util.DataWindow.prototype.getTrueIndex = function (ind) {
if (this.data.length < this.windowSize) {
return ind;
} else {
//wrap around ind so that we can traverse from oldest to newest
return (ind + this.index) % this.windowSize;
}
};
/**
* Append all the contents of data
* @param {Array} data - to be inserted
*/
util.DataWindow.prototype.addAll = function (data) {
for (var i = 0; i < data.length; i++) {
this.push(data[i]);
}
};
//Helper functions
/**
* Grayscales an image patch. Can be used for the whole canvas, detected face, detected eye, etc.
*
* Code from tracking.js by Eduardo Lundgren, et al.
* https://github.com/eduardolundgren/tracking.js/blob/master/src/tracking.js
*
* Software License Agreement (BSD License) Copyright (c) 2014, Eduardo A. Lundgren Melo. All rights reserved.
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* The name of Eduardo A. Lundgren Melo may not be used to endorse or promote products derived from this software without specific prior written permission of Eduardo A. Lundgren Melo.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @param {Array} pixels - image data to be grayscaled
* @param {Number} width - width of image data to be grayscaled
* @param {Number} height - height of image data to be grayscaled
* @return {Array} grayscaledImage
*/
util.grayscale = function (pixels, width, height) {
var gray = new Uint8ClampedArray(pixels.length >> 2);
var p = 0;
var w = 0;
for (var i = 0; i < height; i++) {
for (var j = 0; j < width; j++) {
var value = pixels[w] * 0.299 + pixels[w + 1] * 0.587 + pixels[w + 2] * 0.114;
gray[p++] = value;
w += 4;
}
}
return gray;
};
/**
* Increase contrast of an image.
*
* Code from Martin Tschirsich, Copyright (c) 2012.
* https://github.com/mtschirs/js-objectdetect/blob/gh-pages/js/objectdetect.js
*
* @param {Array} src - grayscale integer array
* @param {Number} step - sampling rate, control performance
* @param {Array} dst - array to hold the resulting image
*/
util.equalizeHistogram = function (src, step, dst) {
var srcLength = src.length;
if (!dst) dst = src;
if (!step) step = 5;
// Compute histogram and histogram sum:
var hist = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
for (var i = 0; i < srcLength; i += step) {
++hist[src[i]];
}
// Compute integral histogram:
var norm = (255 * step) / srcLength,
prev = 0;
for (var i = 0; i < 256; ++i) {
var h = hist[i];
prev = h += prev;
hist[i] = h * norm; // For non-integer src: ~~(h * norm + 0.5);
}
// Equalize image:
for (var i = 0; i < srcLength; ++i) {
dst[i] = hist[src[i]];
}
return dst;
};
util.threshold = function (data, threshold) {
for (let i = 0; i < data.length; i++) {
data[i] = data[i] > threshold ? 255 : 0;
}
return data;
};
util.correlation = function (data1, data2) {
const length = Math.min(data1.length, data2.length);
let count = 0;
for (let i = 0; i < length; i++) {
if (data1[i] === data2[i]) {
count++;
}
}
return count / Math.max(data1.length, data2.length);
};
/**
* Gets an Eye object and resizes it to the desired resolution
* @param {webgazer.util.Eye} eye - patch to be resized
* @param {Number} resizeWidth - desired width
* @param {Number} resizeHeight - desired height
* @return {webgazer.util.Eye} resized eye patch
*/
util.resizeEye = function (eye, resizeWidth, resizeHeight) {
var canvas = document.createElement("canvas");
canvas.width = eye.width;
canvas.height = eye.height;
canvas.getContext("2d").putImageData(eye.patch, 0, 0);
var tempCanvas = document.createElement("canvas");
tempCanvas.width = resizeWidth;
tempCanvas.height = resizeHeight;
// save the canvas into temp canvas
tempCanvas
.getContext("2d")
.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, resizeWidth, resizeHeight);
return tempCanvas.getContext("2d").getImageData(0, 0, resizeWidth, resizeHeight);
};
/**
* Checks if the prediction is within the boundaries of the viewport and constrains it
* @param {Array} prediction [x,y] - predicted gaze coordinates
* @return {Array} constrained coordinates
*/
util.bound = function (prediction) {
if (prediction.x < 0) prediction.x = 0;
if (prediction.y < 0) prediction.y = 0;
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
if (prediction.x > w) {
prediction.x = w;
}
if (prediction.y > h) {
prediction.y = h;
}
return prediction;
};
/**
* Write statistics in debug paragraph panel
* @param {HTMLElement} para - The <p> tag where write data
* @param {Object} stats - The stats data to output
*/
function debugBoxWrite(para, stats) {
var str = "";
for (var key in stats) {
str += key + ": " + stats[key] + "\n";
}
para.innerText = str;
}
/**
* Constructor of DebugBox object,
* it insert an paragraph inside a div to the body, in view to display debug data
* @param {Number} interval - The log interval
* @constructor
*/
util.DebugBox = function (interval) {
this.para = document.createElement("p");
this.div = document.createElement("div");
this.div.appendChild(this.para);
document.body.appendChild(this.div);
this.buttons = {};
this.canvas = {};
this.stats = {};
var updateInterval = interval || 300;
(function (localThis) {
setInterval(function () {
debugBoxWrite(localThis.para, localThis.stats);
}, updateInterval);
})(this);
};
/**
* Add stat data for log
* @param {String} key - The data key
* @param {*} value - The value
*/
util.DebugBox.prototype.set = function (key, value) {
this.stats[key] = value;
};
/**
* Initialize stats in case where key does not exist, else
* increment value for key
* @param {String} key - The key to process
* @param {Number} incBy - Value to increment for given key (default: 1)
* @param {Number} init - Initial value in case where key does not exist (default: 0)
*/
util.DebugBox.prototype.inc = function (key, incBy, init) {
if (!this.stats[key]) {
this.stats[key] = init || 0;
}
this.stats[key] += incBy || 1;
};
/**
* Create a button and register the given function to the button click event
* @param {String} name - The button name to link
* @param {Function} func - The onClick callback
*/
util.DebugBox.prototype.addButton = function (name, func) {
if (!this.buttons[name]) {
this.buttons[name] = document.createElement("button");
this.div.appendChild(this.buttons[name]);
}
var button = this.buttons[name];
this.buttons[name] = button;
button.addEventListener("click", func);
button.innerText = name;
};
/**
* Search for a canvas elemenet with name, or create on if not exist.
* Then send the canvas element as callback parameter.
* @param {String} name - The canvas name to send/create
* @param {Function} func - The callback function where send canvas
*/
util.DebugBox.prototype.show = function (name, func) {
if (!this.canvas[name]) {
this.canvas[name] = document.createElement("canvas");
this.div.appendChild(this.canvas[name]);
}
var canvas = this.canvas[name];
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
func(canvas);
};
/**
* Kalman Filter constructor
* Kalman filters work by reducing the amount of noise in a models.
* https://blog.cordiner.net/2011/05/03/object-tracking-using-a-kalman-filter-matlab/
*
* @param {Array.<Array.<Number>>} F - transition matrix
* @param {Array.<Array.<Number>>} Q - process noise matrix
* @param {Array.<Array.<Number>>} H - maps between measurement vector and noise matrix
* @param {Array.<Array.<Number>>} R - defines measurement error of the device
* @param {Array} P_initial - the initial state
* @param {Array} X_initial - the initial state of the device
*/
util.KalmanFilter = function (F, H, Q, R, P_initial, X_initial) {
this.F = F; // State transition matrix
this.Q = Q; // Process noise matrix
this.H = H; // Transformation matrix
this.R = R; // Measurement Noise
this.P = P_initial; //Initial covariance matrix
this.X = X_initial; //Initial guess of measurement
};
/**
* Get Kalman next filtered value and update the internal state
* @param {Array} z - the new measurement
* @return {Array}
*/
util.KalmanFilter.prototype.update = function (z) {
// Here, we define all the different matrix operations we will need
var add = numeric.add,
sub = numeric.sub,
inv = numeric.inv,
identity = numeric.identity;
var mult = src_mat.mult,
transpose = src_mat.transpose;
//TODO cache variables like the transpose of H
// prediction: X = F * X | P = F * P * F' + Q
var X_p = mult(this.F, this.X); //Update state vector
var P_p = add(mult(mult(this.F, this.P), transpose(this.F)), this.Q); //Predicted covaraince
//Calculate the update values
var y = sub(z, mult(this.H, X_p)); // This is the measurement error (between what we expect and the actual value)
var S = add(mult(mult(this.H, P_p), transpose(this.H)), this.R); //This is the residual covariance (the error in the covariance)
// kalman multiplier: K = P * H' * (H * P * H' + R)^-1
var K = mult(P_p, mult(transpose(this.H), inv(S))); //This is the Optimal Kalman Gain
//We need to change Y into it's column vector form
for (var i = 0; i < y.length; i++) {
y[i] = [y[i]];
}
//Now we correct the internal values of the model
// correction: X = X + K * (m - H * X) | P = (I - K * H) * P
this.X = add(X_p, mult(K, y));
this.P = mult(sub(identity(K.length), mult(K, this.H)), P_p);
return transpose(mult(this.H, this.X))[0]; //Transforms the predicted state back into it's measurement form
};
/* harmony default export */ var src_util = util;
// CONCATENATED MODULE: ./src/ridgeReg.mjs
const ridgeReg_reg = {};
var ridgeParameter = Math.pow(10, -5);
var dataWindow = 700;
var trailDataWindow = 10;
/**
* Performs ridge regression, according to the Weka code.
* @param {Array} y - corresponds to screen coordinates (either x or y) for each of n click events
* @param {Array.<Array.<Number>>} X - corresponds to gray pixel features (120 pixels for both eyes) for each of n clicks
* @param {Array} k - ridge parameter
* @return{Array} regression coefficients
*/
function ridge(y, X, k) {
var nc = X[0].length;
var m_Coefficients = new Array(nc);
var xt = src_mat.transpose(X);
var solution = new Array();
var success = true;
do {
var ss = src_mat.mult(xt, X);
// Set ridge regression adjustment
for (var i = 0; i < nc; i++) {
ss[i][i] = ss[i][i] + k;
}
// Carry out the regression
var bb = src_mat.mult(xt, y);
for (var i = 0; i < nc; i++) {
m_Coefficients[i] = bb[i][0];
}
try {
var n = m_Coefficients.length !== 0 ? m_Coefficients.length / m_Coefficients.length : 0;
if (m_Coefficients.length * n !== m_Coefficients.length) {
console.log("Array length must be a multiple of m");
}
solution =
ss.length === ss[0].length
? numeric_1_2_6.LUsolve(numeric_1_2_6.LU(ss, true), bb)
: src_mat.QRDecomposition(ss, bb);
for (var i = 0; i < nc; i++) {
m_Coefficients[i] = solution[i];
}
success = true;
} catch (ex) {
k *= 10;
console.log(ex);
success = false;
}
} while (!success);
return m_Coefficients;
}
//TODO: still usefull ???
/**
*
* @returns {Number}
*/
function getCurrentFixationIndex() {
var index = 0;
var recentX = this.screenXTrailArray.get(0);
var recentY = this.screenYTrailArray.get(0);
for (var i = this.screenXTrailArray.length - 1; i >= 0; i--) {
var currX = this.screenXTrailArray.get(i);
var currY = this.screenYTrailArray.get(i);
var euclideanDistance = Math.sqrt(
Math.pow(currX - recentX, 2) + Math.pow(currY - recentY, 2)
);
if (euclideanDistance > 72) {
return i + 1;
}
}
return i;
}
/**
* Constructor of RidgeReg object,
* this object allow to perform ridge regression
* @constructor
*/
ridgeReg_reg.RidgeReg = function () {
this.init();
};
/**
* Initialize new arrays and initialize Kalman filter.
*/
ridgeReg_reg.RidgeReg.prototype.init = function () {
this.screenXClicksArray = new src_util.DataWindow(dataWindow);
this.screenYClicksArray = new src_util.DataWindow(dataWindow);
this.eyeFeaturesClicks = new src_util.DataWindow(dataWindow);
//sets to one second worth of cursor trail
this.trailTime = 1000;
this.trailDataWindow = this.trailTime / src_params.moveTickSize;
this.screenXTrailArray = new src_util.DataWindow(trailDataWindow);
this.screenYTrailArray = new src_util.DataWindow(trailDataWindow);
this.eyeFeaturesTrail = new src_util.DataWindow(trailDataWindow);
this.trailTimes = new src_util.DataWindow(trailDataWindow);
this.dataClicks = new src_util.DataWindow(dataWindow);
this.dataTrail = new src_util.DataWindow(trailDataWindow);
// Initialize Kalman filter [20200608 xk] what do we do about parameters?
// [20200611 xk] unsure what to do w.r.t. dimensionality of these matrices. So far at least
// by my own anecdotal observation a 4x1 x vector seems to work alright
var F = [
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 1],
];
//Parameters Q and R may require some fine tuning
var Q = [
[1 / 4, 0, 1 / 2, 0],
[0, 1 / 4, 0, 1 / 2],
[1 / 2, 0, 1, 0],
[0, 1 / 2, 0, 1],
]; // * delta_t
var delta_t = 1 / 10; // The amount of time between frames
Q = numeric_1_2_6.mul(Q, delta_t);
var H = [
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
];
var H = [
[1, 0, 0, 0],
[0, 1, 0, 0],
];
var pixel_error = 47; //We will need to fine tune this value [20200611 xk] I just put a random value here
//This matrix represents the expected measurement error
var R = numeric_1_2_6.mul(numeric_1_2_6.identity(2), pixel_error);
var P_initial = numeric_1_2_6.mul(numeric_1_2_6.identity(4), 0.0001); //Initial covariance matrix
var x_initial = [[500], [500], [0], [0]]; // Initial measurement matrix
this.kalman = new src_util.KalmanFilter(F, H, Q, R, P_initial, x_initial);
};
/**
* Add given data from eyes
* @param {Object} eyes - eyes where extract data to add
* @param {Object} screenPos - The current screen point
* @param {Object} type - The type of performed action
*/
ridgeReg_reg.RidgeReg.prototype.addData = function (eyes, screenPos, type) {
if (!eyes) {
return;
}
//not doing anything with blink at present
// if (eyes.left.blink || eyes.right.blink) {
// return;
// }
//why are we pushing these as arrays rather than single elements?
if (type === "click") {
this.screenXClicksArray.push([screenPos[0]]);
this.screenYClicksArray.push([screenPos[1]]);
this.eyeFeaturesClicks.push(src_util.getEyeFeats(eyes));
this.dataClicks.push({ eyes: eyes, screenPos: screenPos, type: type });
} else if (type === "move") {
this.screenXTrailArray.push([screenPos[0]]);
this.screenYTrailArray.push([screenPos[1]]);
this.eyeFeaturesTrail.push(src_util.getEyeFeats(eyes));
this.trailTimes.push(performance.now());
this.dataTrail.push({ eyes: eyes, screenPos: screenPos, type: type });
}
// [20180730 JT] Why do we do this? It doesn't return anything...
// But as JS is pass by reference, it still affects it.
//
// Causes problems for when we want to call 'addData' twice in a row on the same object, but perhaps with different screenPos or types (think multiple interactions within one video frame)
//eyes.left.patch = Array.from(eyes.left.patch.data);
//eyes.right.patch = Array.from(eyes.right.patch.data);
};
/**
* Try to predict coordinates from pupil data
* after apply linear regression on data set
* @param {Object} eyesObj - The current user eyes object
* @returns {Object}
*/
ridgeReg_reg.RidgeReg.prototype.predict = function (eyesObj) {
if (!eyesObj || this.eyeFeaturesClicks.length === 0) {
return null;
}
var acceptTime = performance.now() - this.trailTime;
var trailX = [];
var trailY = [];
var trailFeat = [];
for (var i = 0; i < this.trailDataWindow; i++) {
if (this.trailTimes.get(i) > acceptTime) {
trailX.push(this.screenXTrailArray.get(i));
trailY.push(this.screenYTrailArray.get(i));
trailFeat.push(this.eyeFeaturesTrail.get(i));
}
}
var screenXArray = this.screenXClicksArray.data.concat(trailX);
var screenYArray = this.screenYClicksArray.data.concat(trailY);
var eyeFeatures = this.eyeFeaturesClicks.data.concat(trailFeat);
var coefficientsX = ridge(screenXArray, eyeFeatures, ridgeParameter);
var coefficientsY = ridge(screenYArray, eyeFeatures, ridgeParameter);
var eyeFeats = src_util.getEyeFeats(eyesObj);
var predictedX = 0;
for (var i = 0; i < eyeFeats.length; i++) {
predictedX += eyeFeats[i] * coefficientsX[i];
}
var predictedY = 0;
for (var i = 0; i < eyeFeats.length; i++) {
predictedY += eyeFeats[i] * coefficientsY[i];
}
predictedX = Math.floor(predictedX);
predictedY = Math.floor(predictedY);
if (src_params.applyKalmanFilter) {
// Update Kalman model, and get prediction
var newGaze = [predictedX, predictedY]; // [20200607 xk] Should we use a 1x4 vector?
newGaze = this.kalman.update(newGaze);
return {
x: newGaze[0],
y: newGaze[1],
};
} else {
return {
x: predictedX,
y: predictedY,
};
}
};
/**
* Add given data to current data set then,
* replace current data member with given data
* @param {Array.<Object>} data - The data to set
*/
ridgeReg_reg.RidgeReg.prototype.setData = function (data) {
for (var i = 0; i < data.length; i++) {
// Clone data array
var leftData = new Uint8ClampedArray(data[i].eyes.left.patch.data);
var rightData = new Uint8ClampedArray(data[i].eyes.right.patch.data);
// Duplicate ImageData object
data[i].eyes.left.patch = new ImageData(
leftData,
data[i].eyes.left.width,
data[i].eyes.left.height
);
data[i].eyes.right.patch = new ImageData(
rightData,
data[i].eyes.right.width,
data[i].eyes.right.height
);
// Add those data objects to model
this.addData(data[i].eyes, data[i].screenPos, data[i].type);
}
};
/**
* Return the data
* @returns {Array.<Object>|*}
*/
ridgeReg_reg.RidgeReg.prototype.getData = function () {
return this.dataClicks.data;
};
/**
* The RidgeReg object name
* @type {string}
*/
ridgeReg_reg.RidgeReg.prototype.name = "ridge";
/* harmony default export */ var ridgeReg = ridgeReg_reg;
// CONCATENATED MODULE: ./src/ridgeWeightedReg.mjs
const ridgeWeightedReg_reg = {};
var ridgeWeightedReg_ridgeParameter = Math.pow(10, -5);
var ridgeWeightedReg_dataWindow = 700;
var ridgeWeightedReg_trailDataWindow = 10;
/**
* Performs ridge regression, according to the Weka code.
* @param {Array} y - corresponds to screen coordinates (either x or y) for each of n click events
* @param {Array.<Array.<Number>>} X - corresponds to gray pixel features (120 pixels for both eyes) for each of n clicks
* @param {Array} k - ridge parameter
* @return{Array} regression coefficients
*/
function ridgeWeightedReg_ridge(y, X, k) {
var nc = X[0].length;
var m_Coefficients = new Array(nc);
var xt = src_mat.transpose(X);
var solution = new Array();
var success = true;
do {
var ss = src_mat.mult(xt, X);
// Set ridge regression adjustment
for (var i = 0; i < nc; i++) {
ss[i][i] = ss[i][i] + k;
}
// Carry out the regression
var bb = src_mat.mult(xt, y);
for (var i = 0; i < nc; i++) {
m_Coefficients[i] = bb[i][0];
}
try {
var n = m_Coefficients.length !== 0 ? m_Coefficients.length / m_Coefficients.length : 0;
if (m_Coefficients.length * n !== m_Coefficients.length) {
console.log("Array length must be a multiple of m");
}
solution =
ss.length === ss[0].length
? numeric_1_2_6.LUsolve(numeric_1_2_6.LU(ss, true), bb)
: webgazer.mat.QRDecomposition(ss, bb);
for (var i = 0; i < nc; i++) {
m_Coefficients[i] = solution[i];
}
success = true;
} catch (ex) {
k *= 10;
console.log(ex);
success = false;
}
} while (!success);
return m_Coefficients;
}
/**
* Compute eyes size as gray histogram
* @param {Object} eyes - The eyes where looking for gray histogram
* @returns {Array.<T>} The eyes gray level histogram
*/
//TODO: still usefull ???
/**
*
* @returns {Number}
*/
function ridgeWeightedReg_getCurrentFixationIndex() {
var index = 0;
var recentX = this.screenXTrailArray.get(0);
var recentY = this.screenYTrailArray.get(0);
for (var i = this.screenXTrailArray.length - 1; i >= 0; i--) {
var currX = this.screenXTrailArray.get(i);
var currY = this.screenYTrailArray.get(i);
var euclideanDistance = Math.sqrt(
Math.pow(currX - recentX, 2) + Math.pow(currY - recentY, 2)
);
if (euclideanDistance > 72) {
return i + 1;
}
}
return i;
}
/**
* Constructor of RidgeWeightedReg object
* @constructor
*/
ridgeWeightedReg_reg.RidgeWeightedReg = function () {
this.init();
};
/**
* Initialize new arrays and initialize Kalman filter.
*/
ridgeWeightedReg_reg.RidgeWeightedReg.prototype.init = function () {
this.screenXClicksArray = new src_util.DataWindow(ridgeWeightedReg_dataWindow);
this.screenYClicksArray = new src_util.DataWindow(ridgeWeightedReg_dataWindow);
this.eyeFeaturesClicks = new src_util.DataWindow(ridgeWeightedReg_dataWindow);
//sets to one second worth of cursor trail
this.trailTime = 1000;
this.trailDataWindow = this.trailTime / src_params.moveTickSize;
this.screenXTrailArray = new src_util.DataWindow(ridgeWeightedReg_trailDataWindow);
this.screenYTrailArray = new src_util.DataWindow(ridgeWeightedReg_trailDataWindow);
this.eyeFeaturesTrail = new src_util.DataWindow(ridgeWeightedReg_trailDataWindow);
this.trailTimes = new src_util.DataWindow(ridgeWeightedReg_trailDataWindow);
this.dataClicks = new src_util.DataWindow(ridgeWeightedReg_dataWindow);
this.dataTrail = new src_util.DataWindow(ridgeWeightedReg_trailDataWindow);
// Initialize Kalman filter [20200608 xk] what do we do about parameters?
// [20200611 xk] unsure what to do w.r.t. dimensionality of these matrices. So far at least
// by my own anecdotal observation a 4x1 x vector seems to work alright
var F = [
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 1],
];
//Parameters Q and R may require some fine tuning
var Q = [
[1 / 4, 0, 1 / 2, 0],
[0, 1 / 4, 0, 1 / 2],
[1 / 2, 0, 1, 0],
[0, 1 / 2, 0, 1],
]; // * delta_t
var delta_t = 1 / 10; // The amount of time between frames
Q = numeric_1_2_6.mul(Q, delta_t);
var H = [
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
];
var H = [
[1, 0, 0, 0],
[0, 1, 0, 0],
];
var pixel_error = 47; //We will need to fine tune this value [20200611 xk] I just put a random value here
//This matrix represents the expected measurement error
var R = numeric_1_2_6.mul(numeric_1_2_6.identity(2), pixel_error);
var P_initial = numeric_1_2_6.mul(numeric_1_2_6.identity(4), 0.0001); //Initial covariance matrix
var x_initial = [[500], [500], [0], [0]]; // Initial measurement matrix
this.kalman = new src_util.KalmanFilter(F, H, Q, R, P_initial, x_initial);
};
/**
* Add given data from eyes
* @param {Object} eyes - eyes where extract data to add
* @param {Object} screenPos - The current screen point
* @param {Object} type - The type of performed action
*/
ridgeWeightedReg_reg.RidgeWeightedReg.prototype.addData = function (eyes, screenPos, type) {
if (!eyes) {
return;
}
//not doing anything with blink at present
// if (eyes.left.blink || eyes.right.blink) {
// return;
// }
if (type === "click") {
this.screenXClicksArray.push([screenPos[0]]);
this.screenYClicksArray.push([screenPos[1]]);
this.eyeFeaturesClicks.push(src_util.getEyeFeats(eyes));
this.dataClicks.push({ eyes: eyes, screenPos: screenPos, type: type });
} else if (type === "move") {
this.screenXTrailArray.push([screenPos[0]]);
this.screenYTrailArray.push([screenPos[1]]);
this.eyeFeaturesTrail.push(src_util.getEyeFeats(eyes));
this.trailTimes.push(performance.now());
this.dataTrail.push({ eyes: eyes, screenPos: screenPos, type: type });
}
// [20180730 JT] Why do we do this? It doesn't return anything...
// But as JS is pass by reference, it still affects it.
//
// Causes problems for when we want to call 'addData' twice in a row on the same object, but perhaps with different screenPos or types (think multiple interactions within one video frame)
//eyes.left.patch = Array.from(eyes.left.patch.data);
//eyes.right.patch = Array.from(eyes.right.patch.data);
};
/**
* Try to predict coordinates from pupil data
* after apply linear regression on data set
* @param {Object} eyesObj - The current user eyes object
* @returns {Object}
*/
ridgeWeightedReg_reg.RidgeWeightedReg.prototype.predict = function (eyesObj) {
if (!eyesObj || this.eyeFeaturesClicks.length === 0) {
return null;
}
var acceptTime = performance.now() - this.trailTime;
var trailX = [];
var trailY = [];
var trailFeat = [];
for (var i = 0; i < this.trailDataWindow; i++) {
if (this.trailTimes.get(i) > acceptTime) {
trailX.push(this.screenXTrailArray.get(i));
trailY.push(this.screenYTrailArray.get(i));
trailFeat.push(this.eyeFeaturesTrail.get(i));
}
}
var len = this.eyeFeaturesClicks.data.length;
var weightedEyeFeats = Array(len);
var weightedXArray = Array(len);
var weightedYArray = Array(len);
for (var i = 0; i < len; i++) {
var weight = Math.sqrt(1 / (len - i)); // access from oldest to newest so should start with low weight and increase steadily
//abstraction is leaking...
var trueIndex = this.eyeFeaturesClicks.getTrueIndex(i);
for (var j = 0; j < this.eyeFeaturesClicks.data[trueIndex].length; j++) {
var val = this.eyeFeaturesClicks.data[trueIndex][j] * weight;
if (weightedEyeFeats[trueIndex] !== undefined) {
weightedEyeFeats[trueIndex].push(val);
} else {
weightedEyeFeats[trueIndex] = [val];
}
}
weightedXArray[trueIndex] = this.screenXClicksArray
.get(i)
.slice(0, this.screenXClicksArray.get(i).length);
weightedYArray[trueIndex] = this.screenYClicksArray
.get(i)
.slice(0, this.screenYClicksArray.get(i).length);
weightedXArray[i][0] = weightedXArray[i][0] * weight;
weightedYArray[i][0] = weightedYArray[i][0] * weight;
}
var screenXArray = weightedXArray.concat(trailX);
var screenYArray = weightedYArray.concat(trailY);
var eyeFeatures = weightedEyeFeats.concat(trailFeat);
var coefficientsX = ridgeWeightedReg_ridge(
screenXArray,
eyeFeatures,
ridgeWeightedReg_ridgeParameter
);
var coefficientsY = ridgeWeightedReg_ridge(
screenYArray,
eyeFeatures,
ridgeWeightedReg_ridgeParameter
);
var eyeFeats = src_util.getEyeFeats(eyesObj);
var predictedX = 0;
for (var i = 0; i < eyeFeats.length; i++) {
predictedX += eyeFeats[i] * coefficientsX[i];
}
var predictedY = 0;
for (var i = 0; i < eyeFeats.length; i++) {
predictedY += eyeFeats[i] * coefficientsY[i];
}
predictedX = Math.floor(predictedX);
predictedY = Math.floor(predictedY);
if (src_params.applyKalmanFilter) {
// Update Kalman model, and get prediction
var newGaze = [predictedX, predictedY]; // [20200607 xk] Should we use a 1x4 vector?
newGaze = this.kalman.update(newGaze);
return {
x: newGaze[0],
y: newGaze[1],
};
} else {
return {
x: predictedX,
y: predictedY,
};
}
};
/**
* Add given data to current data set then,
* replace current data member with given data
* @param {Array.<Object>} data - The data to set
*/
ridgeWeightedReg_reg.RidgeWeightedReg.prototype.setData = function (data) {
for (var i = 0; i < data.length; i++) {
// [20200611 xk] Previous comment said this was a kludge, but it seems like this is the best solution
// Clone data array
var leftData = new Uint8ClampedArray(data[i].eyes.left.patch.data);
var rightData = new Uint8ClampedArray(data[i].eyes.right.patch.data);
// Duplicate ImageData object
data[i].eyes.left.patch = new ImageData(
leftData,
data[i].eyes.left.width,
data[i].eyes.left.height
);
data[i].eyes.right.patch = new ImageData(
rightData,
data[i].eyes.right.width,
data[i].eyes.right.height
);
this.addData(data[i].eyes, data[i].screenPos, data[i].type);
}
};
/**
* Return the data
* @returns {Array.<Object>|*}
*/
ridgeWeightedReg_reg.RidgeWeightedReg.prototype.getData = function () {
return this.dataClicks.data;
};
/**
* The RidgeWeightedReg object name
* @type {string}
*/
ridgeWeightedReg_reg.RidgeWeightedReg.prototype.name = "ridge";
/* harmony default export */ var ridgeWeightedReg = ridgeWeightedReg_reg;
// CONCATENATED MODULE: ./src/ridgeRegThreaded.mjs
const ridgeRegThreaded_reg = {};
var ridgeRegThreaded_ridgeParameter = Math.pow(10, -5);
var ridgeRegThreaded_dataWindow = 700;
var weights = { X: [0], Y: [0] };
var ridgeRegThreaded_trailDataWindow = 10;
/**
* Constructor of RidgeRegThreaded object,
* it retrieve data window, and prepare a worker,
* this object allow to perform threaded ridge regression
* @constructor
*/
ridgeRegThreaded_reg.RidgeRegThreaded = function (workerScriptURL) {
this.init(workerScriptURL);
};
/**
* Initialize new arrays and initialize Kalman filter.
*/
ridgeRegThreaded_reg.RidgeRegThreaded.prototype.init = function (workerScriptURL) {
this.screenXClicksArray = new src_util.DataWindow(ridgeRegThreaded_dataWindow);
this.screenYClicksArray = new src_util.DataWindow(ridgeRegThreaded_dataWindow);
this.eyeFeaturesClicks = new src_util.DataWindow(ridgeRegThreaded_dataWindow);
this.screenXTrailArray = new src_util.DataWindow(ridgeRegThreaded_trailDataWindow);
this.screenYTrailArray = new src_util.DataWindow(ridgeRegThreaded_trailDataWindow);
this.eyeFeaturesTrail = new src_util.DataWindow(ridgeRegThreaded_trailDataWindow);
this.dataClicks = new src_util.DataWindow(ridgeRegThreaded_dataWindow);
this.dataTrail = new src_util.DataWindow(ridgeRegThreaded_dataWindow);
// Place the src/ridgeworker.js file into the same directory as your html file.
if (!this.worker) {
//this.worker = new Worker('ridgeWorker.mjs'); // [20200708] TODO: Figure out how to make this inline
this.worker = new Worker(workerScriptURL);
this.worker.onerror = function (err) {
console.log(err.message);
};
this.worker.onmessage = function (evt) {
weights.X = evt.data.X;
weights.Y = evt.data.Y;
};
console.log("initialized worker");
}
// Initialize Kalman filter [20200608 xk] what do we do about parameters?
// [20200611 xk] unsure what to do w.r.t. dimensionality of these matrices. So far at least
// by my own anecdotal observation a 4x1 x vector seems to work alright
var F = [
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 1],
];
//Parameters Q and R may require some fine tuning
var Q = [
[1 / 4, 0, 1 / 2, 0],
[0, 1 / 4, 0, 1 / 2],
[1 / 2, 0, 1, 0],
[0, 1 / 2, 0, 1],
]; // * delta_t
var delta_t = 1 / 10; // The amount of time between frames
Q = numeric_1_2_6.mul(Q, delta_t);
var H = [
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
];
var H = [
[1, 0, 0, 0],
[0, 1, 0, 0],
];
var pixel_error = 47; //We will need to fine tune this value [20200611 xk] I just put a random value here
//This matrix represents the expected measurement error
var R = numeric_1_2_6.mul(numeric_1_2_6.identity(2), pixel_error);
var P_initial = numeric_1_2_6.mul(numeric_1_2_6.identity(4), 0.0001); //Initial covariance matrix
var x_initial = [[500], [500], [0], [0]]; // Initial measurement matrix
this.kalman = new src_util.KalmanFilter(F, H, Q, R, P_initial, x_initial);
};
/**
* Add given data from eyes
* @param {Object} eyes - eyes where extract data to add
* @param {Object} screenPos - The current screen point
* @param {Object} type - The type of performed action
*/
ridgeRegThreaded_reg.RidgeRegThreaded.prototype.addData = function (eyes, screenPos, type) {
if (!eyes) {
return;
}
//not doing anything with blink at present
// if (eyes.left.blink || eyes.right.blink) {
// return;
// }
this.worker.postMessage({
eyes: src_util.getEyeFeats(eyes),
screenPos: screenPos,
type: type,
});
};
/**
* Try to predict coordinates from pupil data
* after apply linear regression on data set
* @param {Object} eyesObj - The current user eyes object
* @returns {Object}
*/
ridgeRegThreaded_reg.RidgeRegThreaded.prototype.predict = function (eyesObj) {
// console.log('LOGGING..');
if (!eyesObj) {
return null;
}
var coefficientsX = weights.X;
var coefficientsY = weights.Y;
var eyeFeats = src_util.getEyeFeats(eyesObj);
var predictedX = 0,
predictedY = 0;
for (var i = 0; i < eyeFeats.length; i++) {
predictedX += eyeFeats[i] * coefficientsX[i];
predictedY += eyeFeats[i] * coefficientsY[i];
}
predictedX = Math.floor(predictedX);
predictedY = Math.floor(predictedY);
if (src_params.applyKalmanFilter) {
// Update Kalman model, and get prediction
var newGaze = [predictedX, predictedY]; // [20200607 xk] Should we use a 1x4 vector?
newGaze = this.kalman.update(newGaze);
return {
x: newGaze[0],
y: newGaze[1],
};
} else {
return {
x: predictedX,
y: predictedY,
};
}
};
/**
* Add given data to current data set then,
* replace current data member with given data
* @param {Array.<Object>} data - The data to set
*/
ridgeRegThreaded_reg.RidgeRegThreaded.prototype.setData = function (data) {
for (var i = 0; i < data.length; i++) {
// [20200611 xk] Previous comment said this was a kludge, but it seems like this is the best solution
// Clone data array
var leftData = new Uint8ClampedArray(data[i].eyes.left.patch.data);
var rightData = new Uint8ClampedArray(data[i].eyes.right.patch.data);
// Duplicate ImageData object
data[i].eyes.left.patch = new ImageData(
leftData,
data[i].eyes.left.width,
data[i].eyes.left.height
);
data[i].eyes.right.patch = new ImageData(
rightData,
data[i].eyes.right.width,
data[i].eyes.right.height
);
this.addData(data[i].eyes, data[i].screenPos, data[i].type);
}
};
/**
* Return the data
* @returns {Array.<Object>|*}
*/
ridgeRegThreaded_reg.RidgeRegThreaded.prototype.getData = function () {
return this.dataClicks.data;
};
/**
* The RidgeRegThreaded object name
* @type {string}
*/
ridgeRegThreaded_reg.RidgeRegThreaded.prototype.name = "ridge";
/* harmony default export */ var ridgeRegThreaded = ridgeRegThreaded_reg;
// CONCATENATED MODULE: ./src/index.mjs
const src_webgazer = {};
src_webgazer.tracker = {};
src_webgazer.tracker.TFFaceMesh = facemesh;
src_webgazer.reg = ridgeReg;
src_webgazer.reg.RidgeWeightedReg = ridgeWeightedReg.RidgeWeightedReg;
src_webgazer.reg.RidgeRegThreaded = ridgeRegThreaded.RidgeRegThreaded;
src_webgazer.util = src_util;
src_webgazer.params = src_params;
src_webgazer.workerScriptURL = "ridgeWorker.mjs";
//PRIVATE VARIABLES
//video elements
var videoStream = null;
var videoContainerElement = null;
var videoElement = null;
var videoElementCanvas = null;
var faceOverlay = null;
var faceFeedbackBox = null;
var gazeDot = null;
// Why is this not in webgazer.params ?
var debugVideoLoc = "";
/*
* Initialises variables used to store accuracy eigenValues
* This is used by the calibration example file
*/
var xPast50 = new Array(50);
var yPast50 = new Array(50);
// loop parameters
var clockStart = performance.now();
var latestEyeFeatures = null;
var latestGazeData = null;
var paused = false;
//registered callback for loop
var nopCallback = function (data, time) {};
var callback = nopCallback;
//Types that regression systems should handle
//Describes the source of data so that regression systems may ignore or handle differently the various generating events
var eventTypes = ["click", "move"];
//movelistener timeout clock parameters
var moveClock = performance.now();
//currently used tracker and regression models, defaults to clmtrackr and linear regression
var curTracker = new src_webgazer.tracker.TFFaceMesh();
var regs = [new src_webgazer.reg.RidgeReg()];
// var blinkDetector = new webgazer.BlinkDetector();
//lookup tables
var curTrackerMap = {
TFFacemesh: function () {
return new src_webgazer.tracker.TFFaceMesh();
},
};
var regressionMap = {
ridge: function () {
return new src_webgazer.reg.RidgeReg();
},
weightedRidge: function () {
return new src_webgazer.reg.RidgeWeightedReg();
},
threadedRidge: function () {
return new src_webgazer.reg.RidgeRegThreaded(src_webgazer.workerScriptURL);
},
};
//localstorage name
var localstorageDataLabel = "webgazerGlobalData";
var localstorageSettingsLabel = "webgazerGlobalSettings";
//settings object for future storage of settings
var settings = {};
var data = [];
var defaults = {
data: [],
settings: {},
};
//PRIVATE FUNCTIONS
/**
* Computes the size of the face overlay validation box depending on the size of the video preview window.
* @returns {Object} The dimensions of the validation box as top, left, width, height.
*/
src_webgazer.computeValidationBoxSize = function () {
var vw = videoElement.videoWidth;
var vh = videoElement.videoHeight;
var pw = parseInt(videoElement.style.width);
var ph = parseInt(videoElement.style.height);
// Find the size of the box.
// Pick the smaller of the two video preview sizes
var smaller = Math.min(vw, vh);
var larger = Math.max(vw, vh);
// Overall scalar
var scalar = vw == larger ? pw / vw : ph / vh;
// Multiply this by 2/3, then adjust it to the size of the preview
var boxSize = smaller * src_webgazer.params.faceFeedbackBoxRatio * scalar;
// Set the boundaries of the face overlay validation box based on the preview
var topVal = (ph - boxSize) / 2;
var leftVal = (pw - boxSize) / 2;
// top, left, width, height
return [topVal, leftVal, boxSize, boxSize];
};
/**
* Checks if the pupils are in the position box on the video
* // TODO These are all wrong. The latestEyeFeatures will be in 'video' space not 'preview' space, and so need to be converted.
*/
function checkEyesInValidationBox() {
if (faceFeedbackBox != null && latestEyeFeatures) {
var w = videoElement.videoWidth;
var h = videoElement.videoHeight;
// Find the size of the box.
// Pick the smaller of the two video preview sizes
var smaller = Math.min(w, h);
var boxSize = smaller * src_webgazer.params.faceFeedbackBoxRatio;
// Set the boundaries of the face overlay validation box based on the preview
var topBound = (h - boxSize) / 2;
var leftBound = (w - boxSize) / 2;
var rightBound = leftBound + boxSize;
var bottomBound = topBound + boxSize;
//get the x and y positions of the left and right eyes
var eyeLX = latestEyeFeatures.left.imagex;
var eyeLY = latestEyeFeatures.left.imagey;
var eyeRX = latestEyeFeatures.right.imagex;
var eyeRY = latestEyeFeatures.right.imagey;
var xPositions = false;
var yPositions = false;
//check if the x values for the left and right eye are within the
//validation box
if (eyeLX > leftBound && eyeLX < rightBound) {
if (eyeRX > leftBound && eyeRX < rightBound) {
xPositions = true;
}
}
//check if the y values for the left and right eye are within the
//validation box
if (eyeLY > topBound && eyeLY < bottomBound) {
if (eyeRY > topBound && eyeRY < bottomBound) {
yPositions = true;
}
}
//if the x and y values for both the left and right eye are within
//the validation box then the box border turns green, otherwise if
//the eyes are outside of the box the colour is red
if (xPositions && yPositions) {
faceFeedbackBox.style.border = "solid green";
} else {
faceFeedbackBox.style.border = "solid red";
}
} else faceFeedbackBox.style.border = "solid black";
}
/**
* This draws the point (x,y) onto the canvas in the HTML
* @param {colour} colour - The colour of the circle to plot
* @param {x} x - The x co-ordinate of the desired point to plot
* @param {y} y - The y co-ordinate of the desired point to plot
*/
function drawCoordinates(colour, x, y) {
var ctx = document.getElementById("plotting_canvas").getContext("2d");
ctx.fillStyle = colour; // Red color
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2, true);
ctx.fill();
}
/**
* Gets the pupil features by following the pipeline which threads an eyes object through each call:
* curTracker gets eye patches -> blink detector -> pupil detection
* @param {Canvas} canvas - a canvas which will have the video drawn onto it
* @param {Number} width - the width of canvas
* @param {Number} height - the height of canvas
*/
function getPupilFeatures(canvas, width, height) {
if (!canvas) {
return;
}
try {
return curTracker.getEyePatches(canvas, width, height);
} catch (err) {
console.log("can't get pupil features ", err);
return null;
}
}
/**
* Gets the most current frame of video and paints it to a resized version of the canvas with width and height
* @param {Canvas} canvas - the canvas to paint the video on to
* @param {Number} width - the new width of the canvas
* @param {Number} height - the new height of the canvas
*/
function paintCurrentFrame(canvas, width, height) {
if (canvas.width != width) {
canvas.width = width;
}
if (canvas.height != height) {
canvas.height = height;
}
var ctx = canvas.getContext("2d");
ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
}
/**
* Paints the video to a canvas and runs the prediction pipeline to get a prediction
* @param {Number|undefined} regModelIndex - The prediction index we're looking for
* @returns {*}
*/
async function getPrediction(regModelIndex) {
// this allows getPrediction to work even when webgazer is paused, since the only necessary
// component for getPrediction in loop() is paintCurrentFrame().
if (paused) {
paintCurrentFrame(
videoElementCanvas,
videoElementCanvas.width,
videoElementCanvas.height
);
}
var time = performance.now();
var predictions = [];
// [20200617 xk] TODO: this call should be made async somehow. will take some work.
latestEyeFeatures = await getPupilFeatures(
videoElementCanvas,
videoElementCanvas.width,
videoElementCanvas.height
);
if (regs.length === 0) {
console.log("regression not set, call setRegression()");
return null;
}
for (var reg in regs) {
predictions.push(regs[reg].predict(latestEyeFeatures));
}
if (regModelIndex !== undefined) {
return predictions[regModelIndex] === null
? null
: {
x: predictions[regModelIndex].x,
y: predictions[regModelIndex].y,
eyeFeatures: latestEyeFeatures,
t: time,
};
} else {
return predictions.length === 0 || predictions[0] === null
? null
: {
x: predictions[0].x,
y: predictions[0].y,
eyeFeatures: latestEyeFeatures,
all: predictions,
t: time,
};
}
}
/**
* Runs every available animation frame if webgazer is not paused
*/
var smoothingVals = new src_webgazer.util.DataWindow(4);
var src_k = 0;
async function loop() {
if (!paused) {
// [20200617 XK] TODO: there is currently lag between the camera input and the face overlay. This behavior
// is not seen in the facemesh demo. probably need to optimize async implementation. I think the issue lies
// in the implementation of getPrediction().
// Paint the latest video frame into the canvas which will be analyzed by WebGazer
// [20180729 JT] Why do we need to do this? clmTracker does this itself _already_, which is just duplicating the work.
// Is it because other trackers need a canvas instead of an img/video element?
paintCurrentFrame(
videoElementCanvas,
videoElementCanvas.width,
videoElementCanvas.height
);
// Get gaze prediction (ask clm to track; pass the data to the regressor; get back a prediction)
latestGazeData = getPrediction();
// Count time
var elapsedTime = performance.now() - clockStart;
// Draw face overlay
if (src_webgazer.params.showFaceOverlay) {
// Get tracker object
var tracker = src_webgazer.getTracker();
faceOverlay
.getContext("2d")
.clearRect(0, 0, videoElement.videoWidth, videoElement.videoHeight);
tracker.drawFaceOverlay(faceOverlay.getContext("2d"), tracker.getPositions());
}
// Feedback box
// Check that the eyes are inside of the validation box
if (src_webgazer.params.showFaceFeedbackBox) checkEyesInValidationBox();
latestGazeData = await latestGazeData;
// [20200623 xk] callback to function passed into setGazeListener(fn)
callback(latestGazeData, elapsedTime);
if (latestGazeData) {
// [20200608 XK] Smoothing across the most recent 4 predictions, do we need this with Kalman filter?
smoothingVals.push(latestGazeData);
var x = 0;
var y = 0;
var len = smoothingVals.length;
for (var d in smoothingVals.data) {
x += smoothingVals.get(d).x;
y += smoothingVals.get(d).y;
}
var pred = src_webgazer.util.bound({ x: x / len, y: y / len });
if (src_webgazer.params.storingPoints) {
drawCoordinates("blue", pred.x, pred.y); //draws the previous predictions
//store the position of the past fifty occuring tracker preditions
src_webgazer.storePoints(pred.x, pred.y, src_k);
src_k++;
if (src_k == 50) {
src_k = 0;
}
}
// GazeDot
if (src_webgazer.params.showGazeDot) {
gazeDot.style.display = "block";
}
gazeDot.style.transform = "translate3d(" + pred.x + "px," + pred.y + "px,0)";
} else {
gazeDot.style.display = "none";
}
requestAnimationFrame(loop);
}
}
//is problematic to test
//because latestEyeFeatures is not set in many cases
/**
* Records screen position data based on current pupil feature and passes it
* to the regression model.
* @param {Number} x - The x screen position
* @param {Number} y - The y screen position
* @param {String} eventType - The event type to store
* @returns {null}
*/
var recordScreenPosition = function (x, y, eventType) {
if (paused) {
return;
}
if (regs.length === 0) {
console.log("regression not set, call setRegression()");
return null;
}
for (var reg in regs) {
if (latestEyeFeatures) regs[reg].addData(latestEyeFeatures, [x, y], eventType);
}
};
/**
* Records click data and passes it to the regression model
* @param {Event} event - The listened event
*/
var clickListener = async function (event) {
recordScreenPosition(event.clientX, event.clientY, eventTypes[0]); // eventType[0] === 'click'
if (window.saveDataAcrossSessions) {
// Each click stores the next data point into localforage.
await setGlobalData();
// // Debug line
// console.log('Model size: ' + JSON.stringify(await localforage.getItem(localstorageDataLabel)).length / 1000000 + 'MB');
}
};
/**
* Records mouse movement data and passes it to the regression model
* @param {Event} event - The listened event
*/
var moveListener = function (event) {
if (paused) {
return;
}
var now = performance.now();
if (now < moveClock + src_webgazer.params.moveTickSize) {
return;
} else {
moveClock = now;
}
recordScreenPosition(event.clientX, event.clientY, eventTypes[1]); //eventType[1] === 'move'
};
/**
* Add event listeners for mouse click and move.
*/
var addMouseEventListeners = function () {
//third argument set to true so that we get event on 'capture' instead of 'bubbling'
//this prevents a client using event.stopPropagation() preventing our access to the click
document.addEventListener("click", clickListener, true);
document.addEventListener("mousemove", moveListener, true);
};
/**
* Remove event listeners for mouse click and move.
*/
var removeMouseEventListeners = function () {
// must set third argument to same value used in addMouseEventListeners
// for this to work.
document.removeEventListener("click", clickListener, true);
document.removeEventListener("mousemove", moveListener, true);
};
/**
* Loads the global data and passes it to the regression model
*/
async function loadGlobalData() {
// Get settings object from localforage
// [20200611 xk] still unsure what this does, maybe would be good for Kalman filter settings etc?
settings = await localforage.getItem(localstorageSettingsLabel);
settings = settings || defaults;
// Get click data from localforage
var loadData = await localforage.getItem(localstorageDataLabel);
loadData = loadData || defaults;
// Set global var data to newly loaded data
data = loadData;
// Load data into regression model(s)
for (var reg in regs) {
regs[reg].setData(loadData);
}
console.log("loaded stored data into regression model");
}
/**
* Adds data to localforage
*/
async function setGlobalData() {
// Grab data from regression model
var storeData = regs[0].getData() || data; // Array
// Store data into localforage
localforage.setItem(localstorageSettingsLabel, settings); // [20200605 XK] is 'settings' ever being used?
localforage.setItem(localstorageDataLabel, storeData);
//TODO data should probably be stored in webgazer object instead of each regression model
// -> requires duplication of data, but is likely easier on regression model implementors
}
/**
* Clears data from model and global storage
*/
function clearData() {
// Removes data from localforage
localforage.clear();
// Removes data from regression model
for (var reg in regs) {
regs[reg].init();
}
}
/**
* Initializes all needed dom elements and begins the loop
* @param {URL} stream - The video stream to use
*/
async function init(stream) {
//////////////////////////
// Video and video preview
//////////////////////////
var topDist = "0px";
var leftDist = "0px";
// used for webgazer.stopVideo() and webgazer.setCameraConstraints()
videoStream = stream;
// create a video element container to enable customizable placement on the page
videoContainerElement = document.createElement("div");
videoContainerElement.id = src_webgazer.params.videoContainerId;
videoContainerElement.style.display = src_webgazer.params.showVideo ? "block" : "none";
videoContainerElement.style.position = "fixed";
videoContainerElement.style.top = topDist;
videoContainerElement.style.left = leftDist;
videoContainerElement.style.width = src_webgazer.params.videoViewerWidth + "px";
videoContainerElement.style.height = src_webgazer.params.videoViewerHeight + "px";
videoElement = document.createElement("video");
videoElement.setAttribute("playsinline", "");
videoElement.id = src_webgazer.params.videoElementId;
videoElement.srcObject = stream;
videoElement.autoplay = true;
videoElement.style.display = src_webgazer.params.showVideo ? "block" : "none";
videoElement.style.position = "absolute";
// We set these to stop the video appearing too large when it is added for the very first time
videoElement.style.width = src_webgazer.params.videoViewerWidth + "px";
videoElement.style.height = src_webgazer.params.videoViewerHeight + "px";
// videoElement.style.zIndex="-1";
// Canvas for drawing video to pass to clm tracker
videoElementCanvas = document.createElement("canvas");
videoElementCanvas.id = src_webgazer.params.videoElementCanvasId;
videoElementCanvas.style.display = "none";
// Face overlay
// Shows the CLM tracking result
faceOverlay = document.createElement("canvas");
faceOverlay.id = src_webgazer.params.faceOverlayId;
faceOverlay.style.display = src_webgazer.params.showFaceOverlay ? "block" : "none";
faceOverlay.style.position = "absolute";
// Mirror video feed
if (src_webgazer.params.mirrorVideo) {
videoElement.style.setProperty("-moz-transform", "scale(-1, 1)");
videoElement.style.setProperty("-webkit-transform", "scale(-1, 1)");
videoElement.style.setProperty("-o-transform", "scale(-1, 1)");
videoElement.style.setProperty("transform", "scale(-1, 1)");
videoElement.style.setProperty("filter", "FlipH");
faceOverlay.style.setProperty("-moz-transform", "scale(-1, 1)");
faceOverlay.style.setProperty("-webkit-transform", "scale(-1, 1)");
faceOverlay.style.setProperty("-o-transform", "scale(-1, 1)");
faceOverlay.style.setProperty("transform", "scale(-1, 1)");
faceOverlay.style.setProperty("filter", "FlipH");
}
// Feedback box
// Lets the user know when their face is in the middle
faceFeedbackBox = document.createElement("canvas");
faceFeedbackBox.id = src_webgazer.params.faceFeedbackBoxId;
faceFeedbackBox.style.display = src_webgazer.params.showFaceFeedbackBox ? "block" : "none";
faceFeedbackBox.style.border = "solid";
faceFeedbackBox.style.position = "absolute";
// Gaze dot
// Starts offscreen
gazeDot = document.createElement("div");
gazeDot.id = src_webgazer.params.gazeDotId;
gazeDot.style.display = src_webgazer.params.showGazeDot ? "block" : "none";
gazeDot.style.position = "fixed";
gazeDot.style.zIndex = 99999;
gazeDot.style.left = "-5px"; //'-999em';
gazeDot.style.top = "-5px";
gazeDot.style.background = "red";
gazeDot.style.borderRadius = "100%";
gazeDot.style.opacity = "0.7";
gazeDot.style.width = "10px";
gazeDot.style.height = "10px";
// Add other preview/feedback elements to the screen once the video has shown and its parameters are initialized
videoContainerElement.appendChild(videoElement);
document.body.appendChild(videoContainerElement);
function setupPreviewVideo(e) {
// All video preview parts have now been added, so set the size both internally and in the preview window.
setInternalVideoBufferSizes(videoElement.videoWidth, videoElement.videoHeight);
src_webgazer.setVideoViewerSize(
src_webgazer.params.videoViewerWidth,
src_webgazer.params.videoViewerHeight
);
videoContainerElement.appendChild(videoElementCanvas);
videoContainerElement.appendChild(faceOverlay);
videoContainerElement.appendChild(faceFeedbackBox);
document.body.appendChild(gazeDot);
// Run this only once, so remove the event listener
e.target.removeEventListener(e.type, setupPreviewVideo);
}
videoElement.addEventListener("timeupdate", setupPreviewVideo);
addMouseEventListeners();
//BEGIN CALLBACK LOOP
paused = false;
clockStart = performance.now();
await loop();
}
/**
* Initializes navigator.mediaDevices.getUserMedia
* depending on the browser capabilities
*
* @return Promise
*/
function setUserMediaVariable() {
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
// gets the alternative old getUserMedia is possible
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
// set an error message if browser doesn't support getUserMedia
if (!getUserMedia) {
return Promise.reject(
new Error(
"Unfortunately, your browser does not support access to the webcam through the getUserMedia API. Try to use the latest version of Google Chrome, Mozilla Firefox, Opera, or Microsoft Edge instead."
)
);
}
// uses navigator.getUserMedia for older browsers
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
}
//PUBLIC FUNCTIONS - CONTROL
/**
* Starts all state related to webgazer -> dataLoop, video collection, click listener
* If starting fails, call `onFail` param function.
* @param {Function} onFail - Callback to call in case it is impossible to find user camera
* @returns {*}
*/
src_webgazer.begin = function (onFail) {
if (
window.location.protocol !== "https:" &&
window.location.hostname !== "localhost" &&
window.chrome
) {
alert(
"WebGazer works only over https. If you are doing local development, you need to run a local server."
);
}
// Load model data stored in localforage.
if (window.saveDataAcrossSessions) {
loadGlobalData();
}
onFail =
onFail ||
function () {
console.log("No stream");
};
if (debugVideoLoc) {
init(debugVideoLoc);
return src_webgazer;
}
///////////////////////
// SETUP VIDEO ELEMENTS
// Sets .mediaDevices.getUserMedia depending on browser
setUserMediaVariable();
// Request webcam access under specific constraints
// WAIT for access
return new Promise(async (resolve, reject) => {
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia(src_webgazer.params.camConstraints);
init(stream);
resolve(src_webgazer);
} catch (err) {
onFail();
videoElement = null;
stream = null;
reject(err);
}
});
};
/**
* Checks if webgazer has finished initializing after calling begin()
* [20180729 JT] This seems like a bad idea for how this function should be implemented.
* @returns {boolean} if webgazer is ready
*/
src_webgazer.isReady = function () {
if (videoElementCanvas === null) {
return false;
}
return videoElementCanvas.width > 0;
};
/**
* Stops collection of data and predictions
* @returns {webgazer} this
*/
src_webgazer.pause = function () {
paused = true;
return src_webgazer;
};
/**
* Resumes collection of data and predictions if paused
* @returns {webgazer} this
*/
src_webgazer.resume = async function () {
if (!paused) {
return src_webgazer;
}
paused = false;
await loop();
return src_webgazer;
};
/**
* stops collection of data and removes dom modifications, must call begin() to reset up
* @return {webgazer} this
*/
src_webgazer.end = function () {
//loop may run an extra time and fail due to removed elements
paused = true;
//webgazer.stopVideo(); // uncomment if you want to stop the video from streaming
//remove video element and canvas
document.body.removeChild(videoElement);
document.body.removeChild(videoElementCanvas);
return src_webgazer;
};
/**
* Stops the video camera from streaming and removes the video outlines
* @return {webgazer} this
*/
src_webgazer.stopVideo = function () {
// Stops the video from streaming
videoStream.getTracks()[0].stop();
// Removes the outline of the face
document.body.removeChild(faceOverlay);
// Removes the box around the face
document.body.removeChild(faceFeedbackBox);
return src_webgazer;
};
//PUBLIC FUNCTIONS - DEBUG
/**
* Returns if the browser is compatible with webgazer
* @return {boolean} if browser is compatible
*/
src_webgazer.detectCompatibility = function () {
var getUserMedia =
navigator.mediaDevices.getUserMedia ||
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
return getUserMedia !== undefined;
};
/**
* Set whether to show any of the video previews (camera, face overlay, feedback box).
* If true: visibility depends on corresponding params (default all true).
* If false: camera, face overlay, feedback box are all hidden
* @param {bool} val
* @return {webgazer} this
*/
src_webgazer.showVideoPreview = function (val) {
src_webgazer.params.showVideoPreview = val;
src_webgazer.showVideo(val && src_webgazer.params.showVideo);
src_webgazer.showFaceOverlay(val && src_webgazer.params.showFaceOverlay);
src_webgazer.showFaceFeedbackBox(val && src_webgazer.params.showFaceFeedbackBox);
return src_webgazer;
};
/**
* Set whether the camera video preview is visible or not (default true).
* @param {*} bool
* @return {webgazer} this
*/
src_webgazer.showVideo = function (val) {
src_webgazer.params.showVideo = val;
if (videoElement) {
videoElement.style.display = val ? "block" : "none";
}
if (videoContainerElement) {
videoContainerElement.style.display = val ? "block" : "none";
}
return src_webgazer;
};
/**
* Set whether the face overlay is visible or not (default true).
* @param {*} bool
* @return {webgazer} this
*/
src_webgazer.showFaceOverlay = function (val) {
src_webgazer.params.showFaceOverlay = val;
if (faceOverlay) {
faceOverlay.style.display = val ? "block" : "none";
}
return src_webgazer;
};
/**
* Set whether the face feedback box is visible or not (default true).
* @param {*} bool
* @return {webgazer} this
*/
src_webgazer.showFaceFeedbackBox = function (val) {
src_webgazer.params.showFaceFeedbackBox = val;
if (faceFeedbackBox) {
faceFeedbackBox.style.display = val ? "block" : "none";
}
return src_webgazer;
};
/**
* Set whether the gaze prediction point(s) are visible or not.
* Multiple because of a trail of past dots. Default true
* @return {webgazer} this
*/
src_webgazer.showPredictionPoints = function (val) {
src_webgazer.params.showGazeDot = val;
if (gazeDot) {
gazeDot.style.display = val ? "block" : "none";
}
return src_webgazer;
};
/**
* Set whether a Kalman filter will be applied to gaze predictions (default true);
* @return {webgazer} this
*/
src_webgazer.applyKalmanFilter = function (val) {
src_webgazer.params.applyKalmanFilter = val;
return src_webgazer;
};
/**
* Define constraints on the video camera that is used. Useful for non-standard setups.
* This can be set before calling webgazer.begin(), but also mid stream.
*
* @param {Object} constraints Example constraints object:
* { width: { min: 320, ideal: 1280, max: 1920 }, height: { min: 240, ideal: 720, max: 1080 }, facingMode: "user" };
*
* Follows definition here:
* https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API/Constraints
*
* Note: The constraints set here are applied to the video track only. They also _replace_ any constraints, so be sure to set everything you need.
* Warning: Setting a large video resolution will decrease performance, and may require
*/
src_webgazer.setCameraConstraints = async function (constraints) {
var videoTrack, videoSettings;
src_webgazer.params.camConstraints = constraints;
// If the camera stream is already up...
if (videoStream) {
src_webgazer.pause();
videoTrack = videoStream.getVideoTracks()[0];
try {
await videoTrack.applyConstraints(src_webgazer.params.camConstraints);
videoSettings = videoTrack.getSettings();
setInternalVideoBufferSizes(videoSettings.width, videoSettings.height);
} catch (err) {
console.log(err);
return;
}
// Reset and recompute sizes of the video viewer.
// This is only to adjust the feedback box, say, if the aspect ratio of the video has changed.
src_webgazer.setVideoViewerSize(
src_webgazer.params.videoViewerWidth,
src_webgazer.params.videoViewerHeight
);
src_webgazer.getTracker().reset();
await src_webgazer.resume();
}
};
/**
* Does what it says on the tin.
* @param {*} width
* @param {*} height
*/
function setInternalVideoBufferSizes(width, height) {
// Re-set the canvas size used by the internal processes
if (videoElementCanvas) {
videoElementCanvas.width = width;
videoElementCanvas.height = height;
}
// Re-set the face overlay canvas size
if (faceOverlay) {
faceOverlay.width = width;
faceOverlay.height = height;
}
}
/**
* Set a static video file to be used instead of webcam video
* @param {String} videoLoc - video file location
* @return {webgazer} this
*/
src_webgazer.setStaticVideo = function (videoLoc) {
debugVideoLoc = videoLoc;
return src_webgazer;
};
/**
* Set the size of the video viewer
*/
src_webgazer.setVideoViewerSize = function (w, h) {
src_webgazer.params.videoViewerWidth = w;
src_webgazer.params.videoViewerHeight = h;
// Change the video viewer
videoElement.style.width = w + "px";
videoElement.style.height = h + "px";
// Change the face overlay
faceOverlay.style.width = w + "px";
faceOverlay.style.height = h + "px";
// Change the feedback box size
// Compute the boundaries of the face overlay validation box based on the video size
var tlwh = src_webgazer.computeValidationBoxSize();
// Assign them to the object
faceFeedbackBox.style.top = tlwh[0] + "px";
faceFeedbackBox.style.left = tlwh[1] + "px";
faceFeedbackBox.style.width = tlwh[2] + "px";
faceFeedbackBox.style.height = tlwh[3] + "px";
};
/**
* Add the mouse click and move listeners that add training data.
* @return {webgazer} this
*/
src_webgazer.addMouseEventListeners = function () {
addMouseEventListeners();
return src_webgazer;
};
/**
* Remove the mouse click and move listeners that add training data.
* @return {webgazer} this
*/
src_webgazer.removeMouseEventListeners = function () {
removeMouseEventListeners();
return src_webgazer;
};
/**
* Records current screen position for current pupil features.
* @param {String} x - position on screen in the x axis
* @param {String} y - position on screen in the y axis
* @return {webgazer} this
*/
src_webgazer.recordScreenPosition = function (x, y) {
// give this the same weight that a click gets.
recordScreenPosition(x, y, eventTypes[0]);
return src_webgazer;
};
/**
* Records current screen position for current pupil features.
* @param {String} x - position on screen in the x axis
* @param {String} y - position on screen in the y axis
* @param {String} eventType - "click" or "move", as per eventTypes
* @return {webgazer} this
*/
src_webgazer.recordScreenPosition = function (x, y, eventType) {
// give this the same weight that a click gets.
recordScreenPosition(x, y, eventType);
return src_webgazer;
};
/*
* Stores the position of the fifty most recent tracker preditions
*/
src_webgazer.storePoints = function (x, y, k) {
xPast50[k] = x;
yPast50[k] = y;
};
//SETTERS
/**
* Sets the tracking module
* @param {String} name - The name of the tracking module to use
* @return {webgazer} this
*/
src_webgazer.setTracker = function (name) {
if (curTrackerMap[name] === undefined) {
console.log("Invalid tracker selection");
console.log("Options are: ");
for (var t in curTrackerMap) {
console.log(t);
}
return src_webgazer;
}
curTracker = curTrackerMap[name]();
return src_webgazer;
};
/**
* Sets the regression module and clears any other regression modules
* @param {String} name - The name of the regression module to use
* @return {webgazer} this
*/
src_webgazer.setRegression = function (name) {
if (regressionMap[name] === undefined) {
console.log("Invalid regression selection");
console.log("Options are: ");
for (var reg in regressionMap) {
console.log(reg);
}
return src_webgazer;
}
data = regs[0].getData();
regs = [regressionMap[name]()];
regs[0].setData(data);
return src_webgazer;
};
/**
* Adds a new tracker module so that it can be used by setTracker()
* @param {String} name - the new name of the tracker
* @param {Function} constructor - the constructor of the curTracker object
* @return {webgazer} this
*/
src_webgazer.addTrackerModule = function (name, constructor) {
curTrackerMap[name] = function () {
return new constructor();
};
};
/**
* Adds a new regression module so that it can be used by setRegression() and addRegression()
* @param {String} name - the new name of the regression
* @param {Function} constructor - the constructor of the regression object
*/
src_webgazer.addRegressionModule = function (name, constructor) {
regressionMap[name] = function () {
return new constructor();
};
};
/**
* Adds a new regression module to the list of regression modules, seeding its data from the first regression module
* @param {String} name - the string name of the regression module to add
* @return {webgazer} this
*/
src_webgazer.addRegression = function (name) {
var newReg = regressionMap[name]();
data = regs[0].getData();
newReg.setData(data);
regs.push(newReg);
return src_webgazer;
};
/**
* Sets a callback to be executed on every gaze event (currently all time steps)
* @param {function} listener - The callback function to call (it must be like function(data, elapsedTime))
* @return {webgazer} this
*/
src_webgazer.setGazeListener = function (listener) {
callback = listener;
return src_webgazer;
};
/**
* Removes the callback set by setGazeListener
* @return {webgazer} this
*/
src_webgazer.clearGazeListener = function () {
callback = nopCallback;
return src_webgazer;
};
/**
* Set the video element canvas; useful if you want to run WebGazer on your own canvas (e.g., on any random image).
* @return The current video element canvas
*/
src_webgazer.setVideoElementCanvas = function (canvas) {
videoElementCanvas = canvas;
};
/**
* Clear data from localforage and from regs
*/
src_webgazer.clearData = async function () {
clearData();
};
//GETTERS
/**
* Returns the tracker currently in use
* @return {tracker} an object following the tracker interface
*/
src_webgazer.getTracker = function () {
return curTracker;
};
/**
* Returns the regression currently in use
* @return {Array.<Object>} an array of regression objects following the regression interface
*/
src_webgazer.getRegression = function () {
return regs;
};
/**
* Requests an immediate prediction
* @return {object} prediction data object
*/
src_webgazer.getCurrentPrediction = function () {
return getPrediction();
};
/**
* returns the different event types that may be passed to regressions when calling regression.addData()
* @return {Array} array of strings where each string is an event type
*/
src_webgazer.params.getEventTypes = function () {
return eventTypes.slice();
};
/**
* Get the video element canvas that WebGazer uses internally on which to run its face tracker.
* @return The current video element canvas
*/
src_webgazer.getVideoElementCanvas = function () {
return videoElementCanvas;
};
/**
* @return array [a,b] where a is width ratio and b is height ratio
*/
src_webgazer.getVideoPreviewToCameraResolutionRatio = function () {
return [
src_webgazer.params.videoViewerWidth / videoElement.videoWidth,
src_webgazer.params.videoViewerHeight / videoElement.videoHeight,
];
};
/*
* Gets the fifty most recent tracker preditions
*/
src_webgazer.getStoredPoints = function () {
return [xPast50, yPast50];
};
/* harmony default export */ var src = (__webpack_exports__["default"] = src_webgazer);
/***/
},
/******/
]
)["default"];
//# sourceMappingURL=webgazer.js.map