@tensorflow/tfjs-core
Version:
Hardware-accelerated JavaScript library for machine intelligence
1,167 lines • 130 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var seedrandom = require("seedrandom");
var environment_1 = require("../environment");
var log_1 = require("../log");
var array_ops_util = require("../ops/array_ops_util");
var axis_util = require("../ops/axis_util");
var broadcast_util = require("../ops/broadcast_util");
var concat_util = require("../ops/concat_util");
var erf_util = require("../ops/erf_util");
var gather_nd_util = require("../ops/gather_nd_util");
var ops = require("../ops/ops");
var ops_1 = require("../ops/ops");
var scatter_nd_util = require("../ops/scatter_nd_util");
var selu_util = require("../ops/selu_util");
var slice_util_1 = require("../ops/slice_util");
var tensor_1 = require("../tensor");
var types_1 = require("../types");
var util = require("../util");
var util_1 = require("../util");
var backend_1 = require("./backend");
var backend_util = require("./backend_util");
var complex_util = require("./complex_util");
var non_max_suppression_impl_1 = require("./non_max_suppression_impl");
var split_shared_1 = require("./split_shared");
var topk_impl_1 = require("./topk_impl");
var where_impl_1 = require("./where_impl");
function mapActivation(backend, activation, x) {
if (activation === 'linear') {
return backend.linear(x);
}
else if (activation === 'relu') {
return backend.relu(x);
}
throw new Error("Activation " + activation + " has not been implemented for the CPU backend.");
}
var MathBackendCPU = (function () {
function MathBackendCPU() {
this.blockSize = 48;
this.firstUse = true;
if (environment_1.ENV.get('IS_BROWSER')) {
this.fromPixels2DContext =
document.createElement('canvas').getContext('2d');
}
}
MathBackendCPU.prototype.setDataMover = function (dataMover) {
this.data = new backend_1.DataStorage(dataMover);
};
MathBackendCPU.prototype.register = function (dataId, shape, dtype) {
if (this.firstUse) {
this.firstUse = false;
if (environment_1.ENV.get('IS_NODE')) {
log_1.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============================\n');
}
}
if (this.data.has(dataId)) {
throw new Error("Data buffer is already registered");
}
this.data.set(dataId, { dtype: dtype });
};
MathBackendCPU.prototype.write = function (dataId, values) {
if (values == null) {
throw new Error('MathBackendCPU.write(): values can not be null');
}
this.data.get(dataId).values = values;
};
MathBackendCPU.prototype.fromPixels = function (pixels, numChannels) {
if (pixels == null) {
throw new Error('pixels passed to tf.fromPixels() can not be null');
}
var vals;
if (environment_1.ENV.get('IS_NODE') && pixels.getContext == null) {
throw new Error('When running in node, pixels must be an HTMLCanvasElement ' +
'like the one returned by the `canvas` npm package');
}
if (pixels.getContext != null) {
vals = pixels
.getContext('2d')
.getImageData(0, 0, pixels.width, pixels.height)
.data;
}
else if (pixels instanceof ImageData) {
vals = pixels.data;
}
else if (pixels instanceof HTMLImageElement ||
pixels instanceof HTMLVideoElement) {
if (this.fromPixels2DContext == null) {
throw new Error('Can\'t read pixels from HTMLImageElement outside ' +
'the browser.');
}
this.fromPixels2DContext.canvas.width = pixels.width;
this.fromPixels2DContext.canvas.height = pixels.height;
this.fromPixels2DContext.drawImage(pixels, 0, 0, pixels.width, pixels.height);
vals = this.fromPixels2DContext
.getImageData(0, 0, pixels.width, pixels.height)
.data;
}
else {
throw new Error('pixels passed to tf.fromPixels() must be either an ' +
"HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or " +
("ImageData, but was " + pixels.constructor.name));
}
var values;
if (numChannels === 4) {
values = new Int32Array(vals);
}
else {
var numPixels = pixels.width * pixels.height;
values = new Int32Array(numPixels * numChannels);
for (var i = 0; i < numPixels; i++) {
for (var channel = 0; channel < numChannels; ++channel) {
values[i * numChannels + channel] = vals[i * 4 + channel];
}
}
}
var outShape = [pixels.height, pixels.width, numChannels];
return ops_1.tensor3d(values, outShape, 'int32');
};
MathBackendCPU.prototype.read = function (dataId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2, this.readSync(dataId)];
});
});
};
MathBackendCPU.prototype.readSync = function (dataId) {
var _a = this.data.get(dataId), dtype = _a.dtype, complexTensors = _a.complexTensors;
if (dtype === 'complex64') {
var realValues = complexTensors.real.dataSync();
var imagValues = complexTensors.imag.dataSync();
return complex_util.mergeRealAndImagArrays(realValues, imagValues);
}
return this.data.get(dataId).values;
};
MathBackendCPU.prototype.disposeData = function (dataId) {
if (this.data.has(dataId)) {
var complexTensors = this.data.get(dataId).complexTensors;
if (complexTensors != null) {
complexTensors.real.dispose();
complexTensors.imag.dispose();
}
this.data.delete(dataId);
}
};
MathBackendCPU.prototype.time = function (f) {
return __awaiter(this, void 0, void 0, function () {
var start, kernelMs;
return __generator(this, function (_a) {
start = util_1.now();
f();
kernelMs = util_1.now() - start;
return [2, { kernelMs: kernelMs }];
});
});
};
MathBackendCPU.prototype.memory = function () {
return {
unreliable: true,
reasons: ['The reported memory is an upper bound. Due to automatic garbage ' +
'collection, the true allocated memory may be less.']
};
};
MathBackendCPU.prototype.complex = function (real, imag) {
var result = tensor_1.Tensor.make(real.shape, {}, 'complex64');
var resultData = this.data.get(result.dataId);
resultData.complexTensors = {
real: environment_1.ENV.engine.keep(real.clone()),
imag: environment_1.ENV.engine.keep(imag.clone())
};
return result;
};
MathBackendCPU.prototype.real = function (input) {
var resultData = this.data.get(input.dataId);
return resultData.complexTensors.real.clone();
};
MathBackendCPU.prototype.imag = function (input) {
var resultData = this.data.get(input.dataId);
return resultData.complexTensors.imag.clone();
};
MathBackendCPU.prototype.assertNotComplex = function (tensor, opName) {
if (!Array.isArray(tensor)) {
tensor = [tensor];
}
tensor.forEach(function (t) {
if (t != null) {
util.assert(t.dtype !== 'complex64', opName + " does not support complex64 tensors.");
}
});
};
MathBackendCPU.prototype.slice = function (x, begin, size) {
this.assertNotComplex(x, 'slice');
var isContinous = slice_util_1.isSliceContinous(x.shape, begin, size);
if (isContinous) {
var flatOffset = slice_util_1.computeFlatOffset(begin, x.strides);
var length_1 = util.sizeFromShape(size);
var vals = x.dataSync();
return ops_1.tensor(vals.subarray(flatOffset, flatOffset + length_1), size, x.dtype);
}
var buffer = ops.buffer(size, x.dtype);
for (var i = 0; i < buffer.size; ++i) {
var loc = buffer.indexToLoc(i);
var xLoc = loc.map(function (idx, j) { return idx + begin[j]; });
buffer.values[i] = x.get.apply(x, xLoc);
}
return buffer.toTensor();
};
MathBackendCPU.prototype.stridedSlice = function (x, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
this.assertNotComplex(x, 'stridedSlice');
var _a = slice_util_1.getStridedSlicedInfo(x.shape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask), beginIndex = _a[0], size = _a[1], shrinkAxis = _a[2];
var shape = size.filter(function (v, index) { return shrinkAxis.indexOf(index) === -1; });
if (shape.some(function (axis) { return axis === 0; })) {
return ops.tensor([], shape);
}
var buffer = ops.buffer(size, x.dtype);
for (var i = 0; i < buffer.size; i++) {
var loc = buffer.indexToLoc(i);
var newLoc = new Array(loc.length);
for (var j = 0; j < newLoc.length; j++) {
newLoc[j] = loc[j] * strides[j] + beginIndex[j];
}
buffer.set.apply(buffer, [x.get.apply(x, newLoc)].concat(loc));
}
return buffer.toTensor().reshape(shape);
};
MathBackendCPU.prototype.unstack = function (x, axis) {
var num = x.shape[axis];
var outShape = new Array(x.rank - 1);
var outIndex = 0;
for (var i = 0; i < x.rank; i++) {
if (i !== axis) {
outShape[outIndex++] = x.shape[i];
}
}
var begin = new Array(x.rank).fill(0);
var size = x.shape.slice();
size[axis] = 1;
var res = new Array(num);
for (var i = 0; i < res.length; i++) {
begin[axis] = i;
res[i] = this.slice(x, begin, size).reshape(outShape);
}
return res;
};
MathBackendCPU.prototype.reverse = function (x, axis) {
this.assertNotComplex(x, 'reverse');
var buffer = ops.buffer(x.shape, x.dtype);
var xBuffer = x.buffer();
var _loop_1 = function (i) {
var outLoc = buffer.indexToLoc(i);
var inLoc = outLoc.slice();
axis.forEach(function (ax) { return inLoc[ax] = x.shape[ax] - 1 - inLoc[ax]; });
buffer.set.apply(buffer, [xBuffer.get.apply(xBuffer, inLoc)].concat(outLoc));
};
for (var i = 0; i < buffer.size; i++) {
_loop_1(i);
}
return buffer.toTensor();
};
MathBackendCPU.prototype.concat = function (tensors, axis) {
this.assertNotComplex(tensors, 'concat');
var tensors2D = tensors.map(function (t) {
var innerSize = util.sizeFromShape(t.shape.slice(axis));
return t.as2D(-1, innerSize);
});
var outShape = concat_util.computeOutShape(tensors2D.map(function (t) { return t.shape; }), 1);
var values = ops.buffer(outShape, tensors[0].dtype)
.values;
if (tensors2D[0].shape[0] === 1) {
var offset_1 = 0;
tensors2D.forEach(function (t) {
values.set(t.dataSync(), offset_1);
offset_1 += t.size;
});
}
else {
var colOffset_1 = 0;
tensors2D.forEach(function (t) {
var tVals = t.dataSync();
var tIdx = 0;
for (var row = 0; row < t.shape[0]; ++row) {
var resIdx = row * outShape[1] + colOffset_1;
for (var col = 0; col < t.shape[1]; ++col) {
values[resIdx + col] = tVals[tIdx++];
}
}
colOffset_1 += t.shape[1];
});
}
var finalOutShape = concat_util.computeOutShape(tensors.map(function (t) { return t.shape; }), axis);
return ops_1.tensor(values, finalOutShape, tensors[0].dtype);
};
MathBackendCPU.prototype.neg = function (x) {
this.assertNotComplex(x, 'neg');
return this.multiply(ops.scalar(-1), x);
};
MathBackendCPU.prototype.add = function (a, b) {
if (a.dtype === 'complex64' || b.dtype === 'complex64') {
return this.broadcastedBinaryComplexOp(a.cast('complex64'), b.cast('complex64'), function (aReal, aImag, bReal, bImag) {
return { real: aReal + bReal, imag: aImag + bImag };
});
}
return this.broadcastedBinaryOp(a, b, types_1.upcastType(a.dtype, b.dtype), function (aValue, bValue) { return aValue + bValue; });
};
MathBackendCPU.prototype.addN = function (tensors) {
this.assertNotComplex(tensors, 'addN');
var vals = tensors.map(function (t) { return t.dataSync(); });
var result = ops.buffer(tensors[0].shape, tensors[0].dtype);
var resultVals = result.values;
for (var i = 0; i < tensors.length; i++) {
var currVals = vals[i];
for (var j = 0; j < resultVals.length; j++) {
resultVals[j] += currVals[j];
}
}
return result.toTensor();
};
MathBackendCPU.prototype.subtract = function (a, b) {
if (a.dtype === 'complex64' || b.dtype === 'complex64') {
return this.broadcastedBinaryComplexOp(a.cast('complex64'), b.cast('complex64'), function (aReal, aImag, bReal, bImag) {
return { real: aReal - bReal, imag: aImag - bImag };
});
}
return this.broadcastedBinaryOp(a, b, types_1.upcastType(a.dtype, b.dtype), function (aValue, bValue) { return aValue - bValue; });
};
MathBackendCPU.prototype.pow = function (a, b) {
this.assertNotComplex([a, b], 'pow');
return this.broadcastedBinaryOp(a, b, a.dtype, function (aValue, bValue) { return Math.pow(aValue, bValue); });
};
MathBackendCPU.prototype.batchMatMul = function (a, b, transposeA, transposeB) {
this.assertNotComplex([a, b], 'matMul');
var sharedDim = transposeA ? a.shape[1] : a.shape[2];
var leftDim = transposeA ? a.shape[2] : a.shape[1];
var rightDim = transposeB ? b.shape[1] : b.shape[2];
var batchDim = a.shape[0];
var aValues = a.dataSync();
var bValues = b.dataSync();
var _a = transposeA ?
[a.strides[0], 1, a.strides[1]] :
[a.strides[0], a.strides[1], 1], aBatch = _a[0], aOuterStep = _a[1], aInnerStep = _a[2];
var _b = transposeB ?
[1, b.strides[1], b.strides[0]] :
[b.strides[1], 1, b.strides[0]], bInnerStep = _b[0], bOuterStep = _b[1], bBatch = _b[2];
var size = leftDim * rightDim;
var result = ops_1.buffer([batchDim, leftDim, rightDim], a.dtype);
var resVals = result.values;
var blockSize = this.blockSize;
for (var b_1 = 0; b_1 < batchDim; b_1++) {
for (var i0 = 0; i0 < leftDim; i0 += blockSize) {
for (var j0 = 0; j0 < rightDim; j0 += blockSize) {
for (var k0 = 0; k0 < sharedDim; k0 += blockSize) {
var iBlock = Math.min(i0 + blockSize, leftDim);
var jBlock = Math.min(j0 + blockSize, rightDim);
var kBlock = Math.min(k0 + blockSize, sharedDim);
for (var i = i0; i < iBlock; i++) {
for (var j = j0; j < jBlock; j++) {
var sum = 0.0;
for (var k = k0; k < kBlock; k++) {
sum += aValues[b_1 * aBatch + i * aOuterStep + k * aInnerStep] *
bValues[k * bInnerStep + j * bOuterStep + b_1 * bBatch];
}
resVals[b_1 * size + (i * rightDim + j)] += sum;
}
}
}
}
}
}
return result.toTensor();
};
MathBackendCPU.prototype.fusedBatchMatMul = function (a, b, transposeA, transposeB, bias, activation) {
var result = this.batchMatMul(a, b, transposeA, transposeB);
if (bias) {
result = this.add(result, bias);
}
if (activation) {
result = mapActivation(this, activation, result);
}
return result;
};
MathBackendCPU.prototype.multiply = function (a, b) {
if (a.dtype === 'complex64' || b.dtype === 'complex64') {
return this.broadcastedBinaryComplexOp(a.cast('complex64'), b.cast('complex64'), function (aReal, aImag, bReal, bImag) {
return {
real: aReal * bReal - aImag * bImag,
imag: aReal * bImag + aImag * bReal
};
});
}
return this.broadcastedBinaryOp(a, b, types_1.upcastType(a.dtype, b.dtype), function (aValue, bValue) { return aValue * bValue; });
};
MathBackendCPU.prototype.realDivide = function (a, b) {
this.assertNotComplex([a, b], 'realDivide');
var op = function (a, b) { return a / b; };
var outputDtype = 'float32';
return this.broadcastedBinaryOp(a, b, outputDtype, op);
};
MathBackendCPU.prototype.floorDiv = function (a, b) {
this.assertNotComplex([a, b], 'floorDiv');
var op = function (a, b) { return Math.floor(a / b); };
var outputDtype = 'int32';
return this.broadcastedBinaryOp(a, b, outputDtype, op);
};
MathBackendCPU.prototype.sum = function (x, axes) {
this.assertNotComplex(x, 'sum');
axis_util.assertAxesAreInnerMostDims('sum', axes, x.rank);
var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
var resultDtype = types_1.upcastType(x.dtype, 'int32');
var result = ops.zeros(outShape, resultDtype);
var reduceSize = util.sizeFromShape(reduceShape);
var vals = result.dataSync();
var aVals = x.dataSync();
for (var i = 0; i < vals.length; ++i) {
var offset = i * reduceSize;
var sum = 0;
for (var j = 0; j < reduceSize; ++j) {
sum += aVals[offset + j];
}
vals[i] = sum;
}
return result;
};
MathBackendCPU.prototype.prod = function (x, axes) {
this.assertNotComplex(x, 'sum');
var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
var resultDtype = types_1.upcastType(x.dtype, 'int32');
var result = ops.zeros(outShape, resultDtype);
var reduceSize = util.sizeFromShape(reduceShape);
var vals = result.dataSync();
var aVals = x.dataSync();
for (var i = 0; i < vals.length; ++i) {
var offset = i * reduceSize;
var prod = 1;
for (var j = 0; j < reduceSize; ++j) {
prod *= aVals[offset + j];
}
vals[i] = prod;
}
return result;
};
MathBackendCPU.prototype.unsortedSegmentSum = function (x, segmentIds, numSegments) {
this.assertNotComplex(x, 'unsortedSegmentSum');
var res = [];
var numIters = x.rank - segmentIds.rank;
for (var i = 0; i < numIters; ++i) {
segmentIds = segmentIds.expandDims(i + 1);
}
for (var i = 0; i < numSegments; ++i) {
var segmentId = ops.scalar(i, 'int32');
var mask = ops.equal(segmentId, segmentIds).asType('float32');
var sum = mask.mul(x).sum(0);
res.push(sum);
}
return ops.stack(res);
};
MathBackendCPU.prototype.argMin = function (x, axis) {
this.assertNotComplex(x, 'argMin');
var axes = [axis];
axis_util.assertAxesAreInnerMostDims('argMin', axes, x.rank);
var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
var result = ops.zeros(outShape, 'int32');
var reduceSize = util.sizeFromShape(reduceShape);
var vals = result.dataSync();
var aVals = x.dataSync();
for (var i = 0; i < vals.length; ++i) {
var offset = i * reduceSize;
var min = aVals[offset];
var minIndex = 0;
for (var j = 0; j < reduceSize; ++j) {
var value = aVals[offset + j];
if (value < min) {
min = value;
minIndex = j;
}
}
vals[i] = minIndex;
}
return result;
};
MathBackendCPU.prototype.argMax = function (x, axis) {
this.assertNotComplex(x, 'argMax');
var axes = [axis];
axis_util.assertAxesAreInnerMostDims('argMax', axes, x.rank);
var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
var result = ops.zeros(outShape, 'int32');
var reduceSize = util.sizeFromShape(reduceShape);
var vals = result.dataSync();
var aVals = x.dataSync();
for (var i = 0; i < vals.length; ++i) {
var offset = i * reduceSize;
var max = aVals[offset];
var maxIndex = 0;
for (var j = 0; j < reduceSize; ++j) {
var value = aVals[offset + j];
if (value > max) {
max = value;
maxIndex = j;
}
}
vals[i] = maxIndex;
}
return result;
};
MathBackendCPU.prototype.cumsum = function (x, axis, exclusive, reverse) {
this.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));
}
var resultDtype = types_1.upcastType(x.dtype, 'int32');
var result = ops.zeros(x.shape, resultDtype);
var vals = result.dataSync();
var aVals = x.dataSync();
var finalDim = x.shape[x.rank - 1];
var indexAdjuster = reverse ?
function (i, j) { return i + finalDim - j - 1; } :
function (i, j) { return i + j; };
for (var i = 0; i < aVals.length; i += finalDim) {
for (var j = 0; j < finalDim; j++) {
var idx = indexAdjuster(i, j);
if (j === 0) {
vals[idx] = exclusive ? 0 : aVals[idx];
}
else {
var prevIdx = indexAdjuster(i, j - 1);
vals[idx] = exclusive ? aVals[prevIdx] + vals[prevIdx] :
aVals[idx] + vals[prevIdx];
}
}
}
return result;
};
MathBackendCPU.prototype.equal = function (a, b) {
this.assertNotComplex([a, b], 'equal');
return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
return (aVal === bVal) ? 1 : 0;
});
};
MathBackendCPU.prototype.notEqual = function (a, b) {
this.assertNotComplex([a, b], 'notEqual');
return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
return (aVal !== bVal) ? 1 : 0;
});
};
MathBackendCPU.prototype.less = function (a, b) {
this.assertNotComplex([a, b], 'less');
return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
return (aVal < bVal) ? 1 : 0;
});
};
MathBackendCPU.prototype.lessEqual = function (a, b) {
this.assertNotComplex([a, b], 'lessEqual');
return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
return (aVal <= bVal) ? 1 : 0;
});
};
MathBackendCPU.prototype.greater = function (a, b) {
this.assertNotComplex([a, b], 'greater');
return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
return (aVal > bVal) ? 1 : 0;
});
};
MathBackendCPU.prototype.greaterEqual = function (a, b) {
this.assertNotComplex([a, b], 'greaterEqual');
return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
return (aVal >= bVal) ? 1 : 0;
});
};
MathBackendCPU.prototype.logicalNot = function (x) {
this.assertNotComplex(x, 'logicalNot');
var values = x.dataSync();
var newValues = new Uint8Array(values.length);
for (var i = 0; i < values.length; ++i) {
newValues[i] = values[i] ? 0 : 1;
}
return tensor_1.Tensor.make(x.shape, { values: newValues }, 'bool');
};
MathBackendCPU.prototype.logicalAnd = function (a, b) {
this.assertNotComplex([a, b], 'logicalAnd');
return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
return aVal && bVal;
});
};
MathBackendCPU.prototype.logicalOr = function (a, b) {
this.assertNotComplex([a, b], 'logicalOr');
return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
return aVal || bVal;
});
};
MathBackendCPU.prototype.select = function (condition, a, b) {
this.assertNotComplex([condition, a, b], 'select');
var values = condition.dataSync();
var aValues = a.dataSync();
var bValues = b.dataSync();
var result = ops.zeros(a.shape, types_1.upcastType(a.dtype, b.dtype));
var newValues = result.dataSync();
var index = 0;
var offset = condition.rank === 0 || condition.rank > 1 || a.rank === 1 ?
1 :
a.shape[1];
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < offset; j++) {
if (values[i] === 1) {
newValues[index++] = aValues[i];
}
else {
newValues[index++] = bValues[i];
}
}
}
return result;
};
MathBackendCPU.prototype.where = function (condition) {
this.assertNotComplex([condition], 'where');
var condVals = condition.dataSync();
return where_impl_1.whereImpl(condition.shape, condVals);
};
MathBackendCPU.prototype.topk = function (x, k, sorted) {
this.assertNotComplex(x, 'topk');
var xVals = x.dataSync();
return topk_impl_1.topkImpl(xVals, x.shape, x.dtype, k, sorted);
};
MathBackendCPU.prototype.min = function (x, axes) {
this.assertNotComplex(x, 'min');
axis_util.assertAxesAreInnerMostDims('min', axes, x.rank);
var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
var result = ops.zeros(outShape, x.dtype);
var reduceSize = util.sizeFromShape(reduceShape);
var vals = result.dataSync();
var aVals = x.dataSync();
for (var i = 0; i < vals.length; ++i) {
var offset = i * reduceSize;
var min = aVals[offset];
for (var j = 0; j < reduceSize; ++j) {
var value = aVals[offset + j];
if (value < min) {
min = value;
}
}
vals[i] = min;
}
return result;
};
MathBackendCPU.prototype.minimum = function (a, b) {
this.assertNotComplex([a, b], 'minimum');
return this.broadcastedBinaryOp(a, b, a.dtype, function (aVal, bVal) { return Math.min(aVal, bVal); });
};
MathBackendCPU.prototype.mod = function (a, b) {
this.assertNotComplex([a, b], 'mod');
return this.broadcastedBinaryOp(a, b, a.dtype, function (aVal, bVal) {
var rem = aVal % bVal;
if ((aVal < 0 && bVal < 0) || (aVal >= 0 && bVal >= 0)) {
return rem;
}
else {
return (rem + bVal) % bVal;
}
});
};
MathBackendCPU.prototype.max = function (x, axes) {
this.assertNotComplex(x, 'max');
axis_util.assertAxesAreInnerMostDims('max', axes, x.rank);
var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
var result = ops.zeros(outShape, x.dtype);
var reduceSize = util.sizeFromShape(reduceShape);
var vals = result.dataSync();
var aVals = x.dataSync();
for (var i = 0; i < vals.length; ++i) {
var offset = i * reduceSize;
var max = aVals[offset];
for (var j = 0; j < reduceSize; ++j) {
var value = aVals[offset + j];
if (value > max) {
max = value;
}
}
vals[i] = max;
}
return result;
};
MathBackendCPU.prototype.maximum = function (a, b) {
this.assertNotComplex([a, b], 'maximum');
return this.broadcastedBinaryOp(a, b, a.dtype, function (aVal, bVal) { return Math.max(aVal, bVal); });
};
MathBackendCPU.prototype.all = function (x, axes) {
this.assertNotComplex(x, 'all');
axis_util.assertAxesAreInnerMostDims('all', axes, x.rank);
var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
var result = ops.zeros(outShape, x.dtype);
var reduceSize = util.sizeFromShape(reduceShape);
var vals = result.dataSync();
var aVals = x.dataSync();
for (var i = 0; i < vals.length; ++i) {
var offset = i * reduceSize;
var all = aVals[offset];
for (var j = 0; j < reduceSize; ++j) {
var value = aVals[offset + j];
all = all && value;
}
vals[i] = all;
}
return result;
};
MathBackendCPU.prototype.any = function (x, axes) {
this.assertNotComplex(x, 'any');
axis_util.assertAxesAreInnerMostDims('any', axes, x.rank);
var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
var result = ops.zeros(outShape, x.dtype);
var reduceSize = util.sizeFromShape(reduceShape);
var vals = result.dataSync();
var aVals = x.dataSync();
for (var i = 0; i < vals.length; ++i) {
var offset = i * reduceSize;
var anyVal = aVals[offset];
for (var j = 0; j < reduceSize; ++j) {
var value = aVals[offset + j];
anyVal = anyVal || value;
}
vals[i] = anyVal;
}
return result;
};
MathBackendCPU.prototype.squaredDifference = function (a, b) {
this.assertNotComplex([a, b], 'squaredDifference');
return this.broadcastedBinaryOp(a, b, a.dtype, function (aVal, bVal) {
var diff = aVal - bVal;
return diff * diff;
});
};
MathBackendCPU.prototype.ceil = function (x) {
this.assertNotComplex(x, 'ceil');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
newValues[i] = Math.ceil(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.floor = function (x) {
this.assertNotComplex(x, 'floor');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
newValues[i] = Math.floor(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.sign = function (x) {
this.assertNotComplex(x, 'x');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var 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 tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.round = function (x) {
this.assertNotComplex(x, 'round');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
var 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 tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.exp = function (x) {
this.assertNotComplex(x, 'exp');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
newValues[i] = Math.exp(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.expm1 = function (x) {
this.assertNotComplex(x, 'expm1');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
newValues[i] = Math.expm1(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.log = function (x) {
this.assertNotComplex(x, 'log');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
var value = values[i];
newValues[i] = Math.log(value);
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.log1p = function (x) {
this.assertNotComplex(x, 'log1p');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
var value = values[i];
newValues[i] = Math.log1p(value);
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.sqrt = function (x) {
this.assertNotComplex(x, 'sqrt');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
var value = values[i];
newValues[i] = Math.sqrt(value);
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.rsqrt = function (x) {
this.assertNotComplex(x, 'rsqrt');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
var value = values[i];
newValues[i] = 1 / Math.sqrt(value);
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.square = function (x) {
this.assertNotComplex(x, 'square');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
var value = values[i];
newValues[i] = value * value;
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.reciprocal = function (x) {
this.assertNotComplex(x, 'reciprocal');
var values = x.dataSync();
var newValues = new Float32Array(values.length);
for (var i = 0; i < values.length; ++i) {
newValues[i] = 1 / values[i];
}
return tensor_1.Tensor.make(x.shape, { values: newValues });
};
MathBackendCPU.prototype.linear = function (x) {
return x;
};
MathBackendCPU.prototype.relu = function (x) {
this.assertNotComplex(x, 'relu');
var res = ops.zeros(x.shape, x.dtype);
var resVals = res.dataSync();
var inVals = x.dataSync();
for (var i = 0; i < inVals.length; ++i) {
resVals[i] = Math.max(0, inVals[i]);
}
return res;
};
MathBackendCPU.prototype.prelu = function (x, a) {
this.assertNotComplex([x, a], 'prelu');
return this.broadcastedBinaryOp(x, a, x.dtype, function (xValue, aValue) { return xValue < 0 ? aValue * xValue : xValue; });
};
MathBackendCPU.prototype.elu = function (x) {
this.assertNotComplex(x, 'elu');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
var v = values[i];
if (v >= 0) {
resultValues[i] = v;
}
else {
resultValues[i] = (Math.exp(v) - 1);
}
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.eluDer = function (dy, y) {
this.assertNotComplex([dy, y], 'eluDer');
var resultValues = new Float32Array(y.size);
var values = y.dataSync();
var dyValues = dy.dataSync();
for (var i = 0; i < values.length; ++i) {
var v = values[i];
if (v >= 1) {
resultValues[i] = dyValues[i];
}
else {
resultValues[i] = dyValues[i] * (v + 1);
}
}
return tensor_1.Tensor.make(y.shape, { values: resultValues });
};
MathBackendCPU.prototype.selu = function (x) {
this.assertNotComplex(x, 'selu');
var scaleAlpha = selu_util.SELU_SCALEALPHA;
var scale = selu_util.SELU_SCALE;
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
var v = values[i];
if (v >= 0) {
resultValues[i] = scale * v;
}
else {
resultValues[i] = scaleAlpha * (Math.exp(v) - 1);
}
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.clip = function (x, min, max) {
this.assertNotComplex(x, 'clip');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
var v = values[i];
resultValues[i] = v > max ? max : (v < min ? min : v);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.abs = function (x) {
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.abs(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.complexAbs = function (x) {
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < x.size; ++i) {
var real = values[i * 2];
var imag = values[i * 2 + 1];
resultValues[i] = Math.hypot(real, imag);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.int = function (x) {
this.assertNotComplex(x, 'int');
var resultValues = new Int32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = values[i];
}
return tensor_1.Tensor.make(x.shape, { values: resultValues }, 'int32');
};
MathBackendCPU.prototype.sigmoid = function (x) {
this.assertNotComplex(x, 'sigmoid');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = 1 / (1 + Math.exp(-values[i]));
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.softplus = function (x) {
this.assertNotComplex(x, 'softplus');
var epsilon = 1.1920928955078125e-7;
var threshold = Math.log(epsilon) + 2.0;
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
var tooLarge = values[i] > -threshold;
var tooSmall = values[i] < threshold;
var expX = Math.exp(values[i]);
var result = void 0;
if (tooSmall) {
result = expX;
}
else if (tooLarge) {
result = values[i];
}
else {
result = Math.log(1.0 + expX);
}
resultValues[i] = result;
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.sin = function (x) {
this.assertNotComplex(x, 'sin');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.sin(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.cos = function (x) {
this.assertNotComplex(x, 'cos');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.cos(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.tan = function (x) {
this.assertNotComplex(x, 'tan');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.tan(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.asin = function (x) {
this.assertNotComplex(x, 'asin');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.asin(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.acos = function (x) {
this.assertNotComplex(x, 'acos');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.acos(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.atan = function (x) {
this.assertNotComplex(x, 'atan');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.atan(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.atan2 = function (a, b) {
this.assertNotComplex([a, b], 'atan2');
return this.broadcastedBinaryOp(a, b, a.dtype, function (aValue, bValue) { return Math.atan2(aValue, bValue); });
};
MathBackendCPU.prototype.sinh = function (x) {
this.assertNotComplex(x, 'sinh');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.sinh(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.cosh = function (x) {
this.assertNotComplex(x, 'cosh');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.cosh(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.tanh = function (x) {
this.assertNotComplex(x, 'tanh');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = util.tanh(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.asinh = function (x) {
this.assertNotComplex(x, 'asinh');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.asinh(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.acosh = function (x) {
this.assertNotComplex(x, 'acosh');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.acosh(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.atanh = function (x) {
this.assertNotComplex(x, 'atanh');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
for (var i = 0; i < values.length; ++i) {
resultValues[i] = Math.atanh(values[i]);
}
return tensor_1.Tensor.make(x.shape, { values: resultValues });
};
MathBackendCPU.prototype.erf = function (x) {
this.assertNotComplex(x, 'erf');
var resultValues = new Float32Array(x.size);
var values = x.dataSync();
var p = erf_util.ERF_P;
var a1 = erf_util.ERF_A1;
var a2 = erf_util.ERF_A2;
var a3 = erf_util.ERF_A3;
var a4 = erf_util.ERF_A4;
var a5 = erf_util.ERF_A5;
for (var i = 0; i < values.length; ++i) {
var v = values[i];
var t = 1