mirror of
https://github.com/zhw2590582/ArtPlayer.git
synced 2026-10-18 19:01:20 -08:00
88136 lines
3.6 MiB
Plaintext
88136 lines
3.6 MiB
Plaintext
// modules are defined as an array
|
|
// [ module function, map of requires ]
|
|
//
|
|
// map of requires is short require name -> numeric require
|
|
//
|
|
// anything defined in a previous bundle is accessed via the
|
|
// orig method which is the require for previous bundles
|
|
|
|
(function (modules, entry, mainEntry, parcelRequireName, globalName) {
|
|
/* eslint-disable no-undef */
|
|
var globalObject =
|
|
typeof globalThis !== 'undefined'
|
|
? globalThis
|
|
: typeof self !== 'undefined'
|
|
? self
|
|
: typeof window !== 'undefined'
|
|
? window
|
|
: typeof global !== 'undefined'
|
|
? global
|
|
: {};
|
|
/* eslint-enable no-undef */
|
|
|
|
// Save the require from previous bundle to this closure if any
|
|
var previousRequire =
|
|
typeof globalObject[parcelRequireName] === 'function' &&
|
|
globalObject[parcelRequireName];
|
|
|
|
var cache = previousRequire.cache || {};
|
|
// Do not use `require` to prevent Webpack from trying to bundle this call
|
|
var nodeRequire =
|
|
typeof module !== 'undefined' &&
|
|
typeof module.require === 'function' &&
|
|
module.require.bind(module);
|
|
|
|
function newRequire(name, jumped) {
|
|
if (!cache[name]) {
|
|
if (!modules[name]) {
|
|
// if we cannot find the module within our internal map or
|
|
// cache jump to the current global require ie. the last bundle
|
|
// that was added to the page.
|
|
var currentRequire =
|
|
typeof globalObject[parcelRequireName] === 'function' &&
|
|
globalObject[parcelRequireName];
|
|
if (!jumped && currentRequire) {
|
|
return currentRequire(name, true);
|
|
}
|
|
|
|
// If there are other bundles on this page the require from the
|
|
// previous one is saved to 'previousRequire'. Repeat this as
|
|
// many times as there are bundles until the module is found or
|
|
// we exhaust the require chain.
|
|
if (previousRequire) {
|
|
return previousRequire(name, true);
|
|
}
|
|
|
|
// Try the node require function if it exists.
|
|
if (nodeRequire && typeof name === 'string') {
|
|
return nodeRequire(name);
|
|
}
|
|
|
|
var err = new Error("Cannot find module '" + name + "'");
|
|
err.code = 'MODULE_NOT_FOUND';
|
|
throw err;
|
|
}
|
|
|
|
localRequire.resolve = resolve;
|
|
localRequire.cache = {};
|
|
|
|
var module = (cache[name] = new newRequire.Module(name));
|
|
|
|
modules[name][0].call(
|
|
module.exports,
|
|
localRequire,
|
|
module,
|
|
module.exports,
|
|
this
|
|
);
|
|
}
|
|
|
|
return cache[name].exports;
|
|
|
|
function localRequire(x) {
|
|
var res = localRequire.resolve(x);
|
|
return res === false ? {} : newRequire(res);
|
|
}
|
|
|
|
function resolve(x) {
|
|
var id = modules[name][1][x];
|
|
return id != null ? id : x;
|
|
}
|
|
}
|
|
|
|
function Module(moduleName) {
|
|
this.id = moduleName;
|
|
this.bundle = newRequire;
|
|
this.exports = {};
|
|
}
|
|
|
|
newRequire.isParcelRequire = true;
|
|
newRequire.Module = Module;
|
|
newRequire.modules = modules;
|
|
newRequire.cache = cache;
|
|
newRequire.parent = previousRequire;
|
|
newRequire.register = function (id, exports) {
|
|
modules[id] = [
|
|
function (require, module) {
|
|
module.exports = exports;
|
|
},
|
|
{},
|
|
];
|
|
};
|
|
|
|
Object.defineProperty(newRequire, 'root', {
|
|
get: function () {
|
|
return globalObject[parcelRequireName];
|
|
},
|
|
});
|
|
|
|
globalObject[parcelRequireName] = newRequire;
|
|
|
|
for (var i = 0; i < entry.length; i++) {
|
|
newRequire(entry[i]);
|
|
}
|
|
|
|
if (mainEntry) {
|
|
// Expose entry point to Node, AMD or browser globals
|
|
// Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
|
|
var mainExports = newRequire(mainEntry);
|
|
|
|
// CommonJS
|
|
if (typeof exports === 'object' && typeof module !== 'undefined') {
|
|
module.exports = mainExports;
|
|
|
|
// RequireJS
|
|
} else if (typeof define === 'function' && define.amd) {
|
|
define(function () {
|
|
return mainExports;
|
|
});
|
|
|
|
// <script>
|
|
} else if (globalName) {
|
|
this[globalName] = mainExports;
|
|
}
|
|
}
|
|
})({"8uLJa":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "default", ()=>artplayerPluginDanmukuMask);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _tfjsBackendWebgl = require("@tensorflow/tfjs-backend-webgl");
|
|
var _tfjsBackendCpu = require("@tensorflow/tfjs-backend-cpu");
|
|
var _bodySegmentation = require("@tensorflow-models/body-segmentation");
|
|
function artplayerPluginDanmukuMask(option = {}) {
|
|
return (art)=>{
|
|
const { template: { $video, $danmuku } } = art;
|
|
let segmenter = null;
|
|
let canvas = null;
|
|
let ctx = null;
|
|
let animationFrameId = null;
|
|
let isInitialized = false;
|
|
const config = {
|
|
solutionPath: option.solutionPath || "https://cdn.jsdelivr.net/npm/@mediapipe/selfie_segmentation",
|
|
modelSelection: option.modelSelection || 1,
|
|
smoothSegmentation: option.smoothSegmentation !== undefined ? option.smoothSegmentation : true,
|
|
minDetectionConfidence: option.minDetectionConfidence || 0.5,
|
|
minTrackingConfidence: option.minTrackingConfidence || 0.5,
|
|
selfieMode: option.selfieMode || false,
|
|
drawContour: option.drawContour || false,
|
|
foregroundThreshold: option.foregroundThreshold || 0.5,
|
|
opacity: option.opacity || 1,
|
|
maskBlurAmount: option.maskBlurAmount || 3
|
|
};
|
|
async function initTensorFlow() {
|
|
try {
|
|
await _tfjsCore.setBackend("webgl");
|
|
} catch (error) {
|
|
console.warn("WebGL backend not available, falling back to CPU");
|
|
await _tfjsCore.setBackend("cpu");
|
|
}
|
|
}
|
|
async function initSegmenter() {
|
|
await initTensorFlow();
|
|
const model = _bodySegmentation.SupportedModels.MediaPipeSelfieSegmentation;
|
|
const segmenterConfig = {
|
|
runtime: "mediapipe",
|
|
modelType: "general",
|
|
solutionPath: config.solutionPath,
|
|
modelSelection: config.modelSelection,
|
|
smoothSegmentation: config.smoothSegmentation,
|
|
minDetectionConfidence: config.minDetectionConfidence,
|
|
minTrackingConfidence: config.minTrackingConfidence,
|
|
selfieMode: config.selfieMode
|
|
};
|
|
try {
|
|
segmenter = await _bodySegmentation.createSegmenter(model, segmenterConfig);
|
|
console.log("Segmenter initialized:", segmenter);
|
|
isInitialized = true;
|
|
} catch (error) {
|
|
console.error("Error initializing segmenter:", error);
|
|
isInitialized = false;
|
|
}
|
|
}
|
|
function setupDanmukuStyle() {
|
|
Object.assign($danmuku.style, {
|
|
maskMode: "alpha",
|
|
maskSize: "contain",
|
|
maskRepeat: "no-repeat",
|
|
backgroundSize: "contain",
|
|
backgroundRepeat: "no-repeat"
|
|
});
|
|
}
|
|
function createCanvas() {
|
|
canvas = document.createElement("canvas");
|
|
ctx = canvas.getContext("2d");
|
|
}
|
|
function makeWhiteTransparent(imageData) {
|
|
const data = imageData.data;
|
|
for(let i = 0; i < data.length; i += 4)if (data[i] > 250 && data[i + 1] > 250 && data[i + 2] > 250) data[i + 3] = 0;
|
|
return imageData;
|
|
}
|
|
async function segmentBody() {
|
|
if (!isInitialized || $video.paused || $video.ended) {
|
|
animationFrameId = requestAnimationFrame(segmentBody);
|
|
return;
|
|
}
|
|
try {
|
|
canvas.width = $video.videoWidth;
|
|
canvas.height = $video.videoHeight;
|
|
const segmentation = await segmenter.segmentPeople($video);
|
|
if (!segmentation || segmentation.length === 0) {
|
|
animationFrameId = requestAnimationFrame(segmentBody);
|
|
return;
|
|
}
|
|
const foregroundColor = {
|
|
r: 255,
|
|
g: 255,
|
|
b: 255,
|
|
a: 255
|
|
};
|
|
const backgroundColor = {
|
|
r: 0,
|
|
g: 0,
|
|
b: 0,
|
|
a: 255
|
|
};
|
|
const mask = await _bodySegmentation.toBinaryMask(segmentation, foregroundColor, backgroundColor, config.drawContour, config.foregroundThreshold);
|
|
await _bodySegmentation.drawMask(canvas, $video, mask, config.opacity, config.maskBlurAmount);
|
|
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
ctx.putImageData(makeWhiteTransparent(imageData), 0, 0);
|
|
$danmuku.style.maskImage = `url(${canvas.toDataURL()})`;
|
|
} catch (error) {
|
|
console.error("Error in segmentBody:", error);
|
|
}
|
|
animationFrameId = requestAnimationFrame(segmentBody);
|
|
}
|
|
async function startSegmentation() {
|
|
if (!isInitialized) await initSegmenter();
|
|
if (!canvas) createCanvas();
|
|
setupDanmukuStyle();
|
|
segmentBody();
|
|
}
|
|
function stopSegmentation() {
|
|
$danmuku.style.maskImage = "none";
|
|
if (animationFrameId) {
|
|
cancelAnimationFrame(animationFrameId);
|
|
animationFrameId = null;
|
|
}
|
|
}
|
|
art.on("ready", startSegmentation);
|
|
art.on("destroy", stopSegmentation);
|
|
return {
|
|
name: "artplayerPluginDanmukuMask",
|
|
start: startSegmentation,
|
|
stop: stopSegmentation
|
|
};
|
|
};
|
|
}
|
|
if (typeof window !== "undefined") window["artplayerPluginDanmukuMask"] = artplayerPluginDanmukuMask;
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6","@tensorflow/tfjs-core":"21Ftl","@tensorflow/tfjs-backend-webgl":"bXLEs","@tensorflow-models/body-segmentation":"5k877","@tensorflow/tfjs-backend-cpu":"bzQr6"}],"5dUr6":[function(require,module,exports) {
|
|
exports.interopDefault = function(a) {
|
|
return a && a.__esModule ? a : {
|
|
default: a
|
|
};
|
|
};
|
|
exports.defineInteropFlag = function(a) {
|
|
Object.defineProperty(a, "__esModule", {
|
|
value: true
|
|
});
|
|
};
|
|
exports.exportAll = function(source, dest) {
|
|
Object.keys(source).forEach(function(key) {
|
|
if (key === "default" || key === "__esModule" || Object.prototype.hasOwnProperty.call(dest, key)) return;
|
|
Object.defineProperty(dest, key, {
|
|
enumerable: true,
|
|
get: function() {
|
|
return source[key];
|
|
}
|
|
});
|
|
});
|
|
return dest;
|
|
};
|
|
exports.export = function(dest, destName, get) {
|
|
Object.defineProperty(dest, destName, {
|
|
enumerable: true,
|
|
get: get
|
|
});
|
|
};
|
|
|
|
},{}],"21Ftl":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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.
|
|
* =============================================================================
|
|
*/ // Required side effectful code.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
var _baseSideEffects = require("./base_side_effects");
|
|
// TODO(mattSoulanille): Move this to base_side_effects.ts
|
|
// It is here for now because custom bundles need to avoid calling it, and they
|
|
// only replace the index.js file, not the base_side_effects file.
|
|
var _registerOptimizers = require("./optimizers/register_optimizers");
|
|
// All exports from this package should be in base.
|
|
var _base = require("./base");
|
|
parcelHelpers.exportAll(_base, exports);
|
|
(0, _registerOptimizers.registerOptimizers)();
|
|
|
|
},{"./base_side_effects":"8sUPD","./optimizers/register_optimizers":"k7xLP","./base":"ATETN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8sUPD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // Required side effectful code for tfjs-core
|
|
// Set up Engine and ENV
|
|
var _engine = require("./engine");
|
|
// Register backend-agnostic flags.
|
|
var _flags = require("./flags");
|
|
// Register platforms
|
|
var _platformBrowser = require("./platforms/platform_browser");
|
|
var _platformNode = require("./platforms/platform_node");
|
|
// Set up OpHandler
|
|
var _buffer = require("./ops/buffer");
|
|
var _cast = require("./ops/cast");
|
|
var _clone = require("./ops/clone");
|
|
var _print = require("./ops/print");
|
|
var _tensor = require("./tensor");
|
|
(0, _engine.getOrMakeEngine)();
|
|
const opHandler = {
|
|
buffer: (0, _buffer.buffer),
|
|
cast: (0, _cast.cast),
|
|
clone: (0, _clone.clone),
|
|
print: (0, _print.print)
|
|
};
|
|
(0, _tensor.setOpHandler)(opHandler);
|
|
|
|
},{"./engine":"1g2qo","./flags":"5yJGC","./platforms/platform_browser":"k39df","./platforms/platform_node":"2Z7zs","./ops/buffer":"dYyY7","./ops/cast":"b4VDA","./ops/clone":"jmQ7S","./ops/print":"5RyfW","./tensor":"cJNoh"}],"1g2qo":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Engine", ()=>Engine);
|
|
parcelHelpers.export(exports, "getOrMakeEngine", ()=>getOrMakeEngine);
|
|
parcelHelpers.export(exports, "ENGINE", ()=>ENGINE);
|
|
/**
|
|
* A implementation of the add op for use within engine and tape.
|
|
*
|
|
* This allows us to avoid a circular dependency between add.ts and engine.
|
|
* It is exported to be available in tape tests.
|
|
*/ parcelHelpers.export(exports, "add", ()=>add);
|
|
var _backend = require("./backends/backend");
|
|
var _environment = require("./environment");
|
|
var _globalUtil = require("./global_util");
|
|
var _kernelNames = require("./kernel_names");
|
|
var _kernelRegistry = require("./kernel_registry");
|
|
var _log = require("./log");
|
|
var _profiler = require("./profiler");
|
|
var _tape = require("./tape");
|
|
var _tensor = require("./tensor");
|
|
var _tensorUtil = require("./tensor_util");
|
|
var _util = require("./util");
|
|
function isRegisteredKernelInvocation(kernelInvocation) {
|
|
return kernelInvocation.kernelName != null;
|
|
}
|
|
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,
|
|
get kernelNames () {
|
|
return Array.from(new Set(this.kernels.map((k)=>k.name)));
|
|
}
|
|
};
|
|
}
|
|
dispose() {
|
|
for(const variableName in this.registeredVariables)this.registeredVariables[variableName].dispose();
|
|
}
|
|
}
|
|
class 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) {
|
|
_log.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 (0, _profiler.Profiler)(this.backendInstance);
|
|
return true;
|
|
}
|
|
setupRegisteredKernels() {
|
|
const kernels = (0, _kernelRegistry.getKernelsForBackend)(this.backendName);
|
|
kernels.forEach((kernel)=>{
|
|
if (kernel.setupFunc != null) kernel.setupFunc(this.backendInstance);
|
|
});
|
|
}
|
|
disposeRegisteredKernels(backendName) {
|
|
const kernels = (0, _kernelRegistry.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.
|
|
Done in a more liberal way than
|
|
previous 'Promise.resolve(backend)===backend'
|
|
as we needed to account for custom Promise
|
|
implementations (e.g. Angular) */ if (backend && !(backend instanceof (0, _backend.KernelBackend)) && typeof backend.then === "function") {
|
|
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;
|
|
_log.warn(`Initialization of backend ${backendName} failed`);
|
|
_log.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) {
|
|
_log.warn(`Initialization of backend ${backendName} failed`);
|
|
_log.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);
|
|
const refCount = srcBackend.refCount(dataId);
|
|
// Delete the tensor from the old backend and move it to the new
|
|
// backend.
|
|
srcBackend.disposeData(dataId, true);
|
|
info.backend = backend;
|
|
backend.move(dataId, values, info.shape, info.dtype, refCount);
|
|
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.nextTensorId++;
|
|
}
|
|
nextVariableId() {
|
|
return 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.
|
|
*/ clone(x) {
|
|
const y = ENGINE.runKernel((0, _kernelNames.Identity), {
|
|
x
|
|
});
|
|
const inputs = {
|
|
x
|
|
};
|
|
const grad = (dy)=>({
|
|
x: ()=>{
|
|
const dtype = "float32";
|
|
const gradInputs = {
|
|
x: dy
|
|
};
|
|
const attrs = {
|
|
dtype
|
|
};
|
|
return ENGINE.runKernel((0, _kernelNames.Cast), gradInputs, // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
attrs);
|
|
}
|
|
});
|
|
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) {
|
|
if (this.backendName == null) // backend has not been initialized yet (backend initialization is lazy
|
|
// can be deferred until an op/ kernel is run).
|
|
// The below getter has side effects that will try to initialize the
|
|
// backend and set properties like this.backendName
|
|
// tslint:disable-next-line: no-unused-expression
|
|
this.backend;
|
|
const hasKernel = (0, _kernelRegistry.getKernel)(kernelName, this.backendName) != null;
|
|
if (!hasKernel) throw new Error(`Kernel '${kernelName}' not registered for backend '${this.backendName}'`);
|
|
return this.runKernelFunc({
|
|
kernelName,
|
|
inputs,
|
|
attrs
|
|
});
|
|
}
|
|
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}'`);
|
|
}
|
|
/**
|
|
* Internal helper method to execute a kernel Func
|
|
*
|
|
* Use `runKernel` to execute kernels from outside of engine.
|
|
*/ runKernelFunc(kernelParams) {
|
|
let outputs;
|
|
let saved = [];
|
|
const isTapeOn = this.isTapeOn();
|
|
const startingBytecount = this.state.numBytes;
|
|
const startingNumTensors = this.state.numTensors;
|
|
if (this.shouldCheckForMemLeaks()) this.state.numDataMovesStack.push(0);
|
|
let kernelFunc;
|
|
if (this.backendName == null) // backend has not been initialized yet (backend initialization is lazy
|
|
// can be deferred until an op/ kernel is run).
|
|
// The below getter has side effects that will try to initialize the
|
|
// backend and set properties like this.backendName
|
|
// tslint:disable-next-line: no-unused-expression
|
|
this.backend;
|
|
let out;
|
|
const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ? kernelParams.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
|
|
// Create the kernelFunc from either a registered kernel OR passed in
|
|
// forward/backward functions (used by custom grad). In this context a
|
|
// kernelFunc wraps a kernel implementation with some bookkeeping.
|
|
if (isRegisteredKernelInvocation(kernelParams)) {
|
|
const { kernelName, inputs, attrs } = kernelParams;
|
|
if (this.backendName == null) // backend has not been initialized yet (backend initialization is lazy
|
|
// can be deferred until an op/ kernel is run).
|
|
// The below getter has side effects that will try to initialize the
|
|
// backend and set properties like this.backendName
|
|
// tslint:disable-next-line: no-unused-expression
|
|
this.backend;
|
|
const kernel = (0, _kernelRegistry.getKernel)(kernelName, this.backendName);
|
|
_util.assert(kernel != null, ()=>`Cannot find registered kernel '${kernelName}' for backend '${this.backendName}'`);
|
|
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((outInfo)=>{
|
|
// todo (yassogba) remove this option (Tensor) when node backend
|
|
// methods have been modularized and they all return tensorInfo.
|
|
// TensorInfos do not have a rank attribute.
|
|
if (outInfo.rank != null) return outInfo;
|
|
return this.makeTensorFromTensorInfo(outInfo);
|
|
});
|
|
// Save any required inputs and outputs.
|
|
// Do not save unless we are recording to the tape. Otherwise it would
|
|
// cause a mem leak since there would be no backprop for these tensors
|
|
// (which would otherwise dispose them).
|
|
if (isTapeOn) {
|
|
const tensorsToSave = this.getTensorsForGradient(kernelName, inputs, outTensors);
|
|
saved = this.saveTensorsForBackwardMode(tensorsToSave);
|
|
}
|
|
return outTensors;
|
|
};
|
|
} else {
|
|
const { forwardFunc } = kernelParams;
|
|
// Running a customGrad op.
|
|
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()) // Scope name is used to print a more helpful error message if needed.
|
|
this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);
|
|
return outs;
|
|
};
|
|
}
|
|
//
|
|
// Run the kernelFunc. Optionally profiling it.
|
|
//
|
|
const { inputs, attrs } = kernelParams;
|
|
const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ? null : kernelParams.backwardsFunc;
|
|
let kernelProfile;
|
|
this.scopedRun(// Stop recording to a tape when running a kernel.
|
|
()=>this.state.kernelDepth++, ()=>this.state.kernelDepth--, ()=>{
|
|
if (!this.ENV.getBool("DEBUG") && !this.state.profiling) outputs = kernelFunc();
|
|
else {
|
|
kernelProfile = this.profiler.profileKernel(kernelOrScopeName, inputs, ()=>kernelFunc());
|
|
if (this.ENV.getBool("DEBUG")) this.profiler.logKernelProfile(kernelProfile);
|
|
outputs = kernelProfile.outputs;
|
|
}
|
|
});
|
|
if (isTapeOn) this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);
|
|
if (this.state.profiling) this.state.activeProfile.kernels.push({
|
|
name: kernelOrScopeName,
|
|
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] != null ? inputs[key].shape : null),
|
|
outputShapes: outputs.map((item)=>item.shape),
|
|
kernelTimeMs: kernelProfile.timeMs,
|
|
extraInfo: kernelProfile.extraInfo
|
|
});
|
|
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.
|
|
*
|
|
* @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 = (0, _kernelRegistry.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);
|
|
}
|
|
// We return an empty list rather than throw an error because the kernel we
|
|
// are looking up may not actually be relevant to backproping through the
|
|
// overall function
|
|
//
|
|
// See 'does not error if irrelevant (pruned) ops are missing grads' test
|
|
// in gradients_test.ts for an example.
|
|
return [];
|
|
}
|
|
/**
|
|
* 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 (0, _tensor.Tensor)(shape, dtype, dataId, this.nextTensorId());
|
|
this.trackTensor(t, backend);
|
|
// Count bytes for string tensors.
|
|
if (dtype === "string") {
|
|
const info = this.state.tensorInfo.get(dataId);
|
|
const newBytes = (0, _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.
|
|
* @deprecated
|
|
*/ makeTensorFromDataId(dataId, shape, dtype, backend) {
|
|
dtype = dtype || "float32";
|
|
const tensorInfo = {
|
|
dataId,
|
|
shape,
|
|
dtype
|
|
};
|
|
return this.makeTensorFromTensorInfo(tensorInfo, backend);
|
|
}
|
|
/**
|
|
* Internal method used by backends. Makes a new tensor that is a wrapper
|
|
* around an existing data id in TensorInfo. It doesn't create a new data id,
|
|
* only increments the ref count used in memory tracking.
|
|
*/ makeTensorFromTensorInfo(tensorInfo, backend) {
|
|
const { dataId, shape, dtype } = tensorInfo;
|
|
const t = new (0, _tensor.Tensor)(shape, dtype, dataId, this.nextTensorId());
|
|
this.trackTensor(t, backend);
|
|
return t;
|
|
}
|
|
makeVariable(initialValue, trainable = true, name, dtype) {
|
|
name = name || this.nextVariableId().toString();
|
|
if (dtype != null && dtype !== initialValue.dtype) initialValue = initialValue.cast(dtype);
|
|
const v = new (0, _tensor.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;
|
|
}
|
|
trackTensor(a, backend) {
|
|
this.state.numTensors++;
|
|
if (a.dtype === "string") this.state.numStringTensors++;
|
|
// 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.numBytes += bytes;
|
|
if (!this.state.tensorInfo.has(a.dataId)) {
|
|
this.state.numDataBuffers++;
|
|
this.state.tensorInfo.set(a.dataId, {
|
|
backend: backend || this.backend,
|
|
dtype: a.dtype,
|
|
shape: a.shape,
|
|
bytes
|
|
});
|
|
}
|
|
if (!(a instanceof (0, _tensor.Variable))) this.track(a);
|
|
}
|
|
// Track the tensor by dataId and increase the refCount for the dataId in the
|
|
// backend.
|
|
// TODO(pyu10055): This is currently used by makeVariable method, to increase
|
|
// refCount on the backend for the dataId. It can potentially be replaced with
|
|
// Identity op indead of calling backend directly.
|
|
incRef(a, backend) {
|
|
this.trackTensor(a, backend);
|
|
this.backend.incRef(a.dataId);
|
|
}
|
|
removeDataId(dataId, backend) {
|
|
if (this.state.tensorInfo.has(dataId) && this.state.tensorInfo.get(dataId).backend === backend) {
|
|
this.state.tensorInfo.delete(dataId);
|
|
this.state.numDataBuffers--;
|
|
}
|
|
}
|
|
disposeTensor(a) {
|
|
if (!this.state.tensorInfo.has(a.dataId)) return;
|
|
const info = this.state.tensorInfo.get(a.dataId);
|
|
this.state.numTensors--;
|
|
if (a.dtype === "string") {
|
|
this.state.numStringTensors--;
|
|
this.state.numBytes -= info.bytes;
|
|
}
|
|
// Don't count bytes for complex numbers as they are counted by their
|
|
// components.
|
|
if (a.dtype !== "complex64" && a.dtype !== "string") {
|
|
const bytes = a.size * _util.bytesPerElement(a.dtype);
|
|
this.state.numBytes -= bytes;
|
|
}
|
|
// Remove the reference to dataId if backend dispose the data successfully
|
|
if (info.backend.disposeData(a.dataId)) this.removeDataId(a.dataId, info.backend);
|
|
// 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 = await 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;
|
|
for (const kernel of this.state.activeProfile.kernels){
|
|
kernel.kernelTimeMs = await kernel.kernelTimeMs;
|
|
kernel.extraInfo = await kernel.extraInfo;
|
|
}
|
|
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 = (0, _kernelRegistry.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 = (0, _tensorUtil.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 (0, _tensor.Tensor), ()=>"The result y returned by f() must be a tensor.");
|
|
// Filter out the nodes that don't connect x => y.
|
|
const filteredTape = (0, _tape.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.
|
|
(0, _tape.backpropagateGradients)(accumulatedGradientMap, filteredTape, // Pass the tidy function to avoid circular dep with `tape.ts`.
|
|
(f)=>this.tidy(f), // Pass an add function to avoide a circular dep with `tape.ts`.
|
|
add);
|
|
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 (0, _tensor.Tensor)), ()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");
|
|
let res;
|
|
const inputMap = {};
|
|
inputs.forEach((input, i)=>{
|
|
inputMap[i] = input;
|
|
});
|
|
const forwardFunc = (_, save)=>{
|
|
res = f(...[
|
|
...inputs,
|
|
save
|
|
]);
|
|
_util.assert(res.value instanceof (0, _tensor.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;
|
|
};
|
|
const backwardsFunc = (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 (0, _tensor.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;
|
|
};
|
|
return this.runKernelFunc({
|
|
forwardFunc,
|
|
backwardsFunc,
|
|
inputs: inputMap
|
|
});
|
|
};
|
|
}
|
|
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);
|
|
}
|
|
readToGPU(dataId, options) {
|
|
// Route the read to the correct backend.
|
|
const info = this.state.tensorInfo.get(dataId);
|
|
return info.backend.readToGPU(dataId, options);
|
|
}
|
|
async time(query) {
|
|
const start = (0, _util.now)();
|
|
const timingInfo = await this.backend.time(query);
|
|
timingInfo.wallMs = (0, _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.nextTensorId = 0;
|
|
Engine.nextVariableId = 0;
|
|
function ones(shape) {
|
|
const values = (0, _util.makeOnesTypedArray)((0, _util.sizeFromShape)(shape), "float32");
|
|
return ENGINE.makeTensor(values, shape, "float32");
|
|
}
|
|
function getOrMakeEngine() {
|
|
const ns = (0, _globalUtil.getGlobalNamespace)();
|
|
if (ns._tfengine == null) {
|
|
const environment = new (0, _environment.Environment)(ns);
|
|
ns._tfengine = new Engine(environment);
|
|
}
|
|
(0, _environment.setEnvironmentGlobal)(ns._tfengine.ENV);
|
|
// Tell the current tensor interface that the global engine is responsible
|
|
// for tracking.
|
|
(0, _tensor.setTensorTracker)(()=>ns._tfengine);
|
|
return ns._tfengine;
|
|
}
|
|
const ENGINE = getOrMakeEngine();
|
|
function add(a, b) {
|
|
// We duplicate Add here to avoid a circular dependency with add.ts.
|
|
const inputs = {
|
|
a,
|
|
b
|
|
};
|
|
return ENGINE.runKernel((0, _kernelNames.Add), inputs);
|
|
}
|
|
|
|
},{"./backends/backend":"dL2i3","./environment":"dXmHm","./global_util":"82SAe","./kernel_names":"hniYO","./kernel_registry":"aG7g9","./log":"5xR9j","./profiler":"aLKDS","./tape":"cUi5z","./tensor":"cJNoh","./tensor_util":"8jzJG","./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dL2i3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "EPSILON_FLOAT32", ()=>EPSILON_FLOAT32);
|
|
parcelHelpers.export(exports, "EPSILON_FLOAT16", ()=>EPSILON_FLOAT16);
|
|
/** Convenient class for storing tensor-related data. */ parcelHelpers.export(exports, "DataStorage", ()=>DataStorage);
|
|
/**
|
|
* 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).
|
|
*/ parcelHelpers.export(exports, "KernelBackend", ()=>KernelBackend);
|
|
const EPSILON_FLOAT32 = 1e-7;
|
|
const EPSILON_FLOAT16 = 1e-4;
|
|
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;
|
|
}
|
|
}
|
|
class KernelBackend {
|
|
refCount(dataId) {
|
|
return notYetImplemented("refCount");
|
|
}
|
|
incRef(dataId) {
|
|
return notYetImplemented("incRef");
|
|
}
|
|
timerAvailable() {
|
|
return true;
|
|
}
|
|
time(f) {
|
|
return notYetImplemented("time");
|
|
}
|
|
read(dataId) {
|
|
return notYetImplemented("read");
|
|
}
|
|
readSync(dataId) {
|
|
return notYetImplemented("readSync");
|
|
}
|
|
readToGPU(dataId, options) {
|
|
return notYetImplemented("readToGPU");
|
|
}
|
|
numDataIds() {
|
|
return notYetImplemented("numDataIds");
|
|
}
|
|
disposeData(dataId, force) {
|
|
return notYetImplemented("disposeData");
|
|
}
|
|
write(values, shape, dtype) {
|
|
return notYetImplemented("write");
|
|
}
|
|
move(dataId, values, shape, dtype, refCount) {
|
|
return notYetImplemented("move");
|
|
}
|
|
createTensorFromGPUData(values, shape, dtype) {
|
|
return notYetImplemented("createTensorFromGPUData");
|
|
}
|
|
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;
|
|
}
|
|
dispose() {
|
|
return notYetImplemented("dispose");
|
|
}
|
|
}
|
|
function notYetImplemented(kernelName) {
|
|
throw new Error(`'${kernelName}' not yet implemented or not found in the registry. ` + `This kernel may not be supported by the tfjs backend you have chosen`);
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dXmHm":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "Environment", ()=>Environment);
|
|
parcelHelpers.export(exports, "getQueryParams", ()=>getQueryParams);
|
|
/**
|
|
* Returns the current environment (a global singleton).
|
|
*
|
|
* The environment object contains the evaluated feature values as well as the
|
|
* active platform.
|
|
*
|
|
* @doc {heading: 'Environment'}
|
|
*/ parcelHelpers.export(exports, "env", ()=>env);
|
|
parcelHelpers.export(exports, "ENV", ()=>ENV);
|
|
parcelHelpers.export(exports, "setEnvironmentGlobal", ()=>setEnvironmentGlobal);
|
|
var _utilBase = require("./util_base");
|
|
// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.
|
|
const TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags";
|
|
class Environment {
|
|
// tslint:disable-next-line: no-any
|
|
constructor(global){
|
|
this.global = global;
|
|
this.flags = {};
|
|
this.flagRegistry = {};
|
|
this.urlFlags = {};
|
|
// Jasmine spies on this in 'environment_test.ts'
|
|
this.getQueryParams = getQueryParams;
|
|
this.populateURLFlags();
|
|
}
|
|
setPlatform(platformName, platform) {
|
|
if (this.platform != null) {
|
|
if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) console.warn(`Platform ${this.platformName} has already been set. ` + `Overwriting the platform with ${platformName}.`);
|
|
}
|
|
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];
|
|
if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) 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 ((0, _utilBase.isPromise)(flagValue)) 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);
|
|
}
|
|
getString(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 = this.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) {
|
|
const lowerCaseValue = value.toLowerCase();
|
|
if (lowerCaseValue === "true" || lowerCaseValue === "false") return lowerCaseValue === "true";
|
|
else if (`${+lowerCaseValue}` === lowerCaseValue) return +lowerCaseValue;
|
|
else return value;
|
|
}
|
|
function env() {
|
|
return ENV;
|
|
}
|
|
let ENV = null;
|
|
function setEnvironmentGlobal(environment) {
|
|
ENV = environment;
|
|
}
|
|
|
|
},{"./util_base":"4Vo4a","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4Vo4a":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ /**
|
|
* 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
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "shuffle", ()=>shuffle);
|
|
/**
|
|
* Shuffles two arrays in-place the same way using Fisher-Yates algorithm.
|
|
*
|
|
* ```js
|
|
* const a = [1,2,3,4,5];
|
|
* const b = [11,22,33,44,55];
|
|
* tf.util.shuffleCombo(a, b);
|
|
* console.log(a, b);
|
|
* ```
|
|
*
|
|
* @param array The first array to shuffle in-place.
|
|
* @param array2 The second array to shuffle in-place with the same permutation
|
|
* as the first array.
|
|
*
|
|
* @doc {heading: 'Util', namespace: 'util'}
|
|
*/ parcelHelpers.export(exports, "shuffleCombo", ()=>shuffleCombo);
|
|
/** Clamps a value to a specified range. */ parcelHelpers.export(exports, "clamp", ()=>clamp);
|
|
parcelHelpers.export(exports, "nearestLargerEven", ()=>nearestLargerEven);
|
|
parcelHelpers.export(exports, "swap", ()=>swap);
|
|
parcelHelpers.export(exports, "sum", ()=>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).
|
|
*/ parcelHelpers.export(exports, "randUniform", ()=>randUniform);
|
|
/** Returns the squared Euclidean distance between two vectors. */ parcelHelpers.export(exports, "distSquared", ()=>distSquared);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "assert", ()=>assert);
|
|
parcelHelpers.export(exports, "assertShapesMatch", ()=>assertShapesMatch);
|
|
parcelHelpers.export(exports, "assertNonNull", ()=>assertNonNull);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "sizeFromShape", ()=>sizeFromShape);
|
|
parcelHelpers.export(exports, "isScalarShape", ()=>isScalarShape);
|
|
parcelHelpers.export(exports, "arraysEqualWithNull", ()=>arraysEqualWithNull);
|
|
parcelHelpers.export(exports, "arraysEqual", ()=>arraysEqual);
|
|
parcelHelpers.export(exports, "isInt", ()=>isInt);
|
|
parcelHelpers.export(exports, "tanh", ()=>tanh);
|
|
parcelHelpers.export(exports, "sizeToSquarishShape", ()=>sizeToSquarishShape);
|
|
/**
|
|
* Creates a new array with randomized indices to a given quantity.
|
|
*
|
|
* ```js
|
|
* const randomTen = tf.util.createShuffledIndices(10);
|
|
* console.log(randomTen);
|
|
* ```
|
|
*
|
|
* @param number Quantity of how many shuffled indices to create.
|
|
*
|
|
* @doc {heading: 'Util', namespace: 'util'}
|
|
*/ parcelHelpers.export(exports, "createShuffledIndices", ()=>createShuffledIndices);
|
|
parcelHelpers.export(exports, "rightPad", ()=>rightPad);
|
|
parcelHelpers.export(exports, "repeatedTry", ()=>repeatedTry);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "inferFromImplicitShape", ()=>inferFromImplicitShape);
|
|
parcelHelpers.export(exports, "parseAxisParam", ()=>parseAxisParam);
|
|
/** Reduces the shape by removing all dimensions of shape 1. */ parcelHelpers.export(exports, "squeezeShape", ()=>squeezeShape);
|
|
parcelHelpers.export(exports, "getTypedArrayFromDType", ()=>getTypedArrayFromDType);
|
|
parcelHelpers.export(exports, "getArrayFromDType", ()=>getArrayFromDType);
|
|
parcelHelpers.export(exports, "checkConversionForErrors", ()=>checkConversionForErrors);
|
|
/** Returns true if the dtype is valid. */ parcelHelpers.export(exports, "isValidDtype", ()=>isValidDtype);
|
|
/**
|
|
* Returns true if the new type can't encode the old type without loss of
|
|
* precision.
|
|
*/ parcelHelpers.export(exports, "hasEncodingLoss", ()=>hasEncodingLoss);
|
|
parcelHelpers.export(exports, "bytesPerElement", ()=>bytesPerElement);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "bytesFromStringArray", ()=>bytesFromStringArray);
|
|
/** Returns true if the value is a string. */ parcelHelpers.export(exports, "isString", ()=>isString);
|
|
parcelHelpers.export(exports, "isBoolean", ()=>isBoolean);
|
|
parcelHelpers.export(exports, "isNumber", ()=>isNumber);
|
|
parcelHelpers.export(exports, "inferDtype", ()=>inferDtype);
|
|
parcelHelpers.export(exports, "isFunction", ()=>isFunction);
|
|
parcelHelpers.export(exports, "nearestDivisor", ()=>nearestDivisor);
|
|
parcelHelpers.export(exports, "computeStrides", ()=>computeStrides);
|
|
// Provide a nested array of TypedArray in given shape.
|
|
parcelHelpers.export(exports, "toNestedArray", ()=>toNestedArray);
|
|
parcelHelpers.export(exports, "convertBackendValuesAndArrayBuffer", ()=>convertBackendValuesAndArrayBuffer);
|
|
parcelHelpers.export(exports, "makeOnesTypedArray", ()=>makeOnesTypedArray);
|
|
parcelHelpers.export(exports, "makeZerosTypedArray", ()=>makeZerosTypedArray);
|
|
/**
|
|
* Make nested `TypedArray` filled with zeros.
|
|
* @param shape The shape information for the nested array.
|
|
* @param dtype dtype of the array element.
|
|
*/ parcelHelpers.export(exports, "makeZerosNestedTypedArray", ()=>makeZerosNestedTypedArray);
|
|
parcelHelpers.export(exports, "assertNonNegativeIntegerDimensions", ()=>assertNonNegativeIntegerDimensions);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "locToIndex", ()=>locToIndex);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "indexToLoc", ()=>indexToLoc);
|
|
/**
|
|
* This method asserts whether an object is a Promise instance.
|
|
* @param object
|
|
*/ // tslint:disable-next-line: no-any
|
|
parcelHelpers.export(exports, "isPromise", ()=>isPromise);
|
|
function shuffle(array) {
|
|
let counter = array.length;
|
|
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
|
|
swap(array, counter, index);
|
|
}
|
|
}
|
|
function shuffleCombo(// tslint:disable-next-line:no-any
|
|
array, // tslint:disable-next-line:no-any
|
|
array2) {
|
|
if (array.length !== array2.length) throw new Error(`Array sizes must match to be shuffled together ` + `First array length was ${array.length}` + `Second array length was ${array2.length}`);
|
|
let counter = array.length;
|
|
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 of each array with it
|
|
swap(array, counter, index);
|
|
swap(array2, counter, index);
|
|
}
|
|
}
|
|
function clamp(min, x, max) {
|
|
return Math.max(min, Math.min(x, max));
|
|
}
|
|
function nearestLargerEven(val) {
|
|
return val % 2 === 0 ? val : val + 1;
|
|
}
|
|
function swap(object, left, right) {
|
|
const temp = object[left];
|
|
object[left] = object[right];
|
|
object[right] = temp;
|
|
}
|
|
function sum(arr) {
|
|
let sum = 0;
|
|
for(let i = 0; i < arr.length; i++)sum += arr[i];
|
|
return sum;
|
|
}
|
|
function randUniform(a, b) {
|
|
const r = Math.random();
|
|
return b * r + (1 - r) * a;
|
|
}
|
|
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;
|
|
}
|
|
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.`);
|
|
}
|
|
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 arraysEqualWithNull(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] !== null && n2[i] !== null && n1[i] !== n2[i]) return false;
|
|
}
|
|
return true;
|
|
}
|
|
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)
|
|
];
|
|
}
|
|
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, scheduleFn) {
|
|
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;
|
|
}
|
|
if (scheduleFn != null) scheduleFn(tryFn, nextBackoff);
|
|
else // google3 does not allow assigning another variable to setTimeout.
|
|
// Don't refactor this so scheduleFn has a default value of setTimeout.
|
|
setTimeout(tryFn, nextBackoff);
|
|
};
|
|
tryFn();
|
|
});
|
|
}
|
|
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);
|
|
}
|
|
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) {
|
|
return getArrayFromDType(dtype, size);
|
|
}
|
|
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}.`);
|
|
}
|
|
}
|
|
function isValidDtype(dtype) {
|
|
return dtype === "bool" || dtype === "complex64" || dtype === "float32" || dtype === "int32" || dtype === "string";
|
|
}
|
|
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 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}`);
|
|
}
|
|
function bytesFromStringArray(arr) {
|
|
if (arr == null) return 0;
|
|
let bytes = 0;
|
|
arr.forEach((x)=>bytes += x.length);
|
|
return bytes;
|
|
}
|
|
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 || values instanceof Uint8ClampedArray) 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 createNestedArray(offset, shape, a, isComplex = false) {
|
|
const ret = new Array();
|
|
if (shape.length === 1) {
|
|
const d = shape[0] * (isComplex ? 2 : 1);
|
|
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) * (isComplex ? 2 : 1);
|
|
for(let i = 0; i < d; i++)ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);
|
|
}
|
|
return ret;
|
|
}
|
|
function toNestedArray(shape, a, isComplex = false) {
|
|
if (shape.length === 0) // Scalar type should return a single number.
|
|
return a[0];
|
|
const size = shape.reduce((acc, c)=>acc * c) * (isComplex ? 2 : 1);
|
|
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 ${a.length}${isComplex ? " for a complex tensor" : ""}.`);
|
|
return createNestedArray(0, shape, a, isComplex);
|
|
}
|
|
function convertBackendValuesAndArrayBuffer(data, dtype) {
|
|
// If is type Uint8Array[], return it directly.
|
|
if (Array.isArray(data)) return data;
|
|
if (dtype === "float32") return data instanceof Float32Array ? data : new Float32Array(data);
|
|
else if (dtype === "int32") return data instanceof Int32Array ? data : new Int32Array(data);
|
|
else if (dtype === "bool" || dtype === "string") return Uint8Array.from(new Int32Array(data));
|
|
else throw new Error(`Unknown dtype ${dtype}`);
|
|
}
|
|
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}`);
|
|
}
|
|
function makeZerosNestedTypedArray(shape, dtype) {
|
|
const size = shape.reduce((prev, curr)=>prev * curr, 1);
|
|
if (dtype == null || dtype === "float32") return toNestedArray(shape, new Float32Array(size));
|
|
else if (dtype === "int32") return toNestedArray(shape, new Int32Array(size));
|
|
else if (dtype === "bool") return toNestedArray(shape, new Uint8Array(size));
|
|
else throw new Error(`Unknown data type ${dtype}`);
|
|
}
|
|
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}].`);
|
|
});
|
|
}
|
|
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;
|
|
}
|
|
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;
|
|
}
|
|
function isPromise(object) {
|
|
// We chose to not use 'obj instanceOf Promise' for two reasons:
|
|
// 1. It only reliably works for es6 Promise, not other Promise
|
|
// implementations.
|
|
// 2. It doesn't work with framework that uses zone.js. zone.js monkey
|
|
// patch the async calls, so it is possible the obj (patched) is
|
|
// comparing to a pre-patched Promise.
|
|
return object && object.then && typeof object.then === "function";
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"82SAe":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // 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
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
// tslint:disable-next-line:no-any
|
|
parcelHelpers.export(exports, "getGlobalNamespace", ()=>getGlobalNamespace);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getGlobal", ()=>getGlobal);
|
|
var global = arguments[3];
|
|
var process = require("585141946453e563");
|
|
let globalNameSpace;
|
|
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;
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
|
|
},{"585141946453e563":"h0aBX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"h0aBX":[function(require,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;
|
|
};
|
|
|
|
},{}],"hniYO":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Abs", ()=>Abs);
|
|
parcelHelpers.export(exports, "Acos", ()=>Acos);
|
|
parcelHelpers.export(exports, "Acosh", ()=>Acosh);
|
|
parcelHelpers.export(exports, "Add", ()=>Add);
|
|
parcelHelpers.export(exports, "AddN", ()=>AddN);
|
|
parcelHelpers.export(exports, "All", ()=>All);
|
|
parcelHelpers.export(exports, "Any", ()=>Any);
|
|
parcelHelpers.export(exports, "ArgMax", ()=>ArgMax);
|
|
parcelHelpers.export(exports, "ArgMin", ()=>ArgMin);
|
|
parcelHelpers.export(exports, "Asin", ()=>Asin);
|
|
parcelHelpers.export(exports, "Asinh", ()=>Asinh);
|
|
parcelHelpers.export(exports, "Atan", ()=>Atan);
|
|
parcelHelpers.export(exports, "Atanh", ()=>Atanh);
|
|
parcelHelpers.export(exports, "Atan2", ()=>Atan2);
|
|
parcelHelpers.export(exports, "AvgPool", ()=>AvgPool);
|
|
parcelHelpers.export(exports, "AvgPoolGrad", ()=>AvgPoolGrad);
|
|
parcelHelpers.export(exports, "AvgPool3D", ()=>AvgPool3D);
|
|
parcelHelpers.export(exports, "AvgPool3DGrad", ()=>AvgPool3DGrad);
|
|
parcelHelpers.export(exports, "BatchMatMul", ()=>BatchMatMul);
|
|
parcelHelpers.export(exports, "BatchToSpaceND", ()=>BatchToSpaceND);
|
|
parcelHelpers.export(exports, "Bincount", ()=>Bincount);
|
|
parcelHelpers.export(exports, "BitwiseAnd", ()=>BitwiseAnd);
|
|
parcelHelpers.export(exports, "BroadcastTo", ()=>BroadcastTo);
|
|
parcelHelpers.export(exports, "BroadcastArgs", ()=>BroadcastArgs);
|
|
parcelHelpers.export(exports, "Cast", ()=>Cast);
|
|
parcelHelpers.export(exports, "Ceil", ()=>Ceil);
|
|
parcelHelpers.export(exports, "ClipByValue", ()=>ClipByValue);
|
|
parcelHelpers.export(exports, "Complex", ()=>Complex);
|
|
parcelHelpers.export(exports, "ComplexAbs", ()=>ComplexAbs);
|
|
parcelHelpers.export(exports, "Concat", ()=>Concat);
|
|
parcelHelpers.export(exports, "Conv2D", ()=>Conv2D);
|
|
parcelHelpers.export(exports, "Conv2DBackpropFilter", ()=>Conv2DBackpropFilter);
|
|
parcelHelpers.export(exports, "Conv2DBackpropInput", ()=>Conv2DBackpropInput);
|
|
parcelHelpers.export(exports, "Conv3D", ()=>Conv3D);
|
|
parcelHelpers.export(exports, "Conv3DBackpropFilterV2", ()=>Conv3DBackpropFilterV2);
|
|
parcelHelpers.export(exports, "Conv3DBackpropInputV2", ()=>Conv3DBackpropInputV2);
|
|
parcelHelpers.export(exports, "Cos", ()=>Cos);
|
|
parcelHelpers.export(exports, "Cosh", ()=>Cosh);
|
|
parcelHelpers.export(exports, "Cumprod", ()=>Cumprod);
|
|
parcelHelpers.export(exports, "Cumsum", ()=>Cumsum);
|
|
parcelHelpers.export(exports, "CropAndResize", ()=>CropAndResize);
|
|
parcelHelpers.export(exports, "DenseBincount", ()=>DenseBincount);
|
|
parcelHelpers.export(exports, "DepthToSpace", ()=>DepthToSpace);
|
|
parcelHelpers.export(exports, "DepthwiseConv2dNative", ()=>DepthwiseConv2dNative);
|
|
parcelHelpers.export(exports, "DepthwiseConv2dNativeBackpropFilter", ()=>DepthwiseConv2dNativeBackpropFilter);
|
|
parcelHelpers.export(exports, "DepthwiseConv2dNativeBackpropInput", ()=>DepthwiseConv2dNativeBackpropInput);
|
|
parcelHelpers.export(exports, "Diag", ()=>Diag);
|
|
parcelHelpers.export(exports, "Dilation2D", ()=>Dilation2D);
|
|
parcelHelpers.export(exports, "Dilation2DBackpropInput", ()=>Dilation2DBackpropInput);
|
|
parcelHelpers.export(exports, "Dilation2DBackpropFilter", ()=>Dilation2DBackpropFilter);
|
|
parcelHelpers.export(exports, "Draw", ()=>Draw);
|
|
parcelHelpers.export(exports, "RealDiv", ()=>RealDiv);
|
|
parcelHelpers.export(exports, "Einsum", ()=>Einsum);
|
|
parcelHelpers.export(exports, "Elu", ()=>Elu);
|
|
parcelHelpers.export(exports, "EluGrad", ()=>EluGrad);
|
|
parcelHelpers.export(exports, "Erf", ()=>Erf);
|
|
parcelHelpers.export(exports, "Equal", ()=>Equal);
|
|
parcelHelpers.export(exports, "Exp", ()=>Exp);
|
|
parcelHelpers.export(exports, "ExpandDims", ()=>ExpandDims);
|
|
parcelHelpers.export(exports, "Expm1", ()=>Expm1);
|
|
parcelHelpers.export(exports, "FFT", ()=>FFT);
|
|
parcelHelpers.export(exports, "Fill", ()=>Fill);
|
|
parcelHelpers.export(exports, "FlipLeftRight", ()=>FlipLeftRight);
|
|
parcelHelpers.export(exports, "Floor", ()=>Floor);
|
|
parcelHelpers.export(exports, "FloorDiv", ()=>FloorDiv);
|
|
parcelHelpers.export(exports, "FusedBatchNorm", ()=>FusedBatchNorm);
|
|
parcelHelpers.export(exports, "GatherV2", ()=>GatherV2);
|
|
parcelHelpers.export(exports, "GatherNd", ()=>GatherNd);
|
|
parcelHelpers.export(exports, "Greater", ()=>Greater);
|
|
parcelHelpers.export(exports, "GreaterEqual", ()=>GreaterEqual);
|
|
parcelHelpers.export(exports, "Identity", ()=>Identity);
|
|
parcelHelpers.export(exports, "IFFT", ()=>IFFT);
|
|
parcelHelpers.export(exports, "Imag", ()=>Imag);
|
|
parcelHelpers.export(exports, "IsFinite", ()=>IsFinite);
|
|
parcelHelpers.export(exports, "IsInf", ()=>IsInf);
|
|
parcelHelpers.export(exports, "IsNan", ()=>IsNan);
|
|
parcelHelpers.export(exports, "LeakyRelu", ()=>LeakyRelu);
|
|
parcelHelpers.export(exports, "Less", ()=>Less);
|
|
parcelHelpers.export(exports, "LessEqual", ()=>LessEqual);
|
|
parcelHelpers.export(exports, "LinSpace", ()=>LinSpace);
|
|
parcelHelpers.export(exports, "Log", ()=>Log);
|
|
parcelHelpers.export(exports, "Log1p", ()=>Log1p);
|
|
parcelHelpers.export(exports, "LogicalAnd", ()=>LogicalAnd);
|
|
parcelHelpers.export(exports, "LogicalNot", ()=>LogicalNot);
|
|
parcelHelpers.export(exports, "LogicalOr", ()=>LogicalOr);
|
|
parcelHelpers.export(exports, "LogicalXor", ()=>LogicalXor);
|
|
parcelHelpers.export(exports, "LogSoftmax", ()=>LogSoftmax);
|
|
parcelHelpers.export(exports, "LowerBound", ()=>LowerBound);
|
|
parcelHelpers.export(exports, "LRN", ()=>LRN);
|
|
parcelHelpers.export(exports, "LRNGrad", ()=>LRNGrad);
|
|
parcelHelpers.export(exports, "MatrixBandPart", ()=>MatrixBandPart);
|
|
parcelHelpers.export(exports, "Max", ()=>Max);
|
|
parcelHelpers.export(exports, "Maximum", ()=>Maximum);
|
|
parcelHelpers.export(exports, "MaxPool", ()=>MaxPool);
|
|
parcelHelpers.export(exports, "MaxPoolGrad", ()=>MaxPoolGrad);
|
|
parcelHelpers.export(exports, "MaxPool3D", ()=>MaxPool3D);
|
|
parcelHelpers.export(exports, "MaxPool3DGrad", ()=>MaxPool3DGrad);
|
|
parcelHelpers.export(exports, "MaxPoolWithArgmax", ()=>MaxPoolWithArgmax);
|
|
parcelHelpers.export(exports, "Mean", ()=>Mean);
|
|
parcelHelpers.export(exports, "Min", ()=>Min);
|
|
parcelHelpers.export(exports, "Minimum", ()=>Minimum);
|
|
parcelHelpers.export(exports, "MirrorPad", ()=>MirrorPad);
|
|
parcelHelpers.export(exports, "Mod", ()=>Mod);
|
|
parcelHelpers.export(exports, "Multinomial", ()=>Multinomial);
|
|
parcelHelpers.export(exports, "Multiply", ()=>Multiply);
|
|
parcelHelpers.export(exports, "Neg", ()=>Neg);
|
|
parcelHelpers.export(exports, "NotEqual", ()=>NotEqual);
|
|
parcelHelpers.export(exports, "NonMaxSuppressionV3", ()=>NonMaxSuppressionV3);
|
|
parcelHelpers.export(exports, "NonMaxSuppressionV4", ()=>NonMaxSuppressionV4);
|
|
parcelHelpers.export(exports, "NonMaxSuppressionV5", ()=>NonMaxSuppressionV5);
|
|
parcelHelpers.export(exports, "OnesLike", ()=>OnesLike);
|
|
parcelHelpers.export(exports, "OneHot", ()=>OneHot);
|
|
parcelHelpers.export(exports, "Pack", ()=>Pack);
|
|
parcelHelpers.export(exports, "PadV2", ()=>PadV2);
|
|
parcelHelpers.export(exports, "Pool", ()=>Pool);
|
|
parcelHelpers.export(exports, "Pow", ()=>Pow);
|
|
parcelHelpers.export(exports, "Prelu", ()=>Prelu);
|
|
parcelHelpers.export(exports, "Prod", ()=>Prod);
|
|
parcelHelpers.export(exports, "RaggedGather", ()=>RaggedGather);
|
|
parcelHelpers.export(exports, "RaggedRange", ()=>RaggedRange);
|
|
parcelHelpers.export(exports, "RaggedTensorToTensor", ()=>RaggedTensorToTensor);
|
|
parcelHelpers.export(exports, "Range", ()=>Range);
|
|
parcelHelpers.export(exports, "Real", ()=>Real);
|
|
parcelHelpers.export(exports, "Reciprocal", ()=>Reciprocal);
|
|
parcelHelpers.export(exports, "Relu", ()=>Relu);
|
|
parcelHelpers.export(exports, "Reshape", ()=>Reshape);
|
|
parcelHelpers.export(exports, "ResizeNearestNeighbor", ()=>ResizeNearestNeighbor);
|
|
parcelHelpers.export(exports, "ResizeNearestNeighborGrad", ()=>ResizeNearestNeighborGrad);
|
|
parcelHelpers.export(exports, "ResizeBilinear", ()=>ResizeBilinear);
|
|
parcelHelpers.export(exports, "ResizeBilinearGrad", ()=>ResizeBilinearGrad);
|
|
parcelHelpers.export(exports, "Relu6", ()=>Relu6);
|
|
parcelHelpers.export(exports, "Reverse", ()=>Reverse);
|
|
parcelHelpers.export(exports, "Round", ()=>Round);
|
|
parcelHelpers.export(exports, "Rsqrt", ()=>Rsqrt);
|
|
parcelHelpers.export(exports, "ScatterNd", ()=>ScatterNd);
|
|
parcelHelpers.export(exports, "TensorScatterUpdate", ()=>TensorScatterUpdate);
|
|
parcelHelpers.export(exports, "SearchSorted", ()=>SearchSorted);
|
|
parcelHelpers.export(exports, "Select", ()=>Select);
|
|
parcelHelpers.export(exports, "Selu", ()=>Selu);
|
|
parcelHelpers.export(exports, "Slice", ()=>Slice);
|
|
parcelHelpers.export(exports, "Sin", ()=>Sin);
|
|
parcelHelpers.export(exports, "Sinh", ()=>Sinh);
|
|
parcelHelpers.export(exports, "Sign", ()=>Sign);
|
|
parcelHelpers.export(exports, "Sigmoid", ()=>Sigmoid);
|
|
parcelHelpers.export(exports, "Softplus", ()=>Softplus);
|
|
parcelHelpers.export(exports, "Sqrt", ()=>Sqrt);
|
|
parcelHelpers.export(exports, "Sum", ()=>Sum);
|
|
parcelHelpers.export(exports, "SpaceToBatchND", ()=>SpaceToBatchND);
|
|
parcelHelpers.export(exports, "SplitV", ()=>SplitV);
|
|
parcelHelpers.export(exports, "Softmax", ()=>Softmax);
|
|
parcelHelpers.export(exports, "SparseFillEmptyRows", ()=>SparseFillEmptyRows);
|
|
parcelHelpers.export(exports, "SparseReshape", ()=>SparseReshape);
|
|
parcelHelpers.export(exports, "SparseSegmentMean", ()=>SparseSegmentMean);
|
|
parcelHelpers.export(exports, "SparseSegmentSum", ()=>SparseSegmentSum);
|
|
parcelHelpers.export(exports, "SparseToDense", ()=>SparseToDense);
|
|
parcelHelpers.export(exports, "SquaredDifference", ()=>SquaredDifference);
|
|
parcelHelpers.export(exports, "Square", ()=>Square);
|
|
parcelHelpers.export(exports, "StaticRegexReplace", ()=>StaticRegexReplace);
|
|
parcelHelpers.export(exports, "StridedSlice", ()=>StridedSlice);
|
|
parcelHelpers.export(exports, "StringNGrams", ()=>StringNGrams);
|
|
parcelHelpers.export(exports, "StringSplit", ()=>StringSplit);
|
|
parcelHelpers.export(exports, "StringToHashBucketFast", ()=>StringToHashBucketFast);
|
|
parcelHelpers.export(exports, "Sub", ()=>Sub);
|
|
parcelHelpers.export(exports, "Tan", ()=>Tan);
|
|
parcelHelpers.export(exports, "Tanh", ()=>Tanh);
|
|
parcelHelpers.export(exports, "Tile", ()=>Tile);
|
|
parcelHelpers.export(exports, "TopK", ()=>TopK);
|
|
parcelHelpers.export(exports, "Transform", ()=>Transform);
|
|
parcelHelpers.export(exports, "Transpose", ()=>Transpose);
|
|
parcelHelpers.export(exports, "Unique", ()=>Unique);
|
|
parcelHelpers.export(exports, "Unpack", ()=>Unpack);
|
|
parcelHelpers.export(exports, "UnsortedSegmentSum", ()=>UnsortedSegmentSum);
|
|
parcelHelpers.export(exports, "UpperBound", ()=>UpperBound);
|
|
parcelHelpers.export(exports, "ZerosLike", ()=>ZerosLike);
|
|
parcelHelpers.export(exports, "Step", ()=>Step);
|
|
parcelHelpers.export(exports, "FromPixels", ()=>FromPixels);
|
|
parcelHelpers.export(exports, "RotateWithOffset", ()=>RotateWithOffset);
|
|
parcelHelpers.export(exports, "_FusedMatMul", ()=>_FusedMatMul);
|
|
parcelHelpers.export(exports, "FusedConv2D", ()=>FusedConv2D);
|
|
parcelHelpers.export(exports, "FusedDepthwiseConv2D", ()=>FusedDepthwiseConv2D);
|
|
const Abs = "Abs";
|
|
const Acos = "Acos";
|
|
const Acosh = "Acosh";
|
|
const Add = "Add";
|
|
const AddN = "AddN";
|
|
const All = "All";
|
|
const Any = "Any";
|
|
const ArgMax = "ArgMax";
|
|
const ArgMin = "ArgMin";
|
|
const Asin = "Asin";
|
|
const Asinh = "Asinh";
|
|
const Atan = "Atan";
|
|
const Atanh = "Atanh";
|
|
const Atan2 = "Atan2";
|
|
const AvgPool = "AvgPool";
|
|
const AvgPoolGrad = "AvgPoolGrad";
|
|
const AvgPool3D = "AvgPool3D";
|
|
const AvgPool3DGrad = "AvgPool3DGrad";
|
|
const BatchMatMul = "BatchMatMul";
|
|
const BatchToSpaceND = "BatchToSpaceND";
|
|
const Bincount = "Bincount";
|
|
const BitwiseAnd = "BitwiseAnd";
|
|
const BroadcastTo = "BroadcastTo";
|
|
const BroadcastArgs = "BroadcastArgs";
|
|
const Cast = "Cast";
|
|
const Ceil = "Ceil";
|
|
const ClipByValue = "ClipByValue";
|
|
const Complex = "Complex";
|
|
const ComplexAbs = "ComplexAbs";
|
|
const Concat = "Concat";
|
|
const Conv2D = "Conv2D";
|
|
const Conv2DBackpropFilter = "Conv2DBackpropFilter";
|
|
const Conv2DBackpropInput = "Conv2DBackpropInput";
|
|
const Conv3D = "Conv3D";
|
|
const Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2";
|
|
const Conv3DBackpropInputV2 = "Conv3DBackpropInputV2";
|
|
const Cos = "Cos";
|
|
const Cosh = "Cosh";
|
|
const Cumprod = "Cumprod";
|
|
const Cumsum = "Cumsum";
|
|
const CropAndResize = "CropAndResize";
|
|
const DenseBincount = "DenseBincount";
|
|
const DepthToSpace = "DepthToSpace";
|
|
const DepthwiseConv2dNative = "DepthwiseConv2dNative";
|
|
const DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter";
|
|
const DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput";
|
|
const Diag = "Diag";
|
|
const Dilation2D = "Dilation2D";
|
|
const Dilation2DBackpropInput = "Dilation2DBackpropInput";
|
|
const Dilation2DBackpropFilter = "Dilation2DBackpropFilter";
|
|
const Draw = "Draw";
|
|
const RealDiv = "RealDiv";
|
|
const Einsum = "Einsum";
|
|
const Elu = "Elu";
|
|
const EluGrad = "EluGrad";
|
|
const Erf = "Erf";
|
|
const Equal = "Equal";
|
|
const Exp = "Exp";
|
|
const ExpandDims = "ExpandDims";
|
|
const Expm1 = "Expm1";
|
|
const FFT = "FFT";
|
|
const Fill = "Fill";
|
|
const FlipLeftRight = "FlipLeftRight";
|
|
const Floor = "Floor";
|
|
const FloorDiv = "FloorDiv";
|
|
const FusedBatchNorm = "FusedBatchNorm";
|
|
const GatherV2 = "GatherV2";
|
|
const GatherNd = "GatherNd";
|
|
const Greater = "Greater";
|
|
const GreaterEqual = "GreaterEqual";
|
|
const Identity = "Identity";
|
|
const IFFT = "IFFT";
|
|
const Imag = "Imag";
|
|
const IsFinite = "IsFinite";
|
|
const IsInf = "IsInf";
|
|
const IsNan = "IsNan";
|
|
const LeakyRelu = "LeakyRelu";
|
|
const Less = "Less";
|
|
const LessEqual = "LessEqual";
|
|
const LinSpace = "LinSpace";
|
|
const Log = "Log";
|
|
const Log1p = "Log1p";
|
|
const LogicalAnd = "LogicalAnd";
|
|
const LogicalNot = "LogicalNot";
|
|
const LogicalOr = "LogicalOr";
|
|
const LogicalXor = "LogicalXor";
|
|
const LogSoftmax = "LogSoftmax";
|
|
const LowerBound = "LowerBound";
|
|
const LRN = "LRN";
|
|
const LRNGrad = "LRNGrad";
|
|
const MatrixBandPart = "MatrixBandPart";
|
|
const Max = "Max";
|
|
const Maximum = "Maximum";
|
|
const MaxPool = "MaxPool";
|
|
const MaxPoolGrad = "MaxPoolGrad";
|
|
const MaxPool3D = "MaxPool3D";
|
|
const MaxPool3DGrad = "MaxPool3DGrad";
|
|
const MaxPoolWithArgmax = "MaxPoolWithArgmax";
|
|
const Mean = "Mean";
|
|
const Min = "Min";
|
|
const Minimum = "Minimum";
|
|
const MirrorPad = "MirrorPad";
|
|
const Mod = "Mod";
|
|
const Multinomial = "Multinomial";
|
|
const Multiply = "Multiply";
|
|
const Neg = "Neg";
|
|
const NotEqual = "NotEqual";
|
|
const NonMaxSuppressionV3 = "NonMaxSuppressionV3";
|
|
const NonMaxSuppressionV4 = "NonMaxSuppressionV4";
|
|
const NonMaxSuppressionV5 = "NonMaxSuppressionV5";
|
|
const OnesLike = "OnesLike";
|
|
const OneHot = "OneHot";
|
|
const Pack = "Pack";
|
|
const PadV2 = "PadV2";
|
|
const Pool = "Pool";
|
|
const Pow = "Pow";
|
|
const Prelu = "Prelu";
|
|
const Prod = "Prod";
|
|
const RaggedGather = "RaggedGather";
|
|
const RaggedRange = "RaggedRange";
|
|
const RaggedTensorToTensor = "RaggedTensorToTensor";
|
|
const Range = "Range";
|
|
const Real = "Real";
|
|
const Reciprocal = "Reciprocal";
|
|
const Relu = "Relu";
|
|
const Reshape = "Reshape";
|
|
const ResizeNearestNeighbor = "ResizeNearestNeighbor";
|
|
const ResizeNearestNeighborGrad = "ResizeNearestNeighborGrad";
|
|
const ResizeBilinear = "ResizeBilinear";
|
|
const ResizeBilinearGrad = "ResizeBilinearGrad";
|
|
const Relu6 = "Relu6";
|
|
const Reverse = "Reverse";
|
|
const Round = "Round";
|
|
const Rsqrt = "Rsqrt";
|
|
const ScatterNd = "ScatterNd";
|
|
const TensorScatterUpdate = "TensorScatterUpdate";
|
|
const SearchSorted = "SearchSorted";
|
|
const Select = "Select";
|
|
const Selu = "Selu";
|
|
const Slice = "Slice";
|
|
const Sin = "Sin";
|
|
const Sinh = "Sinh";
|
|
const Sign = "Sign";
|
|
const Sigmoid = "Sigmoid";
|
|
const Softplus = "Softplus";
|
|
const Sqrt = "Sqrt";
|
|
const Sum = "Sum";
|
|
const SpaceToBatchND = "SpaceToBatchND";
|
|
const SplitV = "SplitV";
|
|
const Softmax = "Softmax";
|
|
const SparseFillEmptyRows = "SparseFillEmptyRows";
|
|
const SparseReshape = "SparseReshape";
|
|
const SparseSegmentMean = "SparseSegmentMean";
|
|
const SparseSegmentSum = "SparseSegmentSum";
|
|
const SparseToDense = "SparseToDense";
|
|
const SquaredDifference = "SquaredDifference";
|
|
const Square = "Square";
|
|
const StaticRegexReplace = "StaticRegexReplace";
|
|
const StridedSlice = "StridedSlice";
|
|
const StringNGrams = "StringNGrams";
|
|
const StringSplit = "StringSplit";
|
|
const StringToHashBucketFast = "StringToHashBucketFast";
|
|
const Sub = "Sub";
|
|
const Tan = "Tan";
|
|
const Tanh = "Tanh";
|
|
const Tile = "Tile";
|
|
const TopK = "TopK";
|
|
const Transform = "Transform";
|
|
const Transpose = "Transpose";
|
|
const Unique = "Unique";
|
|
const Unpack = "Unpack";
|
|
const UnsortedSegmentSum = "UnsortedSegmentSum";
|
|
const UpperBound = "UpperBound";
|
|
const ZerosLike = "ZerosLike";
|
|
const Step = "Step";
|
|
const FromPixels = "FromPixels";
|
|
const RotateWithOffset = "RotateWithOffset";
|
|
const _FusedMatMul = "_FusedMatMul";
|
|
const FusedConv2D = "FusedConv2D";
|
|
const FusedDepthwiseConv2D = "FusedDepthwiseConv2D";
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aG7g9":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getKernel", ()=>getKernel);
|
|
/**
|
|
* Returns the registered gradient info associated with the provided kernel.
|
|
* @param kernelName The official TF kernel name.
|
|
*/ parcelHelpers.export(exports, "getGradient", ()=>getGradient);
|
|
parcelHelpers.export(exports, "getKernelsForBackend", ()=>getKernelsForBackend);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "registerKernel", ()=>registerKernel);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "registerGradient", ()=>registerGradient);
|
|
/**
|
|
* Removes the kernel function from the registry.
|
|
*
|
|
* @param kernelName The official name of the kernel.
|
|
* @param backendName The official name of the backend.
|
|
*
|
|
*/ parcelHelpers.export(exports, "unregisterKernel", ()=>unregisterKernel);
|
|
/** Removes the registered gradient from the global registry. */ parcelHelpers.export(exports, "unregisterGradient", ()=>unregisterGradient);
|
|
/**
|
|
* Finds kernels that have already been registered to a backend and re-registers
|
|
* them for a new backend. Useful for registering custom backends.
|
|
* @param registeredBackendName Already registered backend.
|
|
* @param newBackendName New backend.
|
|
*/ parcelHelpers.export(exports, "copyRegisteredKernels", ()=>copyRegisteredKernels);
|
|
var _environment = require("./environment");
|
|
var _globalUtil = require("./global_util");
|
|
var _log = require("./log");
|
|
const kernelRegistry = (0, _globalUtil.getGlobal)("kernelRegistry", ()=>new Map());
|
|
const gradRegistry = (0, _globalUtil.getGlobal)("gradRegistry", ()=>new Map());
|
|
function getKernel(kernelName, backendName) {
|
|
const key = makeKey(kernelName, backendName);
|
|
return kernelRegistry.get(key);
|
|
}
|
|
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;
|
|
}
|
|
function registerKernel(config) {
|
|
const { kernelName, backendName } = config;
|
|
const key = makeKey(kernelName, backendName);
|
|
if (kernelRegistry.has(key)) _log.warn(`The kernel '${kernelName}' for backend ` + `'${backendName}' is already registered`);
|
|
kernelRegistry.set(key, config);
|
|
}
|
|
function registerGradient(config) {
|
|
const { kernelName } = config;
|
|
if (gradRegistry.has(kernelName)) // TODO (yassogba) after 3.0 assess whether we need to keep this gated
|
|
// to debug mode.
|
|
{
|
|
if ((0, _environment.env)().getBool("DEBUG")) _log.warn(`Overriding the gradient for '${kernelName}'`);
|
|
}
|
|
gradRegistry.set(kernelName, config);
|
|
}
|
|
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);
|
|
}
|
|
function unregisterGradient(kernelName) {
|
|
if (!gradRegistry.has(kernelName)) throw new Error(`The gradient '${kernelName}' for backend is not registered`);
|
|
gradRegistry.delete(kernelName);
|
|
}
|
|
function copyRegisteredKernels(registeredBackendName, newBackendName) {
|
|
const kernels = getKernelsForBackend(registeredBackendName);
|
|
kernels.forEach((kernelConfig)=>{
|
|
const newKernelConfig = Object.assign({}, kernelConfig, {
|
|
backendName: newBackendName
|
|
});
|
|
registerKernel(newKernelConfig);
|
|
});
|
|
}
|
|
function makeKey(kernelName, backendName) {
|
|
return `${backendName}_${kernelName}`;
|
|
}
|
|
|
|
},{"./environment":"dXmHm","./global_util":"82SAe","./log":"5xR9j","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5xR9j":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "warn", ()=>warn);
|
|
parcelHelpers.export(exports, "log", ()=>log);
|
|
var _environment = require("./environment");
|
|
function warn(...msg) {
|
|
if (!((0, _environment.env)().getBool("IS_TEST") || (0, _environment.env)().getBool("PROD"))) console.warn(...msg);
|
|
}
|
|
function log(...msg) {
|
|
if (!((0, _environment.env)().getBool("IS_TEST") || (0, _environment.env)().getBool("PROD"))) console.log(...msg);
|
|
}
|
|
|
|
},{"./environment":"dXmHm","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aLKDS":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Profiler", ()=>Profiler);
|
|
parcelHelpers.export(exports, "checkComputationForErrors", ()=>checkComputationForErrors);
|
|
parcelHelpers.export(exports, "Logger", ()=>Logger);
|
|
var _environment = require("./environment");
|
|
var _util = require("./util");
|
|
class Profiler {
|
|
constructor(backendTimer, logger){
|
|
this.backendTimer = backendTimer;
|
|
this.logger = logger;
|
|
if (logger == null) this.logger = new Logger();
|
|
}
|
|
profileKernel(kernelName, inputs, f) {
|
|
let outputs;
|
|
const holdResultWrapperFn = ()=>{
|
|
outputs = f();
|
|
};
|
|
let timer;
|
|
const start = _util.now();
|
|
if (this.backendTimer.timerAvailable()) timer = this.backendTimer.time(holdResultWrapperFn);
|
|
else {
|
|
holdResultWrapperFn();
|
|
for (const output of outputs)output.dataSync();
|
|
timer = Promise.resolve({
|
|
kernelMs: _util.now() - start
|
|
});
|
|
}
|
|
if ((0, _environment.env)().getBool("CHECK_COMPUTATION_FOR_ERRORS")) for(let i = 0; i < outputs.length; i++){
|
|
const output = outputs[i];
|
|
// Dangling promise here because we don't want to propagate up
|
|
// asynchronicity.
|
|
output.data().then((tensorVals)=>{
|
|
checkComputationForErrors(tensorVals, output.dtype, kernelName);
|
|
});
|
|
}
|
|
const kernelProfile = {
|
|
kernelName,
|
|
outputs,
|
|
inputs,
|
|
timeMs: timer.then((timing)=>timing.kernelMs),
|
|
extraInfo: timer.then((timing)=>timing.getExtraProfileInfo != null ? timing.getExtraProfileInfo() : "")
|
|
};
|
|
return kernelProfile;
|
|
}
|
|
logKernelProfile(kernelProfile) {
|
|
const { kernelName, outputs, timeMs, inputs, extraInfo } = kernelProfile;
|
|
outputs.forEach((result)=>{
|
|
Promise.all([
|
|
result.data(),
|
|
timeMs,
|
|
extraInfo
|
|
]).then((valueContainer)=>{
|
|
this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]);
|
|
});
|
|
});
|
|
}
|
|
}
|
|
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 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];
|
|
if (input != null) {
|
|
// 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");
|
|
}
|
|
}
|
|
|
|
},{"./environment":"dXmHm","./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ctavo":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Create typed array for scalar value. Used for storing in `DataStorage`.
|
|
*/ parcelHelpers.export(exports, "createScalarValue", ()=>createScalarValue);
|
|
parcelHelpers.export(exports, "toTypedArray", ()=>toTypedArray);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "now", ()=>now);
|
|
/**
|
|
* 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://cdn.jsdelivr.net/npm/@tensorflow/tfjs');
|
|
* // handle response
|
|
* ```
|
|
*
|
|
* @doc {heading: 'Util'}
|
|
*/ parcelHelpers.export(exports, "fetch", ()=>fetch);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "encodeString", ()=>encodeString);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "decodeString", ()=>decodeString);
|
|
parcelHelpers.export(exports, "isTypedArray", ()=>isTypedArray);
|
|
// 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'}
|
|
*/ parcelHelpers.export(exports, "flatten", ()=>flatten);
|
|
var _environment = require("./environment");
|
|
var _isTypedArrayBrowser = require("./platforms/is_typed_array_browser");
|
|
var _utilBase = require("./util_base");
|
|
parcelHelpers.exportAll(_utilBase, exports);
|
|
var _hashUtil = require("./hash_util");
|
|
parcelHelpers.exportAll(_hashUtil, exports);
|
|
function createScalarValue(value, dtype) {
|
|
if (dtype === "string") return encodeString(value);
|
|
return toTypedArray([
|
|
value
|
|
], dtype);
|
|
}
|
|
function noConversionNeeded(a, dtype) {
|
|
return a instanceof Float32Array && dtype === "float32" || a instanceof Int32Array && dtype === "int32" || a instanceof Uint8Array && dtype === "bool";
|
|
}
|
|
function toTypedArray(a, dtype) {
|
|
if (dtype === "string") throw new Error("Cannot convert a string[] to a TypedArray");
|
|
if (Array.isArray(a)) a = flatten(a);
|
|
if ((0, _environment.env)().getBool("DEBUG")) _utilBase.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 now() {
|
|
return (0, _environment.env)().platform.now();
|
|
}
|
|
function fetch(path, requestInits) {
|
|
return (0, _environment.env)().platform.fetch(path, requestInits);
|
|
}
|
|
function encodeString(s, encoding = "utf-8") {
|
|
encoding = encoding || "utf-8";
|
|
return (0, _environment.env)().platform.encode(s, encoding);
|
|
}
|
|
function decodeString(bytes, encoding = "utf-8") {
|
|
encoding = encoding || "utf-8";
|
|
return (0, _environment.env)().platform.decode(bytes, encoding);
|
|
}
|
|
function isTypedArray(a) {
|
|
// TODO(mattsoulanille): Remove this fallback in 5.0.0
|
|
if ((0, _environment.env)().platform.isTypedArray != null) return (0, _environment.env)().platform.isTypedArray(a);
|
|
else return (0, _isTypedArrayBrowser.isTypedArrayBrowser)(a);
|
|
}
|
|
function flatten(arr, result = [], skipTypedArray = false) {
|
|
if (result == null) result = [];
|
|
if (typeof arr === "boolean" || typeof arr === "number" || typeof arr === "string" || _utilBase.isPromise(arr) || arr == null || isTypedArray(arr) && skipTypedArray) result.push(arr);
|
|
else if (Array.isArray(arr) || isTypedArray(arr)) for(let i = 0; i < arr.length; ++i)flatten(arr[i], result, skipTypedArray);
|
|
else {
|
|
let maxIndex = -1;
|
|
for (const key of Object.keys(arr))// 0 or positive integer.
|
|
if (/^([1-9]+[0-9]*|0)$/.test(key)) maxIndex = Math.max(maxIndex, Number(key));
|
|
for(let i = 0; i <= maxIndex; i++)// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
flatten(arr[i], result, skipTypedArray);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
},{"./environment":"dXmHm","./platforms/is_typed_array_browser":"cjcvP","./util_base":"4Vo4a","./hash_util":"jaKDR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cjcvP":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isTypedArrayBrowser", ()=>isTypedArrayBrowser);
|
|
function isTypedArrayBrowser(a) {
|
|
return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array || a instanceof Uint8ClampedArray;
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jaKDR":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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.
|
|
* =============================================================================
|
|
*/ // Workaround for allowing cjs module to be included in bundle created by
|
|
// rollup.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "hexToLong", ()=>hexToLong);
|
|
parcelHelpers.export(exports, "fingerPrint64", ()=>fingerPrint64);
|
|
var _long = require("long");
|
|
// tslint:disable-next-line
|
|
const Long = // tslint:disable-next-line
|
|
_long.default || _long;
|
|
function hexToLong(hex) {
|
|
return Long.fromString(hex, true, 16);
|
|
}
|
|
// Some primes between 2^63 and 2^64 for various uses.
|
|
// Hex 0xc3a5c85c97cb3127
|
|
const k0 = hexToLong("c3a5c85c97cb3127");
|
|
// Hex 0xb492b66fbe98f273
|
|
const k1 = hexToLong("b492b66fbe98f273");
|
|
// Hex 0x9ae16a3b2f90404f
|
|
const k2 = hexToLong("9ae16a3b2f90404f");
|
|
function shiftMix(val) {
|
|
return val.xor(val.shru(47));
|
|
}
|
|
function fetch(s, offset, numBytes) {
|
|
const bytes = s.slice(offset, offset + numBytes);
|
|
return Long.fromBytes(Array.from(bytes), true, true);
|
|
}
|
|
function fetch64(s, offset) {
|
|
return fetch(s, offset, 8);
|
|
}
|
|
function fetch32(s, offset) {
|
|
return fetch(s, offset, 4);
|
|
}
|
|
function rotate64(val, shift) {
|
|
// Avoid shifting by 64: doing so yields an undefined result.
|
|
return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));
|
|
}
|
|
function hashLen16(u, v, mul = hexToLong("9ddfea08eb382d69")) {
|
|
// Murmur-inspired hashing.
|
|
let a = u.xor(v).mul(mul);
|
|
a = a.xor(a.shru(47));
|
|
let b = v.xor(a).mul(mul);
|
|
b = b.xor(b.shru(47));
|
|
b = b.mul(mul);
|
|
return b;
|
|
}
|
|
// Return a 16-byte hash for 48 bytes. Quick and dirty.
|
|
// Callers do best to use "random-looking" values for a and b.
|
|
function weakHashLen32WithSeeds(w, x, y, z, a, b) {
|
|
a = a.add(w);
|
|
b = rotate64(b.add(a).add(z), 21);
|
|
const c = a;
|
|
a = a.add(x);
|
|
a = a.add(y);
|
|
b = b.add(rotate64(a, 44));
|
|
return [
|
|
a.add(z),
|
|
b.add(c)
|
|
];
|
|
}
|
|
function weakHashLen32WithSeedsStr(s, offset, a, b) {
|
|
return weakHashLen32WithSeeds(fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16), fetch64(s, offset + 24), a, b);
|
|
}
|
|
function hashLen0to16(s, len = s.length) {
|
|
if (len >= 8) {
|
|
const mul = k2.add(len * 2);
|
|
const a = fetch64(s, 0).add(k2);
|
|
const b = fetch64(s, len - 8);
|
|
const c = rotate64(b, 37).mul(mul).add(a);
|
|
const d = rotate64(a, 25).add(b).mul(mul);
|
|
return hashLen16(c, d, mul);
|
|
}
|
|
if (len >= 4) {
|
|
const mul = k2.add(len * 2);
|
|
const a = fetch32(s, 0);
|
|
return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul);
|
|
}
|
|
if (len > 0) {
|
|
const a = s[0];
|
|
const b = s[len >> 1];
|
|
const c = s[len - 1];
|
|
const y = a + (b << 8);
|
|
const z = len + (c << 2);
|
|
return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);
|
|
}
|
|
return k2;
|
|
}
|
|
function hashLen17to32(s, len = s.length) {
|
|
const mul = k2.add(len * 2);
|
|
const a = fetch64(s, 0).mul(k1);
|
|
const b = fetch64(s, 8);
|
|
const c = fetch64(s, len - 8).mul(mul);
|
|
const d = fetch64(s, len - 16).mul(k2);
|
|
return hashLen16(rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d), a.add(rotate64(b.add(k2), 18)).add(c), mul);
|
|
}
|
|
function hashLen33to64(s, len = s.length) {
|
|
const mul = k2.add(len * 2);
|
|
const a = fetch64(s, 0).mul(k2);
|
|
const b = fetch64(s, 8);
|
|
const c = fetch64(s, len - 8).mul(mul);
|
|
const d = fetch64(s, len - 16).mul(k2);
|
|
const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);
|
|
const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul);
|
|
const e = fetch64(s, 16).mul(mul);
|
|
const f = fetch64(s, 24);
|
|
const g = y.add(fetch64(s, len - 32)).mul(mul);
|
|
const h = z.add(fetch64(s, len - 24)).mul(mul);
|
|
return hashLen16(rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h), e.add(rotate64(f.add(a), 18)).add(g), mul);
|
|
}
|
|
function fingerPrint64(s, len = s.length) {
|
|
const seed = Long.fromNumber(81, true);
|
|
if (len <= 32) {
|
|
if (len <= 16) return hashLen0to16(s, len);
|
|
else return hashLen17to32(s, len);
|
|
} else if (len <= 64) return hashLen33to64(s, len);
|
|
// For strings over 64 bytes we loop. Internal state consists of
|
|
// 56 bytes: v, w, x, y, and z.
|
|
let x = seed;
|
|
let y = seed.mul(k1).add(113);
|
|
let z = shiftMix(y.mul(k2).add(113)).mul(k2);
|
|
let v = [
|
|
Long.UZERO,
|
|
Long.UZERO
|
|
];
|
|
let w = [
|
|
Long.UZERO,
|
|
Long.UZERO
|
|
];
|
|
x = x.mul(k2).add(fetch64(s, 0));
|
|
let offset = 0;
|
|
// Set end so that after the loop we have 1 to 64 bytes left to process.
|
|
const end = (len - 1 >> 6) * 64;
|
|
const last64 = end + (len - 1 & 63) - 63;
|
|
do {
|
|
x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);
|
|
y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);
|
|
x = x.xor(w[1]);
|
|
y = y.add(v[0]).add(fetch64(s, offset + 40));
|
|
z = rotate64(z.add(w[0]), 33).mul(k1);
|
|
v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));
|
|
w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));
|
|
[z, x] = [
|
|
x,
|
|
z
|
|
];
|
|
offset += 64;
|
|
}while (offset !== end);
|
|
const mul = k1.add(z.and(0xff).shl(1));
|
|
// Point to the last 64 bytes of input.
|
|
offset = last64;
|
|
w[0] = w[0].add(len - 1 & 63);
|
|
v[0] = v[0].add(w[0]);
|
|
w[0] = w[0].add(v[0]);
|
|
x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul);
|
|
y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul);
|
|
x = x.xor(w[1].mul(9));
|
|
y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));
|
|
z = rotate64(z.add(w[0]), 33).mul(mul);
|
|
v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul), x.add(w[0]));
|
|
w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));
|
|
[z, x] = [
|
|
x,
|
|
z
|
|
];
|
|
return hashLen16(hashLen16(v[0], w[0], mul).add(shiftMix(y).mul(k0)).add(z), hashLen16(v[1], w[1], mul).add(x), mul);
|
|
}
|
|
|
|
},{"long":"2goS4","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2goS4":[function(require,module,exports) {
|
|
module.exports = Long;
|
|
/**
|
|
* wasm optimizations, to do native i64 multiplication and divide
|
|
*/ var wasm = null;
|
|
try {
|
|
wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
|
|
0,
|
|
97,
|
|
115,
|
|
109,
|
|
1,
|
|
0,
|
|
0,
|
|
0,
|
|
1,
|
|
13,
|
|
2,
|
|
96,
|
|
0,
|
|
1,
|
|
127,
|
|
96,
|
|
4,
|
|
127,
|
|
127,
|
|
127,
|
|
127,
|
|
1,
|
|
127,
|
|
3,
|
|
7,
|
|
6,
|
|
0,
|
|
1,
|
|
1,
|
|
1,
|
|
1,
|
|
1,
|
|
6,
|
|
6,
|
|
1,
|
|
127,
|
|
1,
|
|
65,
|
|
0,
|
|
11,
|
|
7,
|
|
50,
|
|
6,
|
|
3,
|
|
109,
|
|
117,
|
|
108,
|
|
0,
|
|
1,
|
|
5,
|
|
100,
|
|
105,
|
|
118,
|
|
95,
|
|
115,
|
|
0,
|
|
2,
|
|
5,
|
|
100,
|
|
105,
|
|
118,
|
|
95,
|
|
117,
|
|
0,
|
|
3,
|
|
5,
|
|
114,
|
|
101,
|
|
109,
|
|
95,
|
|
115,
|
|
0,
|
|
4,
|
|
5,
|
|
114,
|
|
101,
|
|
109,
|
|
95,
|
|
117,
|
|
0,
|
|
5,
|
|
8,
|
|
103,
|
|
101,
|
|
116,
|
|
95,
|
|
104,
|
|
105,
|
|
103,
|
|
104,
|
|
0,
|
|
0,
|
|
10,
|
|
191,
|
|
1,
|
|
6,
|
|
4,
|
|
0,
|
|
35,
|
|
0,
|
|
11,
|
|
36,
|
|
1,
|
|
1,
|
|
126,
|
|
32,
|
|
0,
|
|
173,
|
|
32,
|
|
1,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
32,
|
|
2,
|
|
173,
|
|
32,
|
|
3,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
126,
|
|
34,
|
|
4,
|
|
66,
|
|
32,
|
|
135,
|
|
167,
|
|
36,
|
|
0,
|
|
32,
|
|
4,
|
|
167,
|
|
11,
|
|
36,
|
|
1,
|
|
1,
|
|
126,
|
|
32,
|
|
0,
|
|
173,
|
|
32,
|
|
1,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
32,
|
|
2,
|
|
173,
|
|
32,
|
|
3,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
127,
|
|
34,
|
|
4,
|
|
66,
|
|
32,
|
|
135,
|
|
167,
|
|
36,
|
|
0,
|
|
32,
|
|
4,
|
|
167,
|
|
11,
|
|
36,
|
|
1,
|
|
1,
|
|
126,
|
|
32,
|
|
0,
|
|
173,
|
|
32,
|
|
1,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
32,
|
|
2,
|
|
173,
|
|
32,
|
|
3,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
128,
|
|
34,
|
|
4,
|
|
66,
|
|
32,
|
|
135,
|
|
167,
|
|
36,
|
|
0,
|
|
32,
|
|
4,
|
|
167,
|
|
11,
|
|
36,
|
|
1,
|
|
1,
|
|
126,
|
|
32,
|
|
0,
|
|
173,
|
|
32,
|
|
1,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
32,
|
|
2,
|
|
173,
|
|
32,
|
|
3,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
129,
|
|
34,
|
|
4,
|
|
66,
|
|
32,
|
|
135,
|
|
167,
|
|
36,
|
|
0,
|
|
32,
|
|
4,
|
|
167,
|
|
11,
|
|
36,
|
|
1,
|
|
1,
|
|
126,
|
|
32,
|
|
0,
|
|
173,
|
|
32,
|
|
1,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
32,
|
|
2,
|
|
173,
|
|
32,
|
|
3,
|
|
173,
|
|
66,
|
|
32,
|
|
134,
|
|
132,
|
|
130,
|
|
34,
|
|
4,
|
|
66,
|
|
32,
|
|
135,
|
|
167,
|
|
36,
|
|
0,
|
|
32,
|
|
4,
|
|
167,
|
|
11
|
|
])), {}).exports;
|
|
} catch (e) {
|
|
// no wasm support :(
|
|
}
|
|
/**
|
|
* Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
|
|
* See the from* functions below for more convenient ways of constructing Longs.
|
|
* @exports Long
|
|
* @class A Long class for representing a 64 bit two's-complement integer value.
|
|
* @param {number} low The low (signed) 32 bits of the long
|
|
* @param {number} high The high (signed) 32 bits of the long
|
|
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
|
|
* @constructor
|
|
*/ function Long(low, high, unsigned) {
|
|
/**
|
|
* The low 32 bits as a signed value.
|
|
* @type {number}
|
|
*/ this.low = low | 0;
|
|
/**
|
|
* The high 32 bits as a signed value.
|
|
* @type {number}
|
|
*/ this.high = high | 0;
|
|
/**
|
|
* Whether unsigned or not.
|
|
* @type {boolean}
|
|
*/ this.unsigned = !!unsigned;
|
|
}
|
|
// The internal representation of a long is the two given signed, 32-bit values.
|
|
// We use 32-bit pieces because these are the size of integers on which
|
|
// Javascript performs bit-operations. For operations like addition and
|
|
// multiplication, we split each number into 16 bit pieces, which can easily be
|
|
// multiplied within Javascript's floating-point representation without overflow
|
|
// or change in sign.
|
|
//
|
|
// In the algorithms below, we frequently reduce the negative case to the
|
|
// positive case by negating the input(s) and then post-processing the result.
|
|
// Note that we must ALWAYS check specially whether those values are MIN_VALUE
|
|
// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
|
|
// a positive number, it overflows back into a negative). Not handling this
|
|
// case would often result in infinite recursion.
|
|
//
|
|
// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
|
|
// methods on which they depend.
|
|
/**
|
|
* An indicator used to reliably determine if an object is a Long or not.
|
|
* @type {boolean}
|
|
* @const
|
|
* @private
|
|
*/ Long.prototype.__isLong__;
|
|
Object.defineProperty(Long.prototype, "__isLong__", {
|
|
value: true
|
|
});
|
|
/**
|
|
* @function
|
|
* @param {*} obj Object
|
|
* @returns {boolean}
|
|
* @inner
|
|
*/ function isLong(obj) {
|
|
return (obj && obj["__isLong__"]) === true;
|
|
}
|
|
/**
|
|
* Tests if the specified object is a Long.
|
|
* @function
|
|
* @param {*} obj Object
|
|
* @returns {boolean}
|
|
*/ Long.isLong = isLong;
|
|
/**
|
|
* A cache of the Long representations of small integer values.
|
|
* @type {!Object}
|
|
* @inner
|
|
*/ var INT_CACHE = {};
|
|
/**
|
|
* A cache of the Long representations of small unsigned integer values.
|
|
* @type {!Object}
|
|
* @inner
|
|
*/ var UINT_CACHE = {};
|
|
/**
|
|
* @param {number} value
|
|
* @param {boolean=} unsigned
|
|
* @returns {!Long}
|
|
* @inner
|
|
*/ function fromInt(value, unsigned) {
|
|
var obj, cachedObj, cache;
|
|
if (unsigned) {
|
|
value >>>= 0;
|
|
if (cache = 0 <= value && value < 256) {
|
|
cachedObj = UINT_CACHE[value];
|
|
if (cachedObj) return cachedObj;
|
|
}
|
|
obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
|
|
if (cache) UINT_CACHE[value] = obj;
|
|
return obj;
|
|
} else {
|
|
value |= 0;
|
|
if (cache = -128 <= value && value < 128) {
|
|
cachedObj = INT_CACHE[value];
|
|
if (cachedObj) return cachedObj;
|
|
}
|
|
obj = fromBits(value, value < 0 ? -1 : 0, false);
|
|
if (cache) INT_CACHE[value] = obj;
|
|
return obj;
|
|
}
|
|
}
|
|
/**
|
|
* Returns a Long representing the given 32 bit integer value.
|
|
* @function
|
|
* @param {number} value The 32 bit integer in question
|
|
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
|
|
* @returns {!Long} The corresponding Long value
|
|
*/ Long.fromInt = fromInt;
|
|
/**
|
|
* @param {number} value
|
|
* @param {boolean=} unsigned
|
|
* @returns {!Long}
|
|
* @inner
|
|
*/ function fromNumber(value, unsigned) {
|
|
if (isNaN(value)) return unsigned ? UZERO : ZERO;
|
|
if (unsigned) {
|
|
if (value < 0) return UZERO;
|
|
if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;
|
|
} else {
|
|
if (value <= -TWO_PWR_63_DBL) return MIN_VALUE;
|
|
if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE;
|
|
}
|
|
if (value < 0) return fromNumber(-value, unsigned).neg();
|
|
return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
|
|
}
|
|
/**
|
|
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
|
|
* @function
|
|
* @param {number} value The number in question
|
|
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
|
|
* @returns {!Long} The corresponding Long value
|
|
*/ Long.fromNumber = fromNumber;
|
|
/**
|
|
* @param {number} lowBits
|
|
* @param {number} highBits
|
|
* @param {boolean=} unsigned
|
|
* @returns {!Long}
|
|
* @inner
|
|
*/ function fromBits(lowBits, highBits, unsigned) {
|
|
return new Long(lowBits, highBits, unsigned);
|
|
}
|
|
/**
|
|
* Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
|
|
* assumed to use 32 bits.
|
|
* @function
|
|
* @param {number} lowBits The low 32 bits
|
|
* @param {number} highBits The high 32 bits
|
|
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
|
|
* @returns {!Long} The corresponding Long value
|
|
*/ Long.fromBits = fromBits;
|
|
/**
|
|
* @function
|
|
* @param {number} base
|
|
* @param {number} exponent
|
|
* @returns {number}
|
|
* @inner
|
|
*/ var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
|
|
/**
|
|
* @param {string} str
|
|
* @param {(boolean|number)=} unsigned
|
|
* @param {number=} radix
|
|
* @returns {!Long}
|
|
* @inner
|
|
*/ function fromString(str, unsigned, radix) {
|
|
if (str.length === 0) throw Error("empty string");
|
|
if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") return ZERO;
|
|
if (typeof unsigned === "number") // For goog.math.long compatibility
|
|
radix = unsigned, unsigned = false;
|
|
else unsigned = !!unsigned;
|
|
radix = radix || 10;
|
|
if (radix < 2 || 36 < radix) throw RangeError("radix");
|
|
var p;
|
|
if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen");
|
|
else if (p === 0) return fromString(str.substring(1), unsigned, radix).neg();
|
|
// Do several (8) digits each time through the loop, so as to
|
|
// minimize the calls to the very expensive emulated div.
|
|
var radixToPower = fromNumber(pow_dbl(radix, 8));
|
|
var result = ZERO;
|
|
for(var i = 0; i < str.length; i += 8){
|
|
var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
|
|
if (size < 8) {
|
|
var power = fromNumber(pow_dbl(radix, size));
|
|
result = result.mul(power).add(fromNumber(value));
|
|
} else {
|
|
result = result.mul(radixToPower);
|
|
result = result.add(fromNumber(value));
|
|
}
|
|
}
|
|
result.unsigned = unsigned;
|
|
return result;
|
|
}
|
|
/**
|
|
* Returns a Long representation of the given string, written using the specified radix.
|
|
* @function
|
|
* @param {string} str The textual representation of the Long
|
|
* @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed
|
|
* @param {number=} radix The radix in which the text is written (2-36), defaults to 10
|
|
* @returns {!Long} The corresponding Long value
|
|
*/ Long.fromString = fromString;
|
|
/**
|
|
* @function
|
|
* @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
|
|
* @param {boolean=} unsigned
|
|
* @returns {!Long}
|
|
* @inner
|
|
*/ function fromValue(val, unsigned) {
|
|
if (typeof val === "number") return fromNumber(val, unsigned);
|
|
if (typeof val === "string") return fromString(val, unsigned);
|
|
// Throws for non-objects, converts non-instanceof Long:
|
|
return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
|
|
}
|
|
/**
|
|
* Converts the specified value to a Long using the appropriate from* function for its type.
|
|
* @function
|
|
* @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
|
|
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
|
|
* @returns {!Long}
|
|
*/ Long.fromValue = fromValue;
|
|
// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
|
|
// no runtime penalty for these.
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var TWO_PWR_16_DBL = 65536;
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var TWO_PWR_24_DBL = 16777216;
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
|
|
/**
|
|
* @type {number}
|
|
* @const
|
|
* @inner
|
|
*/ var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
|
|
/**
|
|
* @type {!Long}
|
|
* @const
|
|
* @inner
|
|
*/ var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
|
|
/**
|
|
* @type {!Long}
|
|
* @inner
|
|
*/ var ZERO = fromInt(0);
|
|
/**
|
|
* Signed zero.
|
|
* @type {!Long}
|
|
*/ Long.ZERO = ZERO;
|
|
/**
|
|
* @type {!Long}
|
|
* @inner
|
|
*/ var UZERO = fromInt(0, true);
|
|
/**
|
|
* Unsigned zero.
|
|
* @type {!Long}
|
|
*/ Long.UZERO = UZERO;
|
|
/**
|
|
* @type {!Long}
|
|
* @inner
|
|
*/ var ONE = fromInt(1);
|
|
/**
|
|
* Signed one.
|
|
* @type {!Long}
|
|
*/ Long.ONE = ONE;
|
|
/**
|
|
* @type {!Long}
|
|
* @inner
|
|
*/ var UONE = fromInt(1, true);
|
|
/**
|
|
* Unsigned one.
|
|
* @type {!Long}
|
|
*/ Long.UONE = UONE;
|
|
/**
|
|
* @type {!Long}
|
|
* @inner
|
|
*/ var NEG_ONE = fromInt(-1);
|
|
/**
|
|
* Signed negative one.
|
|
* @type {!Long}
|
|
*/ Long.NEG_ONE = NEG_ONE;
|
|
/**
|
|
* @type {!Long}
|
|
* @inner
|
|
*/ var MAX_VALUE = fromBits(-1, 2147483647, false);
|
|
/**
|
|
* Maximum signed value.
|
|
* @type {!Long}
|
|
*/ Long.MAX_VALUE = MAX_VALUE;
|
|
/**
|
|
* @type {!Long}
|
|
* @inner
|
|
*/ var MAX_UNSIGNED_VALUE = fromBits(-1, -1, true);
|
|
/**
|
|
* Maximum unsigned value.
|
|
* @type {!Long}
|
|
*/ Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
|
|
/**
|
|
* @type {!Long}
|
|
* @inner
|
|
*/ var MIN_VALUE = fromBits(0, -2147483648, false);
|
|
/**
|
|
* Minimum signed value.
|
|
* @type {!Long}
|
|
*/ Long.MIN_VALUE = MIN_VALUE;
|
|
/**
|
|
* @alias Long.prototype
|
|
* @inner
|
|
*/ var LongPrototype = Long.prototype;
|
|
/**
|
|
* Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
|
|
* @returns {number}
|
|
*/ LongPrototype.toInt = function toInt() {
|
|
return this.unsigned ? this.low >>> 0 : this.low;
|
|
};
|
|
/**
|
|
* Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
|
|
* @returns {number}
|
|
*/ LongPrototype.toNumber = function toNumber() {
|
|
if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
|
|
return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
|
|
};
|
|
/**
|
|
* Converts the Long to a string written in the specified radix.
|
|
* @param {number=} radix Radix (2-36), defaults to 10
|
|
* @returns {string}
|
|
* @override
|
|
* @throws {RangeError} If `radix` is out of range
|
|
*/ LongPrototype.toString = function toString(radix) {
|
|
radix = radix || 10;
|
|
if (radix < 2 || 36 < radix) throw RangeError("radix");
|
|
if (this.isZero()) return "0";
|
|
if (this.isNegative()) {
|
|
if (this.eq(MIN_VALUE)) {
|
|
// We need to change the Long value before it can be negated, so we remove
|
|
// the bottom-most digit in this base and then recurse to do the rest.
|
|
var radixLong = fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
|
|
return div.toString(radix) + rem1.toInt().toString(radix);
|
|
} else return "-" + this.neg().toString(radix);
|
|
}
|
|
// Do several (6) digits each time through the loop, so as to
|
|
// minimize the calls to the very expensive emulated div.
|
|
var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this;
|
|
var result = "";
|
|
while(true){
|
|
var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix);
|
|
rem = remDiv;
|
|
if (rem.isZero()) return digits + result;
|
|
else {
|
|
while(digits.length < 6)digits = "0" + digits;
|
|
result = "" + digits + result;
|
|
}
|
|
}
|
|
};
|
|
/**
|
|
* Gets the high 32 bits as a signed integer.
|
|
* @returns {number} Signed high bits
|
|
*/ LongPrototype.getHighBits = function getHighBits() {
|
|
return this.high;
|
|
};
|
|
/**
|
|
* Gets the high 32 bits as an unsigned integer.
|
|
* @returns {number} Unsigned high bits
|
|
*/ LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
|
|
return this.high >>> 0;
|
|
};
|
|
/**
|
|
* Gets the low 32 bits as a signed integer.
|
|
* @returns {number} Signed low bits
|
|
*/ LongPrototype.getLowBits = function getLowBits() {
|
|
return this.low;
|
|
};
|
|
/**
|
|
* Gets the low 32 bits as an unsigned integer.
|
|
* @returns {number} Unsigned low bits
|
|
*/ LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
|
|
return this.low >>> 0;
|
|
};
|
|
/**
|
|
* Gets the number of bits needed to represent the absolute value of this Long.
|
|
* @returns {number}
|
|
*/ LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
|
|
if (this.isNegative()) return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
|
|
var val = this.high != 0 ? this.high : this.low;
|
|
for(var bit = 31; bit > 0; bit--)if ((val & 1 << bit) != 0) break;
|
|
return this.high != 0 ? bit + 33 : bit + 1;
|
|
};
|
|
/**
|
|
* Tests if this Long's value equals zero.
|
|
* @returns {boolean}
|
|
*/ LongPrototype.isZero = function isZero() {
|
|
return this.high === 0 && this.low === 0;
|
|
};
|
|
/**
|
|
* Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.
|
|
* @returns {boolean}
|
|
*/ LongPrototype.eqz = LongPrototype.isZero;
|
|
/**
|
|
* Tests if this Long's value is negative.
|
|
* @returns {boolean}
|
|
*/ LongPrototype.isNegative = function isNegative() {
|
|
return !this.unsigned && this.high < 0;
|
|
};
|
|
/**
|
|
* Tests if this Long's value is positive.
|
|
* @returns {boolean}
|
|
*/ LongPrototype.isPositive = function isPositive() {
|
|
return this.unsigned || this.high >= 0;
|
|
};
|
|
/**
|
|
* Tests if this Long's value is odd.
|
|
* @returns {boolean}
|
|
*/ LongPrototype.isOdd = function isOdd() {
|
|
return (this.low & 1) === 1;
|
|
};
|
|
/**
|
|
* Tests if this Long's value is even.
|
|
* @returns {boolean}
|
|
*/ LongPrototype.isEven = function isEven() {
|
|
return (this.low & 1) === 0;
|
|
};
|
|
/**
|
|
* Tests if this Long's value equals the specified's.
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.equals = function equals(other) {
|
|
if (!isLong(other)) other = fromValue(other);
|
|
if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) return false;
|
|
return this.high === other.high && this.low === other.low;
|
|
};
|
|
/**
|
|
* Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.eq = LongPrototype.equals;
|
|
/**
|
|
* Tests if this Long's value differs from the specified's.
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.notEquals = function notEquals(other) {
|
|
return !this.eq(/* validates */ other);
|
|
};
|
|
/**
|
|
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.neq = LongPrototype.notEquals;
|
|
/**
|
|
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.ne = LongPrototype.notEquals;
|
|
/**
|
|
* Tests if this Long's value is less than the specified's.
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.lessThan = function lessThan(other) {
|
|
return this.comp(/* validates */ other) < 0;
|
|
};
|
|
/**
|
|
* Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.lt = LongPrototype.lessThan;
|
|
/**
|
|
* Tests if this Long's value is less than or equal the specified's.
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
|
|
return this.comp(/* validates */ other) <= 0;
|
|
};
|
|
/**
|
|
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.lte = LongPrototype.lessThanOrEqual;
|
|
/**
|
|
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.le = LongPrototype.lessThanOrEqual;
|
|
/**
|
|
* Tests if this Long's value is greater than the specified's.
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.greaterThan = function greaterThan(other) {
|
|
return this.comp(/* validates */ other) > 0;
|
|
};
|
|
/**
|
|
* Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.gt = LongPrototype.greaterThan;
|
|
/**
|
|
* Tests if this Long's value is greater than or equal the specified's.
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
|
|
return this.comp(/* validates */ other) >= 0;
|
|
};
|
|
/**
|
|
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.gte = LongPrototype.greaterThanOrEqual;
|
|
/**
|
|
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {boolean}
|
|
*/ LongPrototype.ge = LongPrototype.greaterThanOrEqual;
|
|
/**
|
|
* Compares this Long's value with the specified's.
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
|
|
* if the given one is greater
|
|
*/ LongPrototype.compare = function compare(other) {
|
|
if (!isLong(other)) other = fromValue(other);
|
|
if (this.eq(other)) return 0;
|
|
var thisNeg = this.isNegative(), otherNeg = other.isNegative();
|
|
if (thisNeg && !otherNeg) return -1;
|
|
if (!thisNeg && otherNeg) return 1;
|
|
// At this point the sign bits are the same
|
|
if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1;
|
|
// Both are positive if at least one is unsigned
|
|
return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
|
|
};
|
|
/**
|
|
* Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
|
|
* @function
|
|
* @param {!Long|number|string} other Other value
|
|
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
|
|
* if the given one is greater
|
|
*/ LongPrototype.comp = LongPrototype.compare;
|
|
/**
|
|
* Negates this Long's value.
|
|
* @returns {!Long} Negated Long
|
|
*/ LongPrototype.negate = function negate() {
|
|
if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE;
|
|
return this.not().add(ONE);
|
|
};
|
|
/**
|
|
* Negates this Long's value. This is an alias of {@link Long#negate}.
|
|
* @function
|
|
* @returns {!Long} Negated Long
|
|
*/ LongPrototype.neg = LongPrototype.negate;
|
|
/**
|
|
* Returns the sum of this and the specified Long.
|
|
* @param {!Long|number|string} addend Addend
|
|
* @returns {!Long} Sum
|
|
*/ LongPrototype.add = function add(addend) {
|
|
if (!isLong(addend)) addend = fromValue(addend);
|
|
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
|
|
var a48 = this.high >>> 16;
|
|
var a32 = this.high & 0xFFFF;
|
|
var a16 = this.low >>> 16;
|
|
var a00 = this.low & 0xFFFF;
|
|
var b48 = addend.high >>> 16;
|
|
var b32 = addend.high & 0xFFFF;
|
|
var b16 = addend.low >>> 16;
|
|
var b00 = addend.low & 0xFFFF;
|
|
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
|
|
c00 += a00 + b00;
|
|
c16 += c00 >>> 16;
|
|
c00 &= 0xFFFF;
|
|
c16 += a16 + b16;
|
|
c32 += c16 >>> 16;
|
|
c16 &= 0xFFFF;
|
|
c32 += a32 + b32;
|
|
c48 += c32 >>> 16;
|
|
c32 &= 0xFFFF;
|
|
c48 += a48 + b48;
|
|
c48 &= 0xFFFF;
|
|
return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
|
|
};
|
|
/**
|
|
* Returns the difference of this and the specified Long.
|
|
* @param {!Long|number|string} subtrahend Subtrahend
|
|
* @returns {!Long} Difference
|
|
*/ LongPrototype.subtract = function subtract(subtrahend) {
|
|
if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend);
|
|
return this.add(subtrahend.neg());
|
|
};
|
|
/**
|
|
* Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
|
|
* @function
|
|
* @param {!Long|number|string} subtrahend Subtrahend
|
|
* @returns {!Long} Difference
|
|
*/ LongPrototype.sub = LongPrototype.subtract;
|
|
/**
|
|
* Returns the product of this and the specified Long.
|
|
* @param {!Long|number|string} multiplier Multiplier
|
|
* @returns {!Long} Product
|
|
*/ LongPrototype.multiply = function multiply(multiplier) {
|
|
if (this.isZero()) return ZERO;
|
|
if (!isLong(multiplier)) multiplier = fromValue(multiplier);
|
|
// use wasm support if present
|
|
if (wasm) {
|
|
var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
|
|
return fromBits(low, wasm.get_high(), this.unsigned);
|
|
}
|
|
if (multiplier.isZero()) return ZERO;
|
|
if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO;
|
|
if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO;
|
|
if (this.isNegative()) {
|
|
if (multiplier.isNegative()) return this.neg().mul(multiplier.neg());
|
|
else return this.neg().mul(multiplier).neg();
|
|
} else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg();
|
|
// If both longs are small, use float multiplication
|
|
if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
|
|
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
|
|
// We can skip products that would overflow.
|
|
var a48 = this.high >>> 16;
|
|
var a32 = this.high & 0xFFFF;
|
|
var a16 = this.low >>> 16;
|
|
var a00 = this.low & 0xFFFF;
|
|
var b48 = multiplier.high >>> 16;
|
|
var b32 = multiplier.high & 0xFFFF;
|
|
var b16 = multiplier.low >>> 16;
|
|
var b00 = multiplier.low & 0xFFFF;
|
|
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
|
|
c00 += a00 * b00;
|
|
c16 += c00 >>> 16;
|
|
c00 &= 0xFFFF;
|
|
c16 += a16 * b00;
|
|
c32 += c16 >>> 16;
|
|
c16 &= 0xFFFF;
|
|
c16 += a00 * b16;
|
|
c32 += c16 >>> 16;
|
|
c16 &= 0xFFFF;
|
|
c32 += a32 * b00;
|
|
c48 += c32 >>> 16;
|
|
c32 &= 0xFFFF;
|
|
c32 += a16 * b16;
|
|
c48 += c32 >>> 16;
|
|
c32 &= 0xFFFF;
|
|
c32 += a00 * b32;
|
|
c48 += c32 >>> 16;
|
|
c32 &= 0xFFFF;
|
|
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
|
|
c48 &= 0xFFFF;
|
|
return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
|
|
};
|
|
/**
|
|
* Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
|
|
* @function
|
|
* @param {!Long|number|string} multiplier Multiplier
|
|
* @returns {!Long} Product
|
|
*/ LongPrototype.mul = LongPrototype.multiply;
|
|
/**
|
|
* Returns this Long divided by the specified. The result is signed if this Long is signed or
|
|
* unsigned if this Long is unsigned.
|
|
* @param {!Long|number|string} divisor Divisor
|
|
* @returns {!Long} Quotient
|
|
*/ LongPrototype.divide = function divide(divisor) {
|
|
if (!isLong(divisor)) divisor = fromValue(divisor);
|
|
if (divisor.isZero()) throw Error("division by zero");
|
|
// use wasm support if present
|
|
if (wasm) {
|
|
// guard against signed division overflow: the largest
|
|
// negative number / -1 would be 1 larger than the largest
|
|
// positive number, due to two's complement.
|
|
if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) // be consistent with non-wasm code path
|
|
return this;
|
|
var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
|
|
return fromBits(low, wasm.get_high(), this.unsigned);
|
|
}
|
|
if (this.isZero()) return this.unsigned ? UZERO : ZERO;
|
|
var approx, rem, res;
|
|
if (!this.unsigned) {
|
|
// This section is only relevant for signed longs and is derived from the
|
|
// closure library as a whole.
|
|
if (this.eq(MIN_VALUE)) {
|
|
if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
|
|
else if (divisor.eq(MIN_VALUE)) return ONE;
|
|
else {
|
|
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
|
|
var halfThis = this.shr(1);
|
|
approx = halfThis.div(divisor).shl(1);
|
|
if (approx.eq(ZERO)) return divisor.isNegative() ? ONE : NEG_ONE;
|
|
else {
|
|
rem = this.sub(divisor.mul(approx));
|
|
res = approx.add(rem.div(divisor));
|
|
return res;
|
|
}
|
|
}
|
|
} else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO;
|
|
if (this.isNegative()) {
|
|
if (divisor.isNegative()) return this.neg().div(divisor.neg());
|
|
return this.neg().div(divisor).neg();
|
|
} else if (divisor.isNegative()) return this.div(divisor.neg()).neg();
|
|
res = ZERO;
|
|
} else {
|
|
// The algorithm below has not been made for unsigned longs. It's therefore
|
|
// required to take special care of the MSB prior to running it.
|
|
if (!divisor.unsigned) divisor = divisor.toUnsigned();
|
|
if (divisor.gt(this)) return UZERO;
|
|
if (divisor.gt(this.shru(1))) return UONE;
|
|
res = UZERO;
|
|
}
|
|
// Repeat the following until the remainder is less than other: find a
|
|
// floating-point that approximates remainder / other *from below*, add this
|
|
// into the result, and subtract it from the remainder. It is critical that
|
|
// the approximate value is less than or equal to the real value so that the
|
|
// remainder never becomes negative.
|
|
rem = this;
|
|
while(rem.gte(divisor)){
|
|
// Approximate the result of division. This may be a little greater or
|
|
// smaller than the actual value.
|
|
approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
|
|
// We will tweak the approximate result by changing it in the 48-th digit or
|
|
// the smallest non-fractional digit, whichever is larger.
|
|
var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), // Decrease the approximation until it is smaller than the remainder. Note
|
|
// that if it is too large, the product overflows and is negative.
|
|
approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor);
|
|
while(approxRem.isNegative() || approxRem.gt(rem)){
|
|
approx -= delta;
|
|
approxRes = fromNumber(approx, this.unsigned);
|
|
approxRem = approxRes.mul(divisor);
|
|
}
|
|
// We know the answer can't be zero... and actually, zero would cause
|
|
// infinite recursion since we would make no progress.
|
|
if (approxRes.isZero()) approxRes = ONE;
|
|
res = res.add(approxRes);
|
|
rem = rem.sub(approxRem);
|
|
}
|
|
return res;
|
|
};
|
|
/**
|
|
* Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
|
|
* @function
|
|
* @param {!Long|number|string} divisor Divisor
|
|
* @returns {!Long} Quotient
|
|
*/ LongPrototype.div = LongPrototype.divide;
|
|
/**
|
|
* Returns this Long modulo the specified.
|
|
* @param {!Long|number|string} divisor Divisor
|
|
* @returns {!Long} Remainder
|
|
*/ LongPrototype.modulo = function modulo(divisor) {
|
|
if (!isLong(divisor)) divisor = fromValue(divisor);
|
|
// use wasm support if present
|
|
if (wasm) {
|
|
var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
|
|
return fromBits(low, wasm.get_high(), this.unsigned);
|
|
}
|
|
return this.sub(this.div(divisor).mul(divisor));
|
|
};
|
|
/**
|
|
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
|
|
* @function
|
|
* @param {!Long|number|string} divisor Divisor
|
|
* @returns {!Long} Remainder
|
|
*/ LongPrototype.mod = LongPrototype.modulo;
|
|
/**
|
|
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
|
|
* @function
|
|
* @param {!Long|number|string} divisor Divisor
|
|
* @returns {!Long} Remainder
|
|
*/ LongPrototype.rem = LongPrototype.modulo;
|
|
/**
|
|
* Returns the bitwise NOT of this Long.
|
|
* @returns {!Long}
|
|
*/ LongPrototype.not = function not() {
|
|
return fromBits(~this.low, ~this.high, this.unsigned);
|
|
};
|
|
/**
|
|
* Returns the bitwise AND of this Long and the specified.
|
|
* @param {!Long|number|string} other Other Long
|
|
* @returns {!Long}
|
|
*/ LongPrototype.and = function and(other) {
|
|
if (!isLong(other)) other = fromValue(other);
|
|
return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
|
|
};
|
|
/**
|
|
* Returns the bitwise OR of this Long and the specified.
|
|
* @param {!Long|number|string} other Other Long
|
|
* @returns {!Long}
|
|
*/ LongPrototype.or = function or(other) {
|
|
if (!isLong(other)) other = fromValue(other);
|
|
return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
|
|
};
|
|
/**
|
|
* Returns the bitwise XOR of this Long and the given one.
|
|
* @param {!Long|number|string} other Other Long
|
|
* @returns {!Long}
|
|
*/ LongPrototype.xor = function xor(other) {
|
|
if (!isLong(other)) other = fromValue(other);
|
|
return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
|
|
};
|
|
/**
|
|
* Returns this Long with bits shifted to the left by the given amount.
|
|
* @param {number|!Long} numBits Number of bits
|
|
* @returns {!Long} Shifted Long
|
|
*/ LongPrototype.shiftLeft = function shiftLeft(numBits) {
|
|
if (isLong(numBits)) numBits = numBits.toInt();
|
|
if ((numBits &= 63) === 0) return this;
|
|
else if (numBits < 32) return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
|
|
else return fromBits(0, this.low << numBits - 32, this.unsigned);
|
|
};
|
|
/**
|
|
* Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
|
|
* @function
|
|
* @param {number|!Long} numBits Number of bits
|
|
* @returns {!Long} Shifted Long
|
|
*/ LongPrototype.shl = LongPrototype.shiftLeft;
|
|
/**
|
|
* Returns this Long with bits arithmetically shifted to the right by the given amount.
|
|
* @param {number|!Long} numBits Number of bits
|
|
* @returns {!Long} Shifted Long
|
|
*/ LongPrototype.shiftRight = function shiftRight(numBits) {
|
|
if (isLong(numBits)) numBits = numBits.toInt();
|
|
if ((numBits &= 63) === 0) return this;
|
|
else if (numBits < 32) return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
|
|
else return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
|
|
};
|
|
/**
|
|
* Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
|
|
* @function
|
|
* @param {number|!Long} numBits Number of bits
|
|
* @returns {!Long} Shifted Long
|
|
*/ LongPrototype.shr = LongPrototype.shiftRight;
|
|
/**
|
|
* Returns this Long with bits logically shifted to the right by the given amount.
|
|
* @param {number|!Long} numBits Number of bits
|
|
* @returns {!Long} Shifted Long
|
|
*/ LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
|
|
if (isLong(numBits)) numBits = numBits.toInt();
|
|
numBits &= 63;
|
|
if (numBits === 0) return this;
|
|
else {
|
|
var high = this.high;
|
|
if (numBits < 32) {
|
|
var low = this.low;
|
|
return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
|
|
} else if (numBits === 32) return fromBits(high, 0, this.unsigned);
|
|
else return fromBits(high >>> numBits - 32, 0, this.unsigned);
|
|
}
|
|
};
|
|
/**
|
|
* Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
|
|
* @function
|
|
* @param {number|!Long} numBits Number of bits
|
|
* @returns {!Long} Shifted Long
|
|
*/ LongPrototype.shru = LongPrototype.shiftRightUnsigned;
|
|
/**
|
|
* Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
|
|
* @function
|
|
* @param {number|!Long} numBits Number of bits
|
|
* @returns {!Long} Shifted Long
|
|
*/ LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
|
|
/**
|
|
* Converts this Long to signed.
|
|
* @returns {!Long} Signed long
|
|
*/ LongPrototype.toSigned = function toSigned() {
|
|
if (!this.unsigned) return this;
|
|
return fromBits(this.low, this.high, false);
|
|
};
|
|
/**
|
|
* Converts this Long to unsigned.
|
|
* @returns {!Long} Unsigned long
|
|
*/ LongPrototype.toUnsigned = function toUnsigned() {
|
|
if (this.unsigned) return this;
|
|
return fromBits(this.low, this.high, true);
|
|
};
|
|
/**
|
|
* Converts this Long to its byte representation.
|
|
* @param {boolean=} le Whether little or big endian, defaults to big endian
|
|
* @returns {!Array.<number>} Byte representation
|
|
*/ LongPrototype.toBytes = function toBytes(le) {
|
|
return le ? this.toBytesLE() : this.toBytesBE();
|
|
};
|
|
/**
|
|
* Converts this Long to its little endian byte representation.
|
|
* @returns {!Array.<number>} Little endian byte representation
|
|
*/ LongPrototype.toBytesLE = function toBytesLE() {
|
|
var hi = this.high, lo = this.low;
|
|
return [
|
|
lo & 0xff,
|
|
lo >>> 8 & 0xff,
|
|
lo >>> 16 & 0xff,
|
|
lo >>> 24,
|
|
hi & 0xff,
|
|
hi >>> 8 & 0xff,
|
|
hi >>> 16 & 0xff,
|
|
hi >>> 24
|
|
];
|
|
};
|
|
/**
|
|
* Converts this Long to its big endian byte representation.
|
|
* @returns {!Array.<number>} Big endian byte representation
|
|
*/ LongPrototype.toBytesBE = function toBytesBE() {
|
|
var hi = this.high, lo = this.low;
|
|
return [
|
|
hi >>> 24,
|
|
hi >>> 16 & 0xff,
|
|
hi >>> 8 & 0xff,
|
|
hi & 0xff,
|
|
lo >>> 24,
|
|
lo >>> 16 & 0xff,
|
|
lo >>> 8 & 0xff,
|
|
lo & 0xff
|
|
];
|
|
};
|
|
/**
|
|
* Creates a Long from its byte representation.
|
|
* @param {!Array.<number>} bytes Byte representation
|
|
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
|
|
* @param {boolean=} le Whether little or big endian, defaults to big endian
|
|
* @returns {Long} The corresponding Long value
|
|
*/ Long.fromBytes = function fromBytes(bytes, unsigned, le) {
|
|
return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
|
|
};
|
|
/**
|
|
* Creates a Long from its little endian byte representation.
|
|
* @param {!Array.<number>} bytes Little endian byte representation
|
|
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
|
|
* @returns {Long} The corresponding Long value
|
|
*/ Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
|
|
return new Long(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned);
|
|
};
|
|
/**
|
|
* Creates a Long from its big endian byte representation.
|
|
* @param {!Array.<number>} bytes Big endian byte representation
|
|
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
|
|
* @returns {Long} The corresponding Long value
|
|
*/ Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
|
|
return new Long(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned);
|
|
};
|
|
|
|
},{}],"cUi5z":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getFilteredNodesXToY", ()=>getFilteredNodesXToY);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "backpropagateGradients", ()=>backpropagateGradients);
|
|
var _util = require("./util");
|
|
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;
|
|
}
|
|
function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy, add) {
|
|
// 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] = add(curGradient, dx);
|
|
curGradient.dispose();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
},{"./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cJNoh":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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.
|
|
* =============================================================================
|
|
*/ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
|
|
/// <reference types="@webgpu/types/dist" />
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "TensorBuffer", ()=>TensorBuffer);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "setTensorTracker", ()=>setTensorTracker);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "setOpHandler", ()=>setOpHandler);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "setDeprecationWarningFn", ()=>setDeprecationWarningFn);
|
|
/**
|
|
* A `tf.Tensor` object represents an immutable, multidimensional array of
|
|
* numbers that has a shape and a data type.
|
|
*
|
|
* For performance reasons, functions that create tensors do not necessarily
|
|
* perform a copy of the data passed to them (e.g. if the data is passed as a
|
|
* `Float32Array`), and changes to the data will change the tensor. This is not
|
|
* a feature and is not supported. To avoid this behavior, use the tensor before
|
|
* changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.
|
|
*
|
|
* See `tf.tensor` for details on how to create a `tf.Tensor`.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Classes'}
|
|
*/ parcelHelpers.export(exports, "Tensor", ()=>Tensor);
|
|
parcelHelpers.export(exports, "getGlobalTensorClass", ()=>getGlobalTensorClass);
|
|
/**
|
|
* A mutable `tf.Tensor`, useful for persisting state, e.g. for training.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Classes'}
|
|
*/ parcelHelpers.export(exports, "Variable", ()=>Variable);
|
|
var _globalUtil = require("./global_util");
|
|
var _tensorFormat = require("./tensor_format");
|
|
var _util = require("./util");
|
|
class 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 = (0, _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;
|
|
function setTensorTracker(fn) {
|
|
trackerFn = fn;
|
|
}
|
|
function setOpHandler(handler) {
|
|
opHandler = handler;
|
|
}
|
|
function setDeprecationWarningFn(fn) {
|
|
deprecationWarningFn = fn;
|
|
}
|
|
class 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 = (0, _util.computeStrides)(shape);
|
|
this.dataId = dataId;
|
|
this.id = id;
|
|
this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
|
|
}
|
|
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 (0, _util.toNestedArray)(this.shape, vals, this.dtype === "complex64");
|
|
}
|
|
/**
|
|
* Returns the tensor data as a nested array. The transfer of data is done
|
|
* synchronously.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Classes'}
|
|
*/ arraySync() {
|
|
return (0, _util.toNestedArray)(this.shape, this.dataSync(), this.dtype === "complex64");
|
|
}
|
|
/**
|
|
* 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;
|
|
}
|
|
/**
|
|
* Copy the tensor's data to a new GPU resource. Comparing to the `dataSync()`
|
|
* and `data()`, this method prevents data from being downloaded to CPU.
|
|
*
|
|
* For WebGL backend, the data will be stored on a densely packed texture.
|
|
* This means that the texture will use the RGBA channels to store value.
|
|
*
|
|
* For WebGPU backend, the data will be stored on a buffer. There is no
|
|
* parameter, so can not use a user-defined size to create the buffer.
|
|
*
|
|
* @param options:
|
|
* For WebGL,
|
|
* - customTexShape: Optional. If set, will use the user defined
|
|
* texture shape to create the texture.
|
|
*
|
|
* @returns For WebGL backend, a GPUData contains the new texture and
|
|
* its information.
|
|
* {
|
|
* tensorRef: The tensor that is associated with this texture,
|
|
* texture: WebGLTexture,
|
|
* texShape: [number, number] // [height, width]
|
|
* }
|
|
*
|
|
* For WebGPU backend, a GPUData contains the new buffer.
|
|
* {
|
|
* tensorRef: The tensor that is associated with this buffer,
|
|
* buffer: GPUBuffer,
|
|
* }
|
|
*
|
|
* Remember to dispose the GPUData after it is used by
|
|
* `res.tensorRef.dispose()`.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Classes'}
|
|
*/ dataToGPU(options) {
|
|
this.throwIfDisposed();
|
|
return trackerFn().readToGPU(this.dataId, options);
|
|
}
|
|
/**
|
|
* 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;
|
|
if (this.kerasMask) this.kerasMask.dispose();
|
|
trackerFn().disposeTensor(this);
|
|
this.isDisposedInternal = true;
|
|
}
|
|
get isDisposed() {
|
|
return this.isDisposedInternal;
|
|
}
|
|
throwIfDisposed() {
|
|
if (this.isDisposed) throw new Error(`Tensor is disposed.`);
|
|
}
|
|
/**
|
|
* 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);
|
|
}
|
|
/**
|
|
* 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 (0, _tensorFormat.tensorToString)(vals, this.shape, this.dtype, verbose);
|
|
}
|
|
cast(dtype) {
|
|
this.throwIfDisposed();
|
|
return opHandler.cast(this, dtype);
|
|
}
|
|
variable(trainable = true, name, dtype) {
|
|
this.throwIfDisposed();
|
|
return trackerFn().makeVariable(this, trainable, name, dtype);
|
|
}
|
|
}
|
|
Object.defineProperty(Tensor, Symbol.hasInstance, {
|
|
value: (instance)=>{
|
|
// Implementation note: we should use properties of the object that will be
|
|
// defined before the constructor body has finished executing (methods).
|
|
// This is because when this code is transpiled by babel, babel will call
|
|
// classCallCheck before the constructor body is run.
|
|
// See https://github.com/tensorflow/tfjs/issues/3384 for backstory.
|
|
return !!instance && instance.data != null && instance.dataSync != null && instance.throwIfDisposed != null;
|
|
}
|
|
});
|
|
function getGlobalTensorClass() {
|
|
// Use getGlobal so that we can augment the Tensor class across package
|
|
// boundaries becase the node resolution alg may result in different modules
|
|
// being returned for this file depending on the path they are loaded from.
|
|
return (0, _globalUtil.getGlobal)("Tensor", ()=>{
|
|
return Tensor;
|
|
});
|
|
}
|
|
// Global side effect. Cache global reference to Tensor class
|
|
getGlobalTensorClass();
|
|
class Variable extends 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);
|
|
}
|
|
dispose() {
|
|
trackerFn().disposeVariable(this);
|
|
this.isDisposedInternal = true;
|
|
}
|
|
}
|
|
Object.defineProperty(Variable, Symbol.hasInstance, {
|
|
value: (instance)=>{
|
|
return instance instanceof Tensor && instance.assign != null && instance.assign instanceof Function;
|
|
}
|
|
});
|
|
|
|
},{"./global_util":"82SAe","./tensor_format":"k2Ex9","./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"k2Ex9":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tensorToString", ()=>tensorToString);
|
|
var _util = require("./util");
|
|
// 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 = (0, _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 = (0, _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 ((0, _util.isString)(val)) valStr = `'${val}'`;
|
|
else if (dtype === "bool") valStr = boolNumToString(val);
|
|
else valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
|
|
return (0, _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));
|
|
}
|
|
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] = "[" + (size > 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;
|
|
}
|
|
|
|
},{"./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8jzJG":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "makeTypesMatch", ()=>makeTypesMatch);
|
|
parcelHelpers.export(exports, "assertTypesMatch", ()=>assertTypesMatch);
|
|
parcelHelpers.export(exports, "isTensorInList", ()=>isTensorInList);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getTensorsInContainer", ()=>getTensorsInContainer);
|
|
var _tensor = require("./tensor");
|
|
var _types = require("./types");
|
|
var _util = require("./util");
|
|
function makeTypesMatch(a, b) {
|
|
if (a.dtype === b.dtype) return [
|
|
a,
|
|
b
|
|
];
|
|
const dtype = (0, _types.upcastType)(a.dtype, b.dtype);
|
|
return [
|
|
a.cast(dtype),
|
|
b.cast(dtype)
|
|
];
|
|
}
|
|
function assertTypesMatch(a, b) {
|
|
(0, _util.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);
|
|
}
|
|
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 (0, _tensor.Tensor)) {
|
|
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";
|
|
}
|
|
|
|
},{"./tensor":"cJNoh","./types":"10R8n","./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"10R8n":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Rank", ()=>Rank);
|
|
parcelHelpers.export(exports, "upcastType", ()=>upcastType);
|
|
/** Returns the output type after summation. */ parcelHelpers.export(exports, "sumOutType", ()=>sumOutType);
|
|
parcelHelpers.export(exports, "isWebGLData", ()=>isWebGLData);
|
|
parcelHelpers.export(exports, "isWebGPUData", ()=>isWebGPUData);
|
|
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];
|
|
}
|
|
function sumOutType(type) {
|
|
return upcastType(type, "int32");
|
|
}
|
|
function isWebGLData(values) {
|
|
return values != null && typeof values === "object" && "texture" in values && values.texture instanceof WebGLTexture;
|
|
}
|
|
function isWebGPUData(values) {
|
|
return typeof GPUBuffer !== "undefined" && values != null && typeof values === "object" && "buffer" in values && values.buffer instanceof GPUBuffer;
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5yJGC":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var _engine = require("./engine");
|
|
var _deviceUtil = require("./device_util");
|
|
var _environment = require("./environment");
|
|
var process = require("329ebbdb86789035");
|
|
const ENV = (0, _environment.env)();
|
|
/**
|
|
* 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", ()=>_deviceUtil.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));
|
|
/** Whether this browser is Safari. */ ENV.registerFlag("IS_SAFARI", ()=>typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Safari/.test(navigator.userAgent) && /Apple/.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);
|
|
/** Whether to check computation result for errors. */ ENV.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", ()=>ENV.getBool("DEBUG"));
|
|
/** Whether the backend needs to wrap input to imageBitmap. */ ENV.registerFlag("WRAP_TO_IMAGEBITMAP", ()=>false);
|
|
/** Whether to enable canvas2d willReadFrequently for GPU backends */ ENV.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU", ()=>false);
|
|
/** Whether to use setTimeoutCustom */ ENV.registerFlag("USE_SETTIMEOUTCUSTOM", ()=>false);
|
|
|
|
},{"329ebbdb86789035":"h0aBX","./engine":"1g2qo","./device_util":"5fozk","./environment":"dXmHm"}],"5fozk":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line:no-any
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mockIsMobile", ()=>mockIsMobile);
|
|
parcelHelpers.export(exports, "isMobile", ()=>isMobile);
|
|
parcelHelpers.export(exports, "isBrowser", ()=>isBrowser);
|
|
function _isNavigatorDefined() {
|
|
return typeof navigator !== "undefined" && navigator != null;
|
|
}
|
|
let isMobileMockValue;
|
|
function mockIsMobile(value) {
|
|
isMobileMockValue = value;
|
|
}
|
|
function isMobile(nav) {
|
|
if (isMobileMockValue !== undefined) return isMobileMockValue;
|
|
if (nav || _isNavigatorDefined()) {
|
|
if (!nav) nav = navigator;
|
|
if (nav.product === "ReactNative") return true;
|
|
const a = nav.userAgent || nav.vendor || // tslint:disable-next-line:no-any
|
|
(typeof window !== "undefined" ? window.opera : "");
|
|
// Use `navigator.userAgentData.mobile` as fallback.
|
|
if (!a) {
|
|
// tslint:disable-next-line:no-any
|
|
const navAny = nav;
|
|
return navAny.userAgentData && navAny.userAgentData.mobile;
|
|
}
|
|
// 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";
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"k39df":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "PlatformBrowser", ()=>PlatformBrowser);
|
|
var _flags = require("../flags");
|
|
var _environment = require("../environment");
|
|
var _indexedDb = require("../io/indexed_db");
|
|
var _localStorage = require("../io/local_storage");
|
|
var _modelManagement = require("../io/model_management");
|
|
var _isTypedArrayBrowser = require("./is_typed_array_browser");
|
|
class PlatformBrowser {
|
|
constructor(){
|
|
// For setTimeoutCustom
|
|
this.messageName = "setTimeoutCustom";
|
|
this.functionRefs = [];
|
|
this.handledMessageCount = 0;
|
|
this.hasEventListener = false;
|
|
}
|
|
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 the setTimeout nesting level is greater than 5 and timeout is less
|
|
// than 4ms, timeout will be clamped to 4ms, which hurts the perf.
|
|
// Interleaving window.postMessage and setTimeout will trick the browser and
|
|
// avoid the clamp.
|
|
setTimeoutCustom(functionRef, delay) {
|
|
if (typeof window === "undefined" || !(0, _environment.env)().getBool("USE_SETTIMEOUTCUSTOM")) {
|
|
setTimeout(functionRef, delay);
|
|
return;
|
|
}
|
|
this.functionRefs.push(functionRef);
|
|
setTimeout(()=>{
|
|
window.postMessage({
|
|
name: this.messageName,
|
|
index: this.functionRefs.length - 1
|
|
}, "*");
|
|
}, delay);
|
|
if (!this.hasEventListener) {
|
|
this.hasEventListener = true;
|
|
window.addEventListener("message", (event)=>{
|
|
if (event.source === window && event.data.name === this.messageName) {
|
|
event.stopPropagation();
|
|
const functionRef = this.functionRefs[event.data.index];
|
|
functionRef();
|
|
this.handledMessageCount++;
|
|
if (this.handledMessageCount === this.functionRefs.length) {
|
|
this.functionRefs = [];
|
|
this.handledMessageCount = 0;
|
|
}
|
|
}
|
|
}, true);
|
|
}
|
|
}
|
|
isTypedArray(a) {
|
|
return (0, _isTypedArrayBrowser.isTypedArrayBrowser)(a);
|
|
}
|
|
}
|
|
if ((0, _environment.env)().get("IS_BROWSER")) {
|
|
(0, _environment.env)().setPlatform("browser", new PlatformBrowser());
|
|
// Register LocalStorage IOHandler
|
|
try {
|
|
(0, _modelManagement.ModelStoreManagerRegistry).registerManager((0, _localStorage.BrowserLocalStorage).URL_SCHEME, new (0, _localStorage.BrowserLocalStorageManager)());
|
|
} catch (err) {}
|
|
// Register IndexedDB IOHandler
|
|
try {
|
|
(0, _modelManagement.ModelStoreManagerRegistry).registerManager((0, _indexedDb.BrowserIndexedDB).URL_SCHEME, new (0, _indexedDb.BrowserIndexedDBManager)());
|
|
} catch (err) {}
|
|
}
|
|
|
|
},{"../flags":"5yJGC","../environment":"dXmHm","../io/indexed_db":"aWBtv","../io/local_storage":"c3TPR","../io/model_management":"iB0Mw","./is_typed_array_browser":"cjcvP","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aWBtv":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Delete the entire database for tensorflow.js, including the models store.
|
|
*/ parcelHelpers.export(exports, "deleteDatabase", ()=>deleteDatabase);
|
|
parcelHelpers.export(exports, "BrowserIndexedDB", ()=>BrowserIndexedDB);
|
|
parcelHelpers.export(exports, "indexedDBRouter", ()=>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`.
|
|
*/ parcelHelpers.export(exports, "browserIndexedDB", ()=>browserIndexedDB);
|
|
parcelHelpers.export(exports, "BrowserIndexedDBManager", ()=>BrowserIndexedDBManager);
|
|
var _flags = require("../flags");
|
|
var _environment = require("../environment");
|
|
var _ioUtils = require("./io_utils");
|
|
var _routerRegistry = require("./router_registry");
|
|
var _compositeArrayBuffer = require("./composite_array_buffer");
|
|
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";
|
|
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 (!(0, _environment.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 environmentis 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 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.
|
|
// Concatenate all the model weights into a single ArrayBuffer. Large
|
|
// models (~1GB) have problems saving if they are not concatenated.
|
|
// TODO(mattSoulanille): Save large models to multiple indexeddb
|
|
// records.
|
|
modelArtifacts.weightData = (0, _compositeArrayBuffer.CompositeArrayBuffer).join(modelArtifacts.weightData);
|
|
const modelArtifactsInfo = (0, _ioUtils.getModelArtifactsInfoForJSON)(modelArtifacts);
|
|
// First, put ModelArtifactsInfo into info store.
|
|
const infoTx = db.transaction(INFO_STORE_NAME, "readwrite");
|
|
let infoStore = infoTx.objectStore(INFO_STORE_NAME);
|
|
let putInfoRequest;
|
|
try {
|
|
putInfoRequest = infoStore.put({
|
|
modelPath: this.modelPath,
|
|
modelArtifactsInfo
|
|
});
|
|
} catch (error) {
|
|
return reject(error);
|
|
}
|
|
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);
|
|
let putModelRequest;
|
|
try {
|
|
putModelRequest = modelStore.put({
|
|
modelPath: this.modelPath,
|
|
modelArtifacts,
|
|
modelArtifactsInfo
|
|
});
|
|
} catch (error) {
|
|
// Sometimes, the serialized value is too large to store.
|
|
return reject(error);
|
|
}
|
|
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);
|
|
});
|
|
}
|
|
}
|
|
BrowserIndexedDB.URL_SCHEME = "indexeddb://";
|
|
const indexedDBRouter = (url)=>{
|
|
if (!(0, _environment.env)().getBool("IS_BROWSER")) return null;
|
|
else {
|
|
if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));
|
|
else return null;
|
|
}
|
|
};
|
|
(0, _routerRegistry.IORouterRegistry).registerSaveRouter(indexedDBRouter);
|
|
(0, _routerRegistry.IORouterRegistry).registerLoadRouter(indexedDBRouter);
|
|
function browserIndexedDB(modelPath) {
|
|
return new BrowserIndexedDB(modelPath);
|
|
}
|
|
function maybeStripScheme(key) {
|
|
return key.startsWith(BrowserIndexedDB.URL_SCHEME) ? key.slice(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);
|
|
});
|
|
}
|
|
}
|
|
|
|
},{"../flags":"5yJGC","../environment":"dXmHm","./io_utils":"hW5iQ","./router_registry":"btpsw","./composite_array_buffer":"gHH7C","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hW5iQ":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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`.
|
|
*/ parcelHelpers.export(exports, "encodeWeights", ()=>encodeWeights);
|
|
/**
|
|
* Decode flat ArrayBuffer as weights.
|
|
*
|
|
* This function does not handle sharding.
|
|
*
|
|
* This function is the reverse of `encodeWeights`.
|
|
*
|
|
* @param weightData A flat ArrayBuffer or an array of ArrayBuffers 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.
|
|
*/ parcelHelpers.export(exports, "decodeWeights", ()=>decodeWeights);
|
|
parcelHelpers.export(exports, "decodeWeightsStream", ()=>decodeWeightsStream);
|
|
/**
|
|
* Concatenate TypedArrays into an ArrayBuffer.
|
|
*/ parcelHelpers.export(exports, "concatenateTypedArrays", ()=>concatenateTypedArrays);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "stringByteLength", ()=>stringByteLength);
|
|
/**
|
|
* Encode an ArrayBuffer as a base64 encoded string.
|
|
*
|
|
* @param buffer `ArrayBuffer` to be converted.
|
|
* @returns A string that base64-encodes `buffer`.
|
|
*/ parcelHelpers.export(exports, "arrayBufferToBase64String", ()=>arrayBufferToBase64String);
|
|
/**
|
|
* Decode a base64 string as an ArrayBuffer.
|
|
*
|
|
* @param str Base64 string.
|
|
* @returns Decoded `ArrayBuffer`.
|
|
*/ parcelHelpers.export(exports, "base64StringToArrayBuffer", ()=>base64StringToArrayBuffer);
|
|
/**
|
|
* Concatenate a number of ArrayBuffers into one.
|
|
*
|
|
* @param buffers An array of ArrayBuffers to concatenate, or a single
|
|
* ArrayBuffer.
|
|
* @returns Result of concatenating `buffers` in order.
|
|
*
|
|
* @deprecated Use tf.io.CompositeArrayBuffer.join() instead.
|
|
*/ parcelHelpers.export(exports, "concatenateArrayBuffers", ()=>concatenateArrayBuffers);
|
|
/**
|
|
* Get the basename of a path.
|
|
*
|
|
* Behaves in a way analogous to Linux's basename command.
|
|
*
|
|
* @param path
|
|
*/ parcelHelpers.export(exports, "basename", ()=>basename);
|
|
/**
|
|
* Create `ModelJSON` from `ModelArtifacts`.
|
|
*
|
|
* @param artifacts Model artifacts, describing the model and its weights.
|
|
* @param manifest Weight manifest, describing where the weights of the
|
|
* `ModelArtifacts` are stored, and some metadata about them.
|
|
* @returns Object representing the `model.json` file describing the model
|
|
* artifacts and weights
|
|
*/ parcelHelpers.export(exports, "getModelJSONForModelArtifacts", ()=>getModelJSONForModelArtifacts);
|
|
/**
|
|
* Create `ModelArtifacts` from a JSON file and weights.
|
|
*
|
|
* @param modelJSON Object containing the parsed JSON of `model.json`
|
|
* @param weightSpecs The list of WeightsManifestEntry for the model. Must be
|
|
* passed if the modelJSON has a weightsManifest.
|
|
* @param weightData An ArrayBuffer or array of ArrayBuffers of weight data for
|
|
* the model corresponding to the weights in weightSpecs. Must be passed if
|
|
* the modelJSON has a weightsManifest.
|
|
* @returns A Promise of the `ModelArtifacts`, as described by the JSON file.
|
|
*/ parcelHelpers.export(exports, "getModelArtifactsForJSONSync", ()=>getModelArtifactsForJSONSync);
|
|
/**
|
|
* Create `ModelArtifacts` from a JSON file.
|
|
*
|
|
* @param modelJSON Object containing the parsed JSON of `model.json`
|
|
* @param loadWeights Function that takes the JSON file's weights manifest,
|
|
* reads weights from the listed path(s), and returns a Promise of the
|
|
* weight manifest entries along with the weights data.
|
|
* @returns A Promise of the `ModelArtifacts`, as described by the JSON file.
|
|
*/ parcelHelpers.export(exports, "getModelArtifactsForJSON", ()=>getModelArtifactsForJSON);
|
|
/**
|
|
* Populate ModelArtifactsInfo fields for a model with JSON topology.
|
|
* @param modelArtifacts
|
|
* @returns A ModelArtifactsInfo object.
|
|
*/ parcelHelpers.export(exports, "getModelArtifactsInfoForJSON", ()=>getModelArtifactsInfoForJSON);
|
|
/**
|
|
* Concatenate the weights stored in a WeightsManifestConfig into a list of
|
|
* WeightsManifestEntry
|
|
*
|
|
* @param weightsManifest The WeightsManifestConfig to extract weights from.
|
|
* @returns A list of WeightsManifestEntry of the weights in the weightsManifest
|
|
*/ parcelHelpers.export(exports, "getWeightSpecs", ()=>getWeightSpecs);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getFloat16Decoder", ()=>getFloat16Decoder);
|
|
var _complex = require("../ops/complex");
|
|
var _tensor = require("../ops/tensor");
|
|
var _util = require("../util");
|
|
var _types = require("./types");
|
|
var _compositeArrayBuffer = require("./composite_array_buffer");
|
|
var _globals = require("../globals");
|
|
var _environment = require("../environment");
|
|
var Buffer = require("cc5f092a6233570f").Buffer;
|
|
/** Number of bytes reserved for the length of the string. (32bit integer). */ const NUM_BYTES_STRING_LENGTH = 4;
|
|
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
|
|
};
|
|
}
|
|
function decodeWeights(weightData, specs) {
|
|
// TODO(adarob, cais): Support quantization.
|
|
const compositeBuffer = new (0, _compositeArrayBuffer.CompositeArrayBuffer)(weightData);
|
|
const out = {};
|
|
let offset = 0;
|
|
for (const spec of specs){
|
|
const byteLength = getWeightBytelength(spec, (start, end)=>{
|
|
return compositeBuffer.slice(offset + start, offset + end);
|
|
});
|
|
out[spec.name] = decodeWeight(spec, compositeBuffer.slice(offset, offset + byteLength));
|
|
offset += byteLength;
|
|
}
|
|
return out;
|
|
}
|
|
function getWeightBytelength(spec, slice) {
|
|
const size = (0, _util.sizeFromShape)(spec.shape);
|
|
let bytesPerValue;
|
|
if ("quantization" in spec) {
|
|
const quantization = spec.quantization;
|
|
bytesPerValue = (0, _types.DTYPE_VALUE_SIZE_MAP)[quantization.dtype];
|
|
} else if (spec.dtype === "string") {
|
|
// Can not statically determine string length.
|
|
let byteLength = 0;
|
|
for(let i = 0; i < size; i++)byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(slice(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];
|
|
return byteLength;
|
|
} else bytesPerValue = (0, _types.DTYPE_VALUE_SIZE_MAP)[spec.dtype];
|
|
return size * bytesPerValue;
|
|
}
|
|
async function getWeightBytelengthAsync(spec, slice) {
|
|
const size = (0, _util.sizeFromShape)(spec.shape);
|
|
let bytesPerValue;
|
|
if ("quantization" in spec) {
|
|
const quantization = spec.quantization;
|
|
bytesPerValue = (0, _types.DTYPE_VALUE_SIZE_MAP)[quantization.dtype];
|
|
} else if (spec.dtype === "string") {
|
|
// Can not statically determine string length.
|
|
let byteLength = 0;
|
|
for(let i = 0; i < size; i++)byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(await slice(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];
|
|
return byteLength;
|
|
} else bytesPerValue = (0, _types.DTYPE_VALUE_SIZE_MAP)[spec.dtype];
|
|
return size * bytesPerValue;
|
|
}
|
|
function decodeWeight(spec, byteBuffer) {
|
|
const name = spec.name;
|
|
const dtype = spec.dtype;
|
|
const shape = spec.shape;
|
|
const size = (0, _util.sizeFromShape)(shape);
|
|
let values;
|
|
let offset = 0;
|
|
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 = (0, _types.DTYPE_VALUE_SIZE_MAP)[quantization.dtype];
|
|
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") {
|
|
// TODO: This is inefficient. Make getFloat16Decoder efficient.
|
|
const 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 = (0, _util.sizeFromShape)(spec.shape);
|
|
values = [];
|
|
for(let i = 0; i < size; i++){
|
|
const byteLength = new Uint32Array(byteBuffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];
|
|
offset += NUM_BYTES_STRING_LENGTH;
|
|
const bytes = new Uint8Array(byteBuffer.slice(offset, offset + byteLength));
|
|
values.push(bytes);
|
|
offset += byteLength;
|
|
}
|
|
} else {
|
|
const dtypeFactor = (0, _types.DTYPE_VALUE_SIZE_MAP)[dtype];
|
|
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 = (0, _tensor.tensor)(real, shape, "float32");
|
|
const imageTensor = (0, _tensor.tensor)(image, shape, "float32");
|
|
const complexTensor = (0, _complex.complex)(realTensor, imageTensor);
|
|
realTensor.dispose();
|
|
imageTensor.dispose();
|
|
return complexTensor;
|
|
} else throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);
|
|
offset += size * dtypeFactor;
|
|
}
|
|
return (0, _tensor.tensor)(values, shape, dtype);
|
|
}
|
|
async function readToLength(reader, initialData, length) {
|
|
let data = new Uint8Array(initialData);
|
|
while(data.byteLength < length){
|
|
const { done, value } = await reader.read();
|
|
if (done && value == null) {
|
|
const missing = length - data.byteLength;
|
|
throw new Error(`Reader is done but ${missing} bytes are still expected`);
|
|
}
|
|
// TODO: Don't create a new array every loop.
|
|
const newData = new Uint8Array(data.length + value.byteLength);
|
|
newData.set(data, 0);
|
|
newData.set(new Uint8Array(value), data.length);
|
|
data = newData;
|
|
}
|
|
return data.buffer;
|
|
}
|
|
async function decodeWeightsStream(weightStream, specs) {
|
|
const tensors = {};
|
|
const reader = weightStream.getReader();
|
|
let data = new ArrayBuffer(0);
|
|
for (const spec of specs){
|
|
const byteLength = await getWeightBytelengthAsync(spec, async (start, end)=>{
|
|
data = await readToLength(reader, data, end);
|
|
return data.slice(start, end);
|
|
});
|
|
data = await readToLength(reader, data, byteLength);
|
|
// Slice the tensor out
|
|
const tensorData = data.slice(0, byteLength);
|
|
data = data.slice(byteLength);
|
|
const weightTensor = decodeWeight(spec, tensorData);
|
|
tensors[spec.name] = weightTensor;
|
|
// TODO(mattsoulanille): Better way to call uploadToGPU.
|
|
// TODO(mattsoulanille): Make this work for webgl too.
|
|
if ((0, _globals.getBackend)() === "webgpu") {
|
|
const b = (0, _globals.backend)();
|
|
if ("uploadToGPU" in b && (0, _util.sizeFromShape)(weightTensor.shape) >= (0, _environment.env)().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")) b.uploadToGPU(weightTensor.dataId);
|
|
}
|
|
}
|
|
return tensors;
|
|
}
|
|
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");
|
|
function stringByteLength(str) {
|
|
if (useNodeBuffer) return Buffer.byteLength(str, "utf8");
|
|
return new Blob([
|
|
str
|
|
]).size;
|
|
}
|
|
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);
|
|
}
|
|
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;
|
|
}
|
|
function concatenateArrayBuffers(buffers) {
|
|
return (0, _compositeArrayBuffer.CompositeArrayBuffer).join(buffers);
|
|
}
|
|
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];
|
|
}
|
|
function getModelJSONForModelArtifacts(artifacts, manifest) {
|
|
const result = {
|
|
modelTopology: artifacts.modelTopology,
|
|
format: artifacts.format,
|
|
generatedBy: artifacts.generatedBy,
|
|
convertedBy: artifacts.convertedBy,
|
|
weightsManifest: manifest
|
|
};
|
|
if (artifacts.signature != null) result.signature = artifacts.signature;
|
|
if (artifacts.userDefinedMetadata != null) result.userDefinedMetadata = artifacts.userDefinedMetadata;
|
|
if (artifacts.modelInitializer != null) result.modelInitializer = artifacts.modelInitializer;
|
|
if (artifacts.initializerSignature != null) result.initializerSignature = artifacts.initializerSignature;
|
|
if (artifacts.trainingConfig != null) result.trainingConfig = artifacts.trainingConfig;
|
|
return result;
|
|
}
|
|
function getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData) {
|
|
const modelArtifacts = {
|
|
modelTopology: modelJSON.modelTopology,
|
|
format: modelJSON.format,
|
|
generatedBy: modelJSON.generatedBy,
|
|
convertedBy: modelJSON.convertedBy
|
|
};
|
|
if (modelJSON.trainingConfig != null) modelArtifacts.trainingConfig = modelJSON.trainingConfig;
|
|
if (modelJSON.weightsManifest != null) {
|
|
if (!weightSpecs) throw new Error("modelJSON has weightsManifest but weightSpecs is null");
|
|
if (!weightData) throw new Error("modelJSON has weightsManifest but weightData is null");
|
|
modelArtifacts.weightSpecs = weightSpecs;
|
|
modelArtifacts.weightData = weightData;
|
|
}
|
|
if (modelJSON.signature != null) modelArtifacts.signature = modelJSON.signature;
|
|
if (modelJSON.userDefinedMetadata != null) modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;
|
|
if (modelJSON.modelInitializer != null) modelArtifacts.modelInitializer = modelJSON.modelInitializer;
|
|
if (modelJSON.initializerSignature != null) modelArtifacts.initializerSignature = modelJSON.initializerSignature;
|
|
return modelArtifacts;
|
|
}
|
|
async function getModelArtifactsForJSON(modelJSON, loadWeights) {
|
|
let weightSpecs;
|
|
let weightData;
|
|
if (modelJSON.weightsManifest != null) [weightSpecs, weightData] = await loadWeights(modelJSON.weightsManifest);
|
|
return getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData);
|
|
}
|
|
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 : new (0, _compositeArrayBuffer.CompositeArrayBuffer)(modelArtifacts.weightData).byteLength
|
|
};
|
|
}
|
|
function getWeightSpecs(weightsManifest) {
|
|
const weightSpecs = [];
|
|
for (const entry of weightsManifest)weightSpecs.push(...entry.weights);
|
|
return weightSpecs;
|
|
}
|
|
/**
|
|
* 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 &= -8388609;
|
|
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;
|
|
}
|
|
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);
|
|
};
|
|
}
|
|
|
|
},{"cc5f092a6233570f":"kLBSi","../ops/complex":"bPDAx","../ops/tensor":"jdbb1","../util":"ctavo","./types":"ixgVc","./composite_array_buffer":"gHH7C","../globals":"eO1Ja","../environment":"dXmHm","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kLBSi":[function(require,module,exports) {
|
|
/*!
|
|
* The buffer module from node.js, for the browser.
|
|
*
|
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
* @license MIT
|
|
*/ /* eslint-disable no-proto */ "use strict";
|
|
var base64 = require("9c62938f1dccc73c");
|
|
var ieee754 = require("aceacb6a4531a9d2");
|
|
var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" // eslint-disable-line dot-notation
|
|
? Symbol["for"]("nodejs.util.inspect.custom") // eslint-disable-line dot-notation
|
|
: null;
|
|
exports.Buffer = Buffer;
|
|
exports.SlowBuffer = SlowBuffer;
|
|
exports.INSPECT_MAX_BYTES = 50;
|
|
var K_MAX_LENGTH = 0x7fffffff;
|
|
exports.kMaxLength = K_MAX_LENGTH;
|
|
/**
|
|
* If `Buffer.TYPED_ARRAY_SUPPORT`:
|
|
* === true Use Uint8Array implementation (fastest)
|
|
* === false Print warning and recommend using `buffer` v4.x which has an 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+.
|
|
*
|
|
* We report that the browser does not support typed arrays if the are not subclassable
|
|
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
|
|
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
|
|
* for __proto__ and has a buggy typed array implementation.
|
|
*/ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
|
|
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");
|
|
function typedArraySupport() {
|
|
// Can typed array instances can be augmented?
|
|
try {
|
|
var arr = new Uint8Array(1);
|
|
var proto = {
|
|
foo: function() {
|
|
return 42;
|
|
}
|
|
};
|
|
Object.setPrototypeOf(proto, Uint8Array.prototype);
|
|
Object.setPrototypeOf(arr, proto);
|
|
return arr.foo() === 42;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
Object.defineProperty(Buffer.prototype, "parent", {
|
|
enumerable: true,
|
|
get: function() {
|
|
if (!Buffer.isBuffer(this)) return undefined;
|
|
return this.buffer;
|
|
}
|
|
});
|
|
Object.defineProperty(Buffer.prototype, "offset", {
|
|
enumerable: true,
|
|
get: function() {
|
|
if (!Buffer.isBuffer(this)) return undefined;
|
|
return this.byteOffset;
|
|
}
|
|
});
|
|
function createBuffer(length) {
|
|
if (length > K_MAX_LENGTH) throw new RangeError('The value "' + length + '" is invalid for option "size"');
|
|
// Return an augmented `Uint8Array` instance
|
|
var buf = new Uint8Array(length);
|
|
Object.setPrototypeOf(buf, Buffer.prototype);
|
|
return buf;
|
|
}
|
|
/**
|
|
* 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) {
|
|
// Common case.
|
|
if (typeof arg === "number") {
|
|
if (typeof encodingOrOffset === "string") throw new TypeError('The "string" argument must be of type string. Received type number');
|
|
return allocUnsafe(arg);
|
|
}
|
|
return from(arg, encodingOrOffset, length);
|
|
}
|
|
Buffer.poolSize = 8192 // not used by this implementation
|
|
;
|
|
function from(value, encodingOrOffset, length) {
|
|
if (typeof value === "string") return fromString(value, encodingOrOffset);
|
|
if (ArrayBuffer.isView(value)) return fromArrayView(value);
|
|
if (value == null) throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
|
|
if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) return fromArrayBuffer(value, encodingOrOffset, length);
|
|
if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) return fromArrayBuffer(value, encodingOrOffset, length);
|
|
if (typeof value === "number") throw new TypeError('The "value" argument must not be of type number. Received type number');
|
|
var valueOf = value.valueOf && value.valueOf();
|
|
if (valueOf != null && valueOf !== value) return Buffer.from(valueOf, encodingOrOffset, length);
|
|
var b = fromObject(value);
|
|
if (b) return b;
|
|
if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") return Buffer.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
|
|
throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof 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(value, encodingOrOffset, length);
|
|
};
|
|
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
|
|
// https://github.com/feross/buffer/pull/148
|
|
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
|
|
Object.setPrototypeOf(Buffer, Uint8Array);
|
|
function assertSize(size) {
|
|
if (typeof size !== "number") throw new TypeError('"size" argument must be of type number');
|
|
else if (size < 0) throw new RangeError('The value "' + size + '" is invalid for option "size"');
|
|
}
|
|
function alloc(size, fill, encoding) {
|
|
assertSize(size);
|
|
if (size <= 0) return createBuffer(size);
|
|
if (fill !== undefined) // Only pay attention to encoding if it's a string. This
|
|
// prevents accidentally sending in a number that would
|
|
// be interpreted as a start offset.
|
|
return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
|
|
return createBuffer(size);
|
|
}
|
|
/**
|
|
* Creates a new filled Buffer instance.
|
|
* alloc(size[, fill[, encoding]])
|
|
**/ Buffer.alloc = function(size, fill, encoding) {
|
|
return alloc(size, fill, encoding);
|
|
};
|
|
function allocUnsafe(size) {
|
|
assertSize(size);
|
|
return createBuffer(size < 0 ? 0 : checked(size) | 0);
|
|
}
|
|
/**
|
|
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
|
|
* */ Buffer.allocUnsafe = function(size) {
|
|
return allocUnsafe(size);
|
|
};
|
|
/**
|
|
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
|
|
*/ Buffer.allocUnsafeSlow = function(size) {
|
|
return allocUnsafe(size);
|
|
};
|
|
function fromString(string, encoding) {
|
|
if (typeof encoding !== "string" || encoding === "") encoding = "utf8";
|
|
if (!Buffer.isEncoding(encoding)) throw new TypeError("Unknown encoding: " + encoding);
|
|
var length = byteLength(string, encoding) | 0;
|
|
var buf = createBuffer(length);
|
|
var actual = buf.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')
|
|
buf = buf.slice(0, actual);
|
|
return buf;
|
|
}
|
|
function fromArrayLike(array) {
|
|
var length = array.length < 0 ? 0 : checked(array.length) | 0;
|
|
var buf = createBuffer(length);
|
|
for(var i = 0; i < length; i += 1)buf[i] = array[i] & 255;
|
|
return buf;
|
|
}
|
|
function fromArrayView(arrayView) {
|
|
if (isInstance(arrayView, Uint8Array)) {
|
|
var copy = new Uint8Array(arrayView);
|
|
return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
|
|
}
|
|
return fromArrayLike(arrayView);
|
|
}
|
|
function fromArrayBuffer(array, byteOffset, length) {
|
|
if (byteOffset < 0 || array.byteLength < byteOffset) throw new RangeError('"offset" is outside of buffer bounds');
|
|
if (array.byteLength < byteOffset + (length || 0)) throw new RangeError('"length" is outside of buffer bounds');
|
|
var buf;
|
|
if (byteOffset === undefined && length === undefined) buf = new Uint8Array(array);
|
|
else if (length === undefined) buf = new Uint8Array(array, byteOffset);
|
|
else buf = new Uint8Array(array, byteOffset, length);
|
|
// Return an augmented `Uint8Array` instance
|
|
Object.setPrototypeOf(buf, Buffer.prototype);
|
|
return buf;
|
|
}
|
|
function fromObject(obj) {
|
|
if (Buffer.isBuffer(obj)) {
|
|
var len = checked(obj.length) | 0;
|
|
var buf = createBuffer(len);
|
|
if (buf.length === 0) return buf;
|
|
obj.copy(buf, 0, 0, len);
|
|
return buf;
|
|
}
|
|
if (obj.length !== undefined) {
|
|
if (typeof obj.length !== "number" || numberIsNaN(obj.length)) return createBuffer(0);
|
|
return fromArrayLike(obj);
|
|
}
|
|
if (obj.type === "Buffer" && Array.isArray(obj.data)) return fromArrayLike(obj.data);
|
|
}
|
|
function checked(length) {
|
|
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
|
|
// length is NaN (which is otherwise coerced to zero.)
|
|
if (length >= K_MAX_LENGTH) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
|
|
return length | 0;
|
|
}
|
|
function SlowBuffer(length) {
|
|
if (+length != length) length = 0;
|
|
return Buffer.alloc(+length);
|
|
}
|
|
Buffer.isBuffer = function isBuffer(b) {
|
|
return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
|
|
;
|
|
};
|
|
Buffer.compare = function compare(a, b) {
|
|
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
|
|
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
|
|
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
|
|
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 (!Array.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 (isInstance(buf, Uint8Array)) {
|
|
if (pos + buf.length > buffer.length) Buffer.from(buf).copy(buffer, pos);
|
|
else Uint8Array.prototype.set.call(buffer, buf, pos);
|
|
} else if (!Buffer.isBuffer(buf)) throw new TypeError('"list" argument must be an Array of Buffers');
|
|
else buf.copy(buffer, pos);
|
|
pos += buf.length;
|
|
}
|
|
return buffer;
|
|
};
|
|
function byteLength(string, encoding) {
|
|
if (Buffer.isBuffer(string)) return string.length;
|
|
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) return string.byteLength;
|
|
if (typeof string !== "string") throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string);
|
|
var len = string.length;
|
|
var mustMatch = arguments.length > 2 && arguments[2] === true;
|
|
if (!mustMatch && 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":
|
|
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 mustMatch ? -1 : 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 coercion 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;
|
|
}
|
|
}
|
|
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
|
|
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
|
|
// reliably in a browserify context because there could be multiple different
|
|
// copies of the 'buffer' package in use. This method works even for Buffer
|
|
// instances that were created from another copy of the `buffer` package.
|
|
// See: https://github.com/feross/buffer/issues/154
|
|
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;
|
|
if (length === 0) return "";
|
|
if (arguments.length === 0) return utf8Slice(this, 0, length);
|
|
return slowToString.apply(this, arguments);
|
|
};
|
|
Buffer.prototype.toLocaleString = Buffer.prototype.toString;
|
|
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;
|
|
str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
|
|
if (this.length > max) str += " ... ";
|
|
return "<Buffer " + str + ">";
|
|
};
|
|
if (customInspectSymbol) Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
|
|
Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
|
|
if (isInstance(target, Uint8Array)) target = Buffer.from(target, target.offset, target.byteLength);
|
|
if (!Buffer.isBuffer(target)) throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target);
|
|
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 < -2147483648) byteOffset = -2147483648;
|
|
byteOffset = +byteOffset // Coerce to Number.
|
|
;
|
|
if (numberIsNaN(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 (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;
|
|
}
|
|
var strLen = string.length;
|
|
if (length > strLen / 2) length = strLen / 2;
|
|
for(var i = 0; i < length; ++i){
|
|
var parsed = parseInt(string.substr(i * 2, 2), 16);
|
|
if (numberIsNaN(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 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;
|
|
}
|
|
} 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":
|
|
case "latin1":
|
|
case "binary":
|
|
return asciiWrite(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 += hexSliceLookupTable[buf[i]];
|
|
return out;
|
|
}
|
|
function utf16leSlice(buf, start, end) {
|
|
var bytes = buf.slice(start, end);
|
|
var res = "";
|
|
// If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
|
|
for(var i = 0; i < bytes.length - 1; 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 = this.subarray(start, end);
|
|
// Return an augmented `Uint8Array` instance
|
|
Object.setPrototypeOf(newBuf, Buffer.prototype);
|
|
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 = 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 = 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 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkOffset(offset, 1, this.length);
|
|
return this[offset];
|
|
};
|
|
Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkOffset(offset, 2, this.length);
|
|
return this[offset] | this[offset + 1] << 8;
|
|
};
|
|
Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkOffset(offset, 2, this.length);
|
|
return this[offset] << 8 | this[offset + 1];
|
|
};
|
|
Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
|
|
offset = offset >>> 0;
|
|
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 = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
|
|
offset = offset >>> 0;
|
|
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) {
|
|
offset = offset >>> 0;
|
|
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) {
|
|
offset = offset >>> 0;
|
|
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) {
|
|
offset = offset >>> 0;
|
|
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) {
|
|
offset = offset >>> 0;
|
|
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) {
|
|
offset = offset >>> 0;
|
|
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) {
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkOffset(offset, 4, this.length);
|
|
return ieee754.read(this, offset, true, 23, 4);
|
|
};
|
|
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkOffset(offset, 4, this.length);
|
|
return ieee754.read(this, offset, false, 23, 4);
|
|
};
|
|
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkOffset(offset, 8, this.length);
|
|
return ieee754.read(this, offset, true, 52, 8);
|
|
};
|
|
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
|
|
offset = offset >>> 0;
|
|
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 = 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 = 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 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
|
|
this[offset] = value & 0xff;
|
|
return offset + 1;
|
|
};
|
|
Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
|
|
this[offset] = value & 0xff;
|
|
this[offset + 1] = value >>> 8;
|
|
return offset + 2;
|
|
};
|
|
Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
|
|
this[offset] = value >>> 8;
|
|
this[offset + 1] = value & 0xff;
|
|
return offset + 2;
|
|
};
|
|
Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
|
|
this[offset + 3] = value >>> 24;
|
|
this[offset + 2] = value >>> 16;
|
|
this[offset + 1] = value >>> 8;
|
|
this[offset] = value & 0xff;
|
|
return offset + 4;
|
|
};
|
|
Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
|
|
this[offset] = value >>> 24;
|
|
this[offset + 1] = value >>> 16;
|
|
this[offset + 2] = value >>> 8;
|
|
this[offset + 3] = value & 0xff;
|
|
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, -128);
|
|
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, -32768);
|
|
this[offset] = value & 0xff;
|
|
this[offset + 1] = value >>> 8;
|
|
return offset + 2;
|
|
};
|
|
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
|
|
this[offset] = value >>> 8;
|
|
this[offset + 1] = value & 0xff;
|
|
return offset + 2;
|
|
};
|
|
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
|
|
this[offset] = value & 0xff;
|
|
this[offset + 1] = value >>> 8;
|
|
this[offset + 2] = value >>> 16;
|
|
this[offset + 3] = value >>> 24;
|
|
return offset + 4;
|
|
};
|
|
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
|
|
if (value < 0) value = 0xffffffff + value + 1;
|
|
this[offset] = value >>> 24;
|
|
this[offset + 1] = value >>> 16;
|
|
this[offset + 2] = value >>> 8;
|
|
this[offset + 3] = value & 0xff;
|
|
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) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -340282346638528860000000000000000000000);
|
|
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) {
|
|
value = +value;
|
|
offset = offset >>> 0;
|
|
if (!noAssert) checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);
|
|
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 (!Buffer.isBuffer(target)) throw new TypeError("argument should be a Buffer");
|
|
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("Index out of range");
|
|
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;
|
|
if (this === target && typeof Uint8Array.prototype.copyWithin === "function") // Use built-in when available, missing from IE11
|
|
this.copyWithin(targetStart, start, end);
|
|
else Uint8Array.prototype.set.call(target, this.subarray(start, end), 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 (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);
|
|
if (val.length === 1) {
|
|
var code = val.charCodeAt(0);
|
|
if (encoding === "utf8" && code < 128 || encoding === "latin1") // Fast path: If `val` fits into a single byte, use that numeric value.
|
|
val = code;
|
|
}
|
|
} else if (typeof val === "number") val = val & 255;
|
|
else if (typeof val === "boolean") val = Number(val);
|
|
// 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 : Buffer.from(val, encoding);
|
|
var len = bytes.length;
|
|
if (len === 0) throw new TypeError('The value "' + val + '" is invalid for argument "value"');
|
|
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 takes equal signs as end of the Base64 encoding
|
|
str = str.split("=")[0];
|
|
// Node strips out invalid characters like \n and \t from the string, base64-js does not
|
|
str = str.trim().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 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;
|
|
}
|
|
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
|
|
// the `instanceof` check but they should be treated as of that type.
|
|
// See: https://github.com/feross/buffer/issues/166
|
|
function isInstance(obj, type) {
|
|
return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
|
|
}
|
|
function numberIsNaN(obj) {
|
|
// For IE11 support
|
|
return obj !== obj // eslint-disable-line no-self-compare
|
|
;
|
|
}
|
|
// Create lookup table for `toString('hex')`
|
|
// See: https://github.com/feross/buffer/issues/219
|
|
var hexSliceLookupTable = function() {
|
|
var alphabet = "0123456789abcdef";
|
|
var table = new Array(256);
|
|
for(var i = 0; i < 16; ++i){
|
|
var i16 = i * 16;
|
|
for(var j = 0; j < 16; ++j)table[i16 + j] = alphabet[i] + alphabet[j];
|
|
}
|
|
return table;
|
|
}();
|
|
|
|
},{"9c62938f1dccc73c":"jvQRR","aceacb6a4531a9d2":"9hhlZ"}],"jvQRR":[function(require,module,exports) {
|
|
"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("");
|
|
}
|
|
|
|
},{}],"9hhlZ":[function(require,module,exports) {
|
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ 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;
|
|
};
|
|
|
|
},{}],"bPDAx":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "complex", ()=>complex);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(real, "real", "complex");
|
|
const $imag = (0, _tensorUtilEnv.convertToTensor)(imag, "imag", "complex");
|
|
_util.assertShapesMatch($real.shape, $imag.shape, `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` + `must match in call to tf.complex().`);
|
|
const inputs = {
|
|
real: $real,
|
|
imag: $imag
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Complex), inputs);
|
|
}
|
|
const complex = /* @__PURE__ */ (0, _operation.op)({
|
|
complex_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6vfHI":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "inferShape", ()=>inferShape);
|
|
parcelHelpers.export(exports, "convertToTensor", ()=>convertToTensor);
|
|
parcelHelpers.export(exports, "convertToTensorArray", ()=>convertToTensorArray);
|
|
var _engine = require("./engine");
|
|
var _environment = require("./environment");
|
|
var _tensor = require("./tensor");
|
|
var _types = require("./types");
|
|
var _util = require("./util");
|
|
var _utilBase = require("./util_base");
|
|
function inferShape(val, dtype) {
|
|
let firstElem = val;
|
|
if ((0, _util.isTypedArray)(val)) return dtype === "string" ? [] : [
|
|
val.length
|
|
];
|
|
if ((0, _types.isWebGLData)(val)) {
|
|
const usedChannels = val.channels || "RGBA";
|
|
return [
|
|
val.height,
|
|
val.width * usedChannels.length
|
|
];
|
|
} else if ((0, _types.isWebGPUData)(val)) return [
|
|
val.buffer.size / (dtype == null ? 4 : (0, _utilBase.bytesPerElement)(dtype))
|
|
];
|
|
if (!Array.isArray(val)) return []; // Scalar.
|
|
const shape = [];
|
|
while(Array.isArray(firstElem) || (0, _util.isTypedArray)(firstElem) && dtype !== "string"){
|
|
shape.push(firstElem.length);
|
|
firstElem = firstElem[0];
|
|
}
|
|
if (Array.isArray(val) && (0, _environment.env)().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")) deepAssertShapeConsistency(val, shape, []);
|
|
return shape;
|
|
}
|
|
function deepAssertShapeConsistency(val, shape, indices) {
|
|
indices = indices || [];
|
|
if (!Array.isArray(val) && !(0, _util.isTypedArray)(val)) {
|
|
(0, _util.assert)(shape.length === 0, ()=>`Element arr[${indices.join("][")}] is a primitive, ` + `but should be an array/TypedArray of ${shape[0]} elements`);
|
|
return;
|
|
}
|
|
(0, _util.assert)(shape.length > 0, ()=>`Element arr[${indices.join("][")}] should be a primitive, ` + `but is an array of ${val.length} elements`);
|
|
(0, _util.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 === "string_or_numeric") return;
|
|
if (expectedDtype == null) throw new Error(`Expected dtype cannot be null.`);
|
|
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 (0, _tensor.getGlobalTensorClass)()) {
|
|
assertDtype(parseAsDtype, x.dtype, argName, functionName);
|
|
return x;
|
|
}
|
|
let inferredDtype = (0, _util.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 || !(0, _util.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 (!(0, _util.isTypedArray)(x) && !Array.isArray(x)) x = [
|
|
x
|
|
];
|
|
const skipTypedArray = true;
|
|
const values = inferredDtype !== "string" ? (0, _util.toTypedArray)(x, inferredDtype) : (0, _util.flatten)(x, [], skipTypedArray);
|
|
return (0, _engine.ENGINE).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));
|
|
}
|
|
|
|
},{"./engine":"1g2qo","./environment":"dXmHm","./tensor":"cJNoh","./types":"10R8n","./util":"ctavo","./util_base":"4Vo4a","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ip64W":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "OP_SCOPE_SUFFIX", ()=>OP_SCOPE_SUFFIX);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "op", ()=>op);
|
|
var _engine = require("../engine");
|
|
var _util = require("../util");
|
|
const OP_SCOPE_SUFFIX = "__op";
|
|
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);
|
|
// add an __op suffix to distinguish ops from kernels in tf.profile
|
|
opName = opName + OP_SCOPE_SUFFIX;
|
|
// tslint:disable-next-line:no-any
|
|
const f2 = (...args)=>{
|
|
(0, _engine.ENGINE).startScope(opName);
|
|
try {
|
|
const result = fn(...args);
|
|
if ((0, _util.isPromise)(result)) console.error("Cannot return a Promise inside of tidy.");
|
|
(0, _engine.ENGINE).endScope(result);
|
|
return result;
|
|
} catch (ex) {
|
|
(0, _engine.ENGINE).endScope(null);
|
|
throw ex;
|
|
}
|
|
};
|
|
Object.defineProperty(f2, "name", {
|
|
value: opName,
|
|
configurable: true
|
|
});
|
|
// tslint:disable-next-line:no-any
|
|
return f2;
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jdbb1":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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();
|
|
* ```
|
|
*
|
|
* ```js
|
|
* // Pass a `WebGLData` object and specify a shape yourself.
|
|
*
|
|
* // This makes it possible for TF.js applications to avoid GPU / CPU sync.
|
|
* // For example, if your application includes a preprocessing step on the GPU,
|
|
* // you could upload the GPU output directly to TF.js, rather than first
|
|
* // downloading the values.
|
|
*
|
|
* // Example for WebGL2:
|
|
* if (tf.findBackend('custom-webgl') == null) {
|
|
* const customCanvas = document.createElement('canvas');
|
|
* const customBackend = new tf.MathBackendWebGL(customCanvas);
|
|
* tf.registerBackend('custom-webgl', () => customBackend);
|
|
* }
|
|
* const savedBackend = tf.getBackend();
|
|
* await tf.setBackend('custom-webgl');
|
|
* const gl = tf.backend().gpgpu.gl;
|
|
* const texture = gl.createTexture();
|
|
* const tex2d = gl.TEXTURE_2D;
|
|
* const width = 2;
|
|
* const height = 2;
|
|
*
|
|
* gl.bindTexture(tex2d, texture);
|
|
* gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
|
* gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
|
* gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
|
* gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
|
* gl.texImage2D(
|
|
* tex2d, 0, gl.RGBA32F, // internalFormat
|
|
* width, height, 0,
|
|
* gl.RGBA, // textureFormat
|
|
* gl.FLOAT, // textureType
|
|
* new Float32Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
|
|
* );
|
|
*
|
|
* // Currently, the `texture` has 4 pixels:
|
|
* // Pixel0 is {R:0, G:1, B:2, A:3}
|
|
* // Pixel1 is {R:4, G:5, B:6, A:7}
|
|
* // Pixel2 is {R:8, G:9, B:10, A:11}
|
|
* // Pixel3 is {R:12, G:13, B:14, A:15}
|
|
*
|
|
* const logicalShape = [height * width * 2];
|
|
* const a = tf.tensor({texture, height, width, channels: 'BR'}, logicalShape);
|
|
* a.print();
|
|
* // Tensor value will be [2, 0, 6, 4, 10, 8, 14, 12], since [2, 0] is the
|
|
* // values of 'B' and 'R' channels of Pixel0, [6, 4] is the values of 'B' and
|
|
* 'R'
|
|
* // channels of Pixel1...
|
|
*
|
|
* // For postprocessing on the GPU, it's possible to retrieve the texture
|
|
* // backing any tensor by calling the tensor's `dataToGPU` method like
|
|
* // so:
|
|
*
|
|
* const tex = a.dataToGPU();
|
|
* await tf.setBackend(savedBackend);
|
|
* ```
|
|
*
|
|
* ```js
|
|
* // Pass a `WebGPUData` object and specify a shape yourself.
|
|
*
|
|
* // This makes it possible for TF.js applications to avoid GPU / CPU sync.
|
|
* // For example, if your application includes a preprocessing step on the GPU,
|
|
* // you could upload the GPU output directly to TF.js, rather than first
|
|
* // downloading the values. Unlike WebGL, this optionally supports zero copy
|
|
* // by WebGPUData.zeroCopy. When zeroCopy is false or undefined(default), this
|
|
* // passing GPUBuffer can be destroyed after tensor is created. When zeroCopy
|
|
* // is true, this GPUBuffer is bound directly by the tensor, so do not destroy
|
|
* // this GPUBuffer until all access is done.
|
|
*
|
|
* // Example for WebGPU:
|
|
* function createGPUBufferFromData(device, data, dtype) {
|
|
* const bytesPerElement = 4;
|
|
* const sizeInBytes = data.length * bytesPerElement;
|
|
*
|
|
* const gpuWriteBuffer = device.createBuffer({
|
|
* mappedAtCreation: true,
|
|
* size: sizeInBytes,
|
|
* usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC
|
|
* });
|
|
* const arrayBuffer = gpuWriteBuffer.getMappedRange();
|
|
* if (dtype === 'float32') {
|
|
* new Float32Array(arrayBuffer).set(data);
|
|
* } else if (dtype === 'int32') {
|
|
* new Int32Array(arrayBuffer).set(data);
|
|
* } else {
|
|
* throw new Error(
|
|
* `Creating tensor from GPUBuffer only supports` +
|
|
* `'float32'|'int32' dtype, while the dtype is ${dtype}.`);
|
|
* }
|
|
* gpuWriteBuffer.unmap();
|
|
*
|
|
* const gpuReadBuffer = device.createBuffer({
|
|
* mappedAtCreation: false,
|
|
* size: sizeInBytes,
|
|
* usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE |
|
|
* GPUBufferUsage.COPY_SRC
|
|
* });
|
|
*
|
|
* const copyEncoder = device.createCommandEncoder();
|
|
* copyEncoder.copyBufferToBuffer(
|
|
* gpuWriteBuffer, 0, gpuReadBuffer, 0, sizeInBytes);
|
|
* const copyCommands = copyEncoder.finish();
|
|
* device.queue.submit([copyCommands]);
|
|
* gpuWriteBuffer.destroy();
|
|
* return gpuReadBuffer;
|
|
* }
|
|
*
|
|
* const savedBackend = tf.getBackend();
|
|
* await tf.setBackend('webgpu').catch(
|
|
* () => {throw new Error(
|
|
* 'Failed to use WebGPU backend. Please use Chrome Canary to run.')});
|
|
* const dtype = 'float32';
|
|
* const device = tf.backend().device;
|
|
* const aData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
|
|
* const bData = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4];
|
|
* const expected = [2, 4, 6, 8, 6, 8, 10, 12, 10, 12, 14, 16, 14, 16, 18, 20];
|
|
* const aBuffer = createGPUBufferFromData(device, aData, dtype);
|
|
* const shape = [aData.length];
|
|
* // To use zeroCopy, use {buffer: aBuffer, zeroCopy: true} instead and destroy
|
|
* // aBuffer untill all access is done.
|
|
* const a = tf.tensor({buffer: aBuffer}, shape, dtype);
|
|
* const b = tf.tensor(bData, shape, dtype);
|
|
* const result = tf.add(a, b);
|
|
* result.print();
|
|
* a.dispose();
|
|
* b.dispose();
|
|
* result.dispose();
|
|
* aBuffer.destroy();
|
|
* await tf.setBackend(savedBackend);
|
|
* ```
|
|
* @param values The values of the tensor. Can be nested array of numbers,
|
|
* or a flat array, or a `TypedArray`(At the moment it supports Uint8Array,
|
|
* Uint8ClampedArray, Int32Array, Float32Array) data types, or a `WebGLData`
|
|
* object, or a `WebGPUData` object. If the values are strings, they will be
|
|
* encoded as utf-8 and kept as `Uint8Array[]`. If the values is a `WebGLData`
|
|
* object, the dtype could only be 'float32' or 'int32' and the object has to
|
|
* have: 1. texture, a `WebGLTexture`, the texture must share the same
|
|
* `WebGLRenderingContext` with TFJS's WebGL backend (you could create a custom
|
|
* WebGL backend from your texture's canvas) and the internal texture format
|
|
* for the input texture must be floating point or normalized integer; 2.
|
|
* height, the height of the texture; 3. width, the width of the texture; 4.
|
|
* channels, a non-empty subset of 'RGBA', indicating the values of which
|
|
* channels will be passed to the tensor, such as 'R' or 'BR' (The order of the
|
|
* channels affect the order of tensor values. ). (If the values passed from
|
|
* texture is less than the tensor size, zeros will be padded at the rear.). If
|
|
* the values is a `WebGPUData` object, the dtype could only be 'float32' or
|
|
* 'int32 and the object has to have: buffer, a `GPUBuffer`. The buffer must:
|
|
* 1. share the same `GPUDevice` with TFJS's WebGPU backend; 2. buffer.usage
|
|
* should at least support GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC; 3.
|
|
* buffer.size should not be smaller than the byte size of tensor shape.
|
|
* WebGPUData optionally supports zero copy by flag zeroCopy. When zeroCopy is
|
|
* false or undefined(default),this passing GPUBuffer can be destroyed after
|
|
* tensor is created. When zeroCopy is true, this GPUBuffer is bound directly
|
|
* by the tensor, so do not destroy this GPUBuffer until all access is done.
|
|
* @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'}
|
|
*/ parcelHelpers.export(exports, "tensor", ()=>tensor);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _tensorOpsUtil = require("./tensor_ops_util");
|
|
function tensor(values, shape, dtype) {
|
|
const inferredShape = (0, _tensorUtilEnv.inferShape)(values, dtype);
|
|
return (0, _tensorOpsUtil.makeTensor)(values, shape, inferredShape, dtype);
|
|
}
|
|
|
|
},{"../tensor_util_env":"6vfHI","./tensor_ops_util":"adYmX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"adYmX":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/** This is shared code across all tensor creation methods. */ parcelHelpers.export(exports, "makeTensor", ()=>makeTensor);
|
|
var _engine = require("../engine");
|
|
var _types = require("../types");
|
|
var _util = require("../util");
|
|
function makeTensor(values, shape, inferredShape, dtype) {
|
|
if (dtype == null) dtype = (0, _util.inferDtype)(values);
|
|
else if (dtype === "complex64") throw new Error(`Cannot construct a complex64 tensor directly. ` + `Please use tf.complex(real, imag).`);
|
|
if ((0, _types.isWebGPUData)(values) || (0, _types.isWebGLData)(values)) {
|
|
if (dtype !== "float32" && dtype !== "int32") throw new Error(`Creating tensor from GPU data only supports ` + `'float32'|'int32' dtype, while the dtype is ${dtype}.`);
|
|
return (0, _engine.ENGINE).backend.createTensorFromGPUData(values, shape || inferredShape, dtype);
|
|
}
|
|
if (!(0, _util.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");
|
|
// Verify that the shape matches the inferred shape.
|
|
if (shape != null) {
|
|
(0, _util.assertNonNegativeIntegerDimensions)(shape);
|
|
const providedSize = (0, _util.sizeFromShape)(shape);
|
|
const inferredSize = (0, _util.sizeFromShape)(inferredShape);
|
|
(0, _util.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 !== (0, _util.sizeFromShape)(shape.slice(i)) : true;
|
|
(0, _util.assert)(inferredShape[i] === shape[i] || !flatDimsDontMatch, ()=>`Error creating a new Tensor. Inferred shape ` + `(${inferredShape}) does not match the provided ` + `shape (${shape}). `);
|
|
}
|
|
}
|
|
if (!(0, _util.isTypedArray)(values) && !Array.isArray(values)) values = [
|
|
values
|
|
];
|
|
shape = shape || inferredShape;
|
|
values = dtype !== "string" ? (0, _util.toTypedArray)(values, dtype) : (0, _util.flatten)(values, [], true);
|
|
return (0, _engine.ENGINE).makeTensor(values, shape, dtype);
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../types":"10R8n","../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ixgVc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DTYPE_VALUE_SIZE_MAP", ()=>DTYPE_VALUE_SIZE_MAP);
|
|
const DTYPE_VALUE_SIZE_MAP = {
|
|
"float32": 4,
|
|
"float16": 2,
|
|
"int32": 4,
|
|
"uint16": 2,
|
|
"uint8": 1,
|
|
"bool": 1,
|
|
"complex64": 8
|
|
};
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gHH7C":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Wraps a list of ArrayBuffers into a `slice()`-able object without allocating
|
|
* a large ArrayBuffer.
|
|
*
|
|
* Allocating large ArrayBuffers (~2GB) can be unstable on Chrome. TFJS loads
|
|
* its weights as a list of (usually) 4MB ArrayBuffers and then slices the
|
|
* weight tensors out of them. For small models, it's safe to concatenate all
|
|
* the weight buffers into a single ArrayBuffer and then slice the weight
|
|
* tensors out of it, but for large models, a different approach is needed.
|
|
*/ parcelHelpers.export(exports, "CompositeArrayBuffer", ()=>CompositeArrayBuffer);
|
|
/**
|
|
* Search for an element of a sorted array.
|
|
*
|
|
* @param sortedArray The sorted array to search
|
|
* @param compare A function to compare the current value against the searched
|
|
* value. Return 0 on a match, negative if the searched value is less than
|
|
* the value passed to the function, and positive if the searched value is
|
|
* greater than the value passed to the function.
|
|
* @returns The index of the element, or -1 if it's not in the array.
|
|
*/ parcelHelpers.export(exports, "search", ()=>search);
|
|
var _util = require("../util");
|
|
class CompositeArrayBuffer {
|
|
/**
|
|
* Concatenate a number of ArrayBuffers into one.
|
|
*
|
|
* @param buffers An array of ArrayBuffers to concatenate, or a single
|
|
* ArrayBuffer.
|
|
* @returns Result of concatenating `buffers` in order.
|
|
*/ static join(buffers) {
|
|
return new CompositeArrayBuffer(buffers).slice();
|
|
}
|
|
constructor(buffers){
|
|
this.shards = [];
|
|
this.previousShardIndex = 0;
|
|
if (buffers == null) return;
|
|
// Normalize the `buffers` input to be `ArrayBuffer[]`.
|
|
if (!(buffers instanceof Array)) buffers = [
|
|
buffers
|
|
];
|
|
buffers = buffers.map((bufferOrTypedArray)=>{
|
|
if (_util.isTypedArray(bufferOrTypedArray)) return bufferOrTypedArray.buffer;
|
|
return bufferOrTypedArray;
|
|
});
|
|
// Skip setting up shards if there are no buffers.
|
|
if (buffers.length === 0) return;
|
|
this.bufferUniformSize = buffers[0].byteLength;
|
|
let start = 0;
|
|
for(let i = 0; i < buffers.length; i++){
|
|
const buffer = buffers[i];
|
|
// Check that all buffers except the last one have the same length.
|
|
if (i !== buffers.length - 1 && buffer.byteLength !== this.bufferUniformSize) // Unset the buffer uniform size, since the buffer sizes are not
|
|
// uniform.
|
|
this.bufferUniformSize = undefined;
|
|
// Create the shards, including their start and end points.
|
|
const end = start + buffer.byteLength;
|
|
this.shards.push({
|
|
buffer,
|
|
start,
|
|
end
|
|
});
|
|
start = end;
|
|
}
|
|
// Set the byteLenghth
|
|
if (this.shards.length === 0) this.byteLength = 0;
|
|
this.byteLength = this.shards[this.shards.length - 1].end;
|
|
}
|
|
slice(start = 0, end = this.byteLength) {
|
|
// If there are no shards, then the CompositeArrayBuffer was initialized
|
|
// with no data.
|
|
if (this.shards.length === 0) return new ArrayBuffer(0);
|
|
// NaN is treated as zero for slicing. This matches ArrayBuffer's behavior.
|
|
start = isNaN(Number(start)) ? 0 : start;
|
|
end = isNaN(Number(end)) ? 0 : end;
|
|
// Fix the bounds to within the array.
|
|
start = Math.max(0, start);
|
|
end = Math.min(this.byteLength, end);
|
|
if (end <= start) return new ArrayBuffer(0);
|
|
const startShardIndex = this.findShardForByte(start);
|
|
if (startShardIndex === -1) // This should not happen since the start and end indices are always
|
|
// within 0 and the composite array's length.
|
|
throw new Error(`Could not find start shard for byte ${start}`);
|
|
const size = end - start;
|
|
const outputBuffer = new ArrayBuffer(size);
|
|
const outputArray = new Uint8Array(outputBuffer);
|
|
let sliced = 0;
|
|
for(let i = startShardIndex; i < this.shards.length; i++){
|
|
const shard = this.shards[i];
|
|
const globalStart = start + sliced;
|
|
const localStart = globalStart - shard.start;
|
|
const outputStart = sliced;
|
|
const globalEnd = Math.min(end, shard.end);
|
|
const localEnd = globalEnd - shard.start;
|
|
const outputSlice = new Uint8Array(shard.buffer, localStart, localEnd - localStart);
|
|
outputArray.set(outputSlice, outputStart);
|
|
sliced += outputSlice.length;
|
|
if (end < shard.end) break;
|
|
}
|
|
return outputBuffer;
|
|
}
|
|
/**
|
|
* Get the index of the shard that contains the byte at `byteIndex`.
|
|
*/ findShardForByte(byteIndex) {
|
|
if (this.shards.length === 0 || byteIndex < 0 || byteIndex >= this.byteLength) return -1;
|
|
// If the buffers have a uniform size, compute the shard directly.
|
|
if (this.bufferUniformSize != null) {
|
|
this.previousShardIndex = Math.floor(byteIndex / this.bufferUniformSize);
|
|
return this.previousShardIndex;
|
|
}
|
|
// If the buffers don't have a uniform size, we need to search for the
|
|
// shard. That means we need a function to check where the byteIndex lies
|
|
// relative to a given shard.
|
|
function check(shard) {
|
|
if (byteIndex < shard.start) return -1;
|
|
if (byteIndex >= shard.end) return 1;
|
|
return 0;
|
|
}
|
|
// For efficiency, try the previous shard first.
|
|
if (check(this.shards[this.previousShardIndex]) === 0) return this.previousShardIndex;
|
|
// Otherwise, use a generic search function.
|
|
// This should almost never end up being used in practice since the weight
|
|
// entries should always be in order.
|
|
const index = search(this.shards, check);
|
|
if (index === -1) return -1;
|
|
this.previousShardIndex = index;
|
|
return this.previousShardIndex;
|
|
}
|
|
}
|
|
function search(sortedArray, compare) {
|
|
// Binary search
|
|
let min = 0;
|
|
let max = sortedArray.length;
|
|
while(min <= max){
|
|
const middle = Math.floor((max - min) / 2) + min;
|
|
const side = compare(sortedArray[middle]);
|
|
if (side === 0) return middle;
|
|
else if (side < 0) max = middle;
|
|
else min = middle + 1;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eO1Ja":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Enables production mode which disables correctness checks in favor of
|
|
* performance.
|
|
*
|
|
* @doc {heading: 'Environment'}
|
|
*/ parcelHelpers.export(exports, "enableProdMode", ()=>enableProdMode);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "enableDebugMode", ()=>enableDebugMode);
|
|
/** Globally disables deprecation warnings */ parcelHelpers.export(exports, "disableDeprecationWarnings", ()=>disableDeprecationWarnings);
|
|
/** Warn users about deprecated functionality. */ parcelHelpers.export(exports, "deprecationWarn", ()=>deprecationWarn);
|
|
/**
|
|
* Dispose all variables kept in backend engine.
|
|
*
|
|
* @doc {heading: 'Environment'}
|
|
*/ parcelHelpers.export(exports, "disposeVariables", ()=>disposeVariables);
|
|
/**
|
|
* It returns the global engine that keeps track of all tensors and backends.
|
|
*
|
|
* @doc {heading: 'Environment'}
|
|
*/ parcelHelpers.export(exports, "engine", ()=>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'}
|
|
*/ parcelHelpers.export(exports, "memory", ()=>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.
|
|
* - `kernelNames`: an array of unique strings with just the names of the
|
|
* kernels in the `kernels` array.
|
|
*
|
|
* ```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'}
|
|
*/ parcelHelpers.export(exports, "profile", ()=>profile);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "tidy", ()=>tidy);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "dispose", ()=>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'}
|
|
*/ parcelHelpers.export(exports, "keep", ()=>keep);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "time", ()=>time);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "setBackend", ()=>setBackend);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "ready", ()=>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'}
|
|
*/ parcelHelpers.export(exports, "getBackend", ()=>getBackend);
|
|
/**
|
|
* Removes a backend and the registered factory.
|
|
*
|
|
* @doc {heading: 'Backends'}
|
|
*/ parcelHelpers.export(exports, "removeBackend", ()=>removeBackend);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "findBackend", ()=>findBackend);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "findBackendFactory", ()=>findBackendFactory);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "registerBackend", ()=>registerBackend);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "backend", ()=>backend);
|
|
/**
|
|
* Sets the global platform.
|
|
*
|
|
* @param platformName The name of this platform.
|
|
* @param platform A platform implementation.
|
|
*/ parcelHelpers.export(exports, "setPlatform", ()=>setPlatform);
|
|
var _engine = require("./engine");
|
|
var _environment = require("./environment");
|
|
var _tensor = require("./tensor");
|
|
var _tensorUtil = require("./tensor_util");
|
|
function enableProdMode() {
|
|
(0, _environment.env)().set("PROD", true);
|
|
}
|
|
function enableDebugMode() {
|
|
(0, _environment.env)().set("DEBUG", true);
|
|
}
|
|
function disableDeprecationWarnings() {
|
|
(0, _environment.env)().set("DEPRECATION_WARNINGS_ENABLED", false);
|
|
console.warn(`TensorFlow.js deprecation warnings have been disabled.`);
|
|
}
|
|
function deprecationWarn(msg) {
|
|
if ((0, _environment.env)().getBool("DEPRECATION_WARNINGS_ENABLED")) console.warn(msg + " You can disable deprecation warnings with " + "tf.disableDeprecationWarnings().");
|
|
}
|
|
(0, _tensor.setDeprecationWarningFn)(deprecationWarn);
|
|
function disposeVariables() {
|
|
(0, _engine.ENGINE).disposeVariables();
|
|
}
|
|
function engine() {
|
|
return 0, _engine.ENGINE;
|
|
}
|
|
function memory() {
|
|
return (0, _engine.ENGINE).memory();
|
|
}
|
|
function profile(f) {
|
|
return (0, _engine.ENGINE).profile(f);
|
|
}
|
|
function tidy(nameOrFn, fn) {
|
|
return (0, _engine.ENGINE).tidy(nameOrFn, fn);
|
|
}
|
|
function dispose(container) {
|
|
const tensors = (0, _tensorUtil.getTensorsInContainer)(container);
|
|
tensors.forEach((tensor)=>tensor.dispose());
|
|
}
|
|
function keep(result) {
|
|
return (0, _engine.ENGINE).keep(result);
|
|
}
|
|
function time(f) {
|
|
return (0, _engine.ENGINE).time(f);
|
|
}
|
|
function setBackend(backendName) {
|
|
return (0, _engine.ENGINE).setBackend(backendName);
|
|
}
|
|
function ready() {
|
|
return (0, _engine.ENGINE).ready();
|
|
}
|
|
function getBackend() {
|
|
return (0, _engine.ENGINE).backendName;
|
|
}
|
|
function removeBackend(name) {
|
|
(0, _engine.ENGINE).removeBackend(name);
|
|
}
|
|
function findBackend(name) {
|
|
return (0, _engine.ENGINE).findBackend(name);
|
|
}
|
|
function findBackendFactory(name) {
|
|
return (0, _engine.ENGINE).findBackendFactory(name);
|
|
}
|
|
function registerBackend(name, factory, priority = 1) {
|
|
return (0, _engine.ENGINE).registerBackend(name, factory, priority);
|
|
}
|
|
function backend() {
|
|
return (0, _engine.ENGINE).backend;
|
|
}
|
|
function setPlatform(platformName, platform) {
|
|
(0, _environment.env)().setPlatform(platformName, platform);
|
|
}
|
|
|
|
},{"./engine":"1g2qo","./environment":"dXmHm","./tensor":"cJNoh","./tensor_util":"8jzJG","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"btpsw":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "IORouterRegistry", ()=>IORouterRegistry);
|
|
parcelHelpers.export(exports, "registerSaveRouter", ()=>registerSaveRouter);
|
|
parcelHelpers.export(exports, "registerLoadRouter", ()=>registerLoadRouter);
|
|
parcelHelpers.export(exports, "getSaveHandlers", ()=>getSaveHandlers);
|
|
parcelHelpers.export(exports, "getLoadHandlers", ()=>getLoadHandlers);
|
|
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);
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c3TPR":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Purge all tensorflow.js-saved model artifacts from local storage.
|
|
*
|
|
* @returns Paths of the models purged.
|
|
*/ parcelHelpers.export(exports, "purgeLocalStorageArtifacts", ()=>purgeLocalStorageArtifacts);
|
|
parcelHelpers.export(exports, "BrowserLocalStorage", ()=>BrowserLocalStorage);
|
|
parcelHelpers.export(exports, "localStorageRouter", ()=>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`.
|
|
*/ parcelHelpers.export(exports, "browserLocalStorage", ()=>browserLocalStorage);
|
|
parcelHelpers.export(exports, "BrowserLocalStorageManager", ()=>BrowserLocalStorageManager);
|
|
var _flags = require("../flags");
|
|
var _environment = require("../environment");
|
|
var _util = require("../util");
|
|
var _ioUtils = require("./io_utils");
|
|
var _compositeArrayBuffer = require("./composite_array_buffer");
|
|
var _routerRegistry = require("./router_registry");
|
|
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";
|
|
function purgeLocalStorageArtifacts() {
|
|
if (!(0, _environment.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)
|
|
};
|
|
}
|
|
function removeItems(keys) {
|
|
for (const key of Object.values(keys))window.localStorage.removeItem(key);
|
|
}
|
|
/**
|
|
* 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 maybeStripScheme(key) {
|
|
return key.startsWith(BrowserLocalStorage.URL_SCHEME) ? key.slice(BrowserLocalStorage.URL_SCHEME.length) : key;
|
|
}
|
|
/**
|
|
* IOHandler subclass: Browser Local Storage.
|
|
*
|
|
* See the doc string to `browserLocalStorage` for more details.
|
|
*/ class BrowserLocalStorage {
|
|
constructor(modelPath){
|
|
if (!(0, _environment.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 = (0, _ioUtils.getModelArtifactsInfoForJSON)(modelArtifacts);
|
|
// TODO(mattsoulanille): Support saving models over 2GB that exceed
|
|
// Chrome's ArrayBuffer size limit.
|
|
const weightBuffer = (0, _compositeArrayBuffer.CompositeArrayBuffer).join(modelArtifacts.weightData);
|
|
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, (0, _ioUtils.arrayBufferToBase64String)(weightBuffer));
|
|
// Note that JSON.stringify doesn't write out keys that have undefined
|
|
// values, so for some keys, we set undefined instead of a null-ish
|
|
// value.
|
|
const metadata = {
|
|
format: modelArtifacts.format,
|
|
generatedBy: modelArtifacts.generatedBy,
|
|
convertedBy: modelArtifacts.convertedBy,
|
|
signature: modelArtifacts.signature != null ? modelArtifacts.signature : undefined,
|
|
userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ? modelArtifacts.userDefinedMetadata : undefined,
|
|
modelInitializer: modelArtifacts.modelInitializer != null ? modelArtifacts.modelInitializer : undefined,
|
|
initializerSignature: modelArtifacts.initializerSignature != null ? modelArtifacts.initializerSignature : undefined,
|
|
trainingConfig: modelArtifacts.trainingConfig != null ? modelArtifacts.trainingConfig : undefined
|
|
};
|
|
this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));
|
|
return {
|
|
modelArtifactsInfo
|
|
};
|
|
} catch (err) {
|
|
// If saving failed, clean up all items saved so far.
|
|
removeItems(this.keys);
|
|
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;
|
|
if (metadata.signature != null) out.signature = metadata.signature;
|
|
if (metadata.userDefinedMetadata != null) out.userDefinedMetadata = metadata.userDefinedMetadata;
|
|
if (metadata.modelInitializer != null) out.modelInitializer = metadata.modelInitializer;
|
|
if (metadata.initializerSignature != null) out.initializerSignature = metadata.initializerSignature;
|
|
if (metadata.trainingConfig != null) out.trainingConfig = metadata.trainingConfig;
|
|
}
|
|
// 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 = (0, _ioUtils.base64StringToArrayBuffer)(weightDataBase64);
|
|
return out;
|
|
}
|
|
}
|
|
BrowserLocalStorage.URL_SCHEME = "localstorage://";
|
|
const localStorageRouter = (url)=>{
|
|
if (!(0, _environment.env)().getBool("IS_BROWSER")) return null;
|
|
else {
|
|
if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length));
|
|
else return null;
|
|
}
|
|
};
|
|
(0, _routerRegistry.IORouterRegistry).registerSaveRouter(localStorageRouter);
|
|
(0, _routerRegistry.IORouterRegistry).registerLoadRouter(localStorageRouter);
|
|
function browserLocalStorage(modelPath) {
|
|
return new BrowserLocalStorage(modelPath);
|
|
}
|
|
class BrowserLocalStorageManager {
|
|
constructor(){
|
|
(0, _util.assert)((0, _environment.env)().getBool("IS_BROWSER"), ()=>"Current environment is not a web browser");
|
|
(0, _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 = 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));
|
|
removeItems(keys);
|
|
return info;
|
|
}
|
|
}
|
|
|
|
},{"../flags":"5yJGC","../environment":"dXmHm","../util":"ctavo","./io_utils":"hW5iQ","./composite_array_buffer":"gHH7C","./router_registry":"btpsw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iB0Mw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ModelStoreManagerRegistry", ()=>ModelStoreManagerRegistry);
|
|
parcelHelpers.export(exports, "moveModel", ()=>moveModel);
|
|
parcelHelpers.export(exports, "copyModel", ()=>copyModel);
|
|
parcelHelpers.export(exports, "removeModel", ()=>removeModel);
|
|
parcelHelpers.export(exports, "listModels", ()=>listModels);
|
|
var _util = require("../util");
|
|
var _routerRegistry = require("./router_registry");
|
|
const URL_SCHEME_SUFFIX = "://";
|
|
class ModelStoreManagerRegistry {
|
|
constructor(){
|
|
this.managers = {};
|
|
}
|
|
static getInstance() {
|
|
if (ModelStoreManagerRegistry.instance == null) ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();
|
|
return 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) {
|
|
(0, _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));
|
|
(0, _util.assert)(scheme.length > 0, ()=>"scheme must not be an empty string.");
|
|
const registry = ModelStoreManagerRegistry.getInstance();
|
|
(0, _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 = ModelStoreManagerRegistry.getInstance().managers[scheme];
|
|
if (manager == null) throw new Error(`Cannot find model manager for scheme '${scheme}'`);
|
|
return manager;
|
|
}
|
|
static getSchemes() {
|
|
return Object.keys(ModelStoreManagerRegistry.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: ` + `${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) {
|
|
(0, _util.assert)(sourceURL !== destURL, ()=>`Old path and new path are the same: '${sourceURL}'`);
|
|
const loadHandlers = (0, _routerRegistry.IORouterRegistry).getLoadHandlers(sourceURL);
|
|
(0, _util.assert)(loadHandlers.length > 0, ()=>`Copying failed because no load handler is found for source URL ${sourceURL}.`);
|
|
(0, _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 = (0, _routerRegistry.IORouterRegistry).getSaveHandlers(destURL);
|
|
(0, _util.assert)(saveHandlers.length > 0, ()=>`Copying failed because no save handler is found for destination ` + `URL ${destURL}.`);
|
|
(0, _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 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 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 = ModelStoreManagerRegistry.getSchemes();
|
|
const out = {};
|
|
for (const scheme of schemes){
|
|
const schemeOut = await 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 registered 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 = 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);
|
|
}
|
|
|
|
},{"../util":"ctavo","./router_registry":"btpsw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2Z7zs":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getNodeFetch", ()=>getNodeFetch);
|
|
// These getters and setters are for testing so we don't export a mutable
|
|
// variable.
|
|
parcelHelpers.export(exports, "resetSystemFetch", ()=>resetSystemFetch);
|
|
parcelHelpers.export(exports, "setSystemFetch", ()=>setSystemFetch);
|
|
parcelHelpers.export(exports, "getSystemFetch", ()=>getSystemFetch);
|
|
parcelHelpers.export(exports, "PlatformNode", ()=>PlatformNode);
|
|
var _environment = require("../environment");
|
|
var process = require("9eae209353a3d608");
|
|
const getNodeFetch = {
|
|
// tslint:disable-next-line:no-require-imports
|
|
importFetch: ()=>require("dfcdb939bb56fbb8")
|
|
};
|
|
let systemFetch;
|
|
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 = require("3818a9dc927c4605");
|
|
// 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 ((0, _environment.env)().global.fetch != null) return (0, _environment.env)().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);
|
|
}
|
|
isTypedArray(a) {
|
|
return this.util.types.isFloat32Array(a) || this.util.types.isInt32Array(a) || this.util.types.isUint8Array(a) || this.util.types.isUint8ClampedArray(a);
|
|
}
|
|
}
|
|
if ((0, _environment.env)().get("IS_NODE") && !(0, _environment.env)().get("IS_BROWSER")) (0, _environment.env)().setPlatform("node", new PlatformNode());
|
|
|
|
},{"9eae209353a3d608":"h0aBX","../environment":"dXmHm","dfcdb939bb56fbb8":"1kJBy","3818a9dc927c4605":"1kJBy","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1kJBy":[function(require,module,exports) {
|
|
"use strict";
|
|
|
|
},{}],"dYyY7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "buffer", ()=>buffer);
|
|
var _tensor = require("../tensor");
|
|
var _util = require("../util");
|
|
function buffer(shape, dtype = "float32", values) {
|
|
dtype = dtype || "float32";
|
|
_util.assertNonNegativeIntegerDimensions(shape);
|
|
return new (0, _tensor.TensorBuffer)(shape, dtype, values);
|
|
}
|
|
|
|
},{"../tensor":"cJNoh","../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b4VDA":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cast", ()=>cast);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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 inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
dtype
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Cast), inputs, attrs);
|
|
}
|
|
const cast = /* @__PURE__ */ (0, _operation.op)({
|
|
cast_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jmQ7S":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "clone", ()=>clone);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "clone", "string_or_numeric");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
// Note this op is called tf.identity in python. Hence the kernel name used
|
|
// here.
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Identity), inputs);
|
|
}
|
|
const clone = /* @__PURE__ */ (0, _operation.op)({
|
|
clone_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5RyfW":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ /**
|
|
* 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'}
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "print", ()=>print);
|
|
function print(x, verbose = false) {
|
|
console.log(x.toString(verbose));
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"k7xLP":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "registerOptimizers", ()=>registerOptimizers);
|
|
var _adadeltaOptimizer = require("./adadelta_optimizer");
|
|
var _adagradOptimizer = require("./adagrad_optimizer");
|
|
var _adamOptimizer = require("./adam_optimizer");
|
|
var _adamaxOptimizer = require("./adamax_optimizer");
|
|
var _momentumOptimizer = require("./momentum_optimizer");
|
|
var _rmspropOptimizer = require("./rmsprop_optimizer");
|
|
var _sgdOptimizer = require("./sgd_optimizer");
|
|
var _serialization = require("../serialization");
|
|
const OPTIMIZERS = [
|
|
(0, _adadeltaOptimizer.AdadeltaOptimizer),
|
|
(0, _adagradOptimizer.AdagradOptimizer),
|
|
(0, _adamOptimizer.AdamOptimizer),
|
|
(0, _adamaxOptimizer.AdamaxOptimizer),
|
|
(0, _momentumOptimizer.MomentumOptimizer),
|
|
(0, _rmspropOptimizer.RMSPropOptimizer),
|
|
(0, _sgdOptimizer.SGDOptimizer)
|
|
];
|
|
function registerOptimizers() {
|
|
for (const optimizer of OPTIMIZERS)(0, _serialization.registerClass)(optimizer);
|
|
}
|
|
|
|
},{"./adadelta_optimizer":"a2jsK","./adagrad_optimizer":"ddRDd","./adam_optimizer":"5uefH","./adamax_optimizer":"72DSu","./momentum_optimizer":"bKhX1","./rmsprop_optimizer":"66Wvy","./sgd_optimizer":"4dxnr","../serialization":"dv6JX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a2jsK":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/** @doclink Optimizer */ parcelHelpers.export(exports, "AdadeltaOptimizer", ()=>AdadeltaOptimizer);
|
|
var _engine = require("../engine");
|
|
var _globals = require("../globals");
|
|
var _add = require("../ops/add");
|
|
var _div = require("../ops/div");
|
|
var _mul = require("../ops/mul");
|
|
var _ops = require("../ops/ops");
|
|
var _square = require("../ops/square");
|
|
var _zerosLike = require("../ops/zeros_like");
|
|
var _optimizer = require("./optimizer");
|
|
class AdadeltaOptimizer extends (0, _optimizer.Optimizer) {
|
|
/** @nocollapse */ static get className() {
|
|
// Name matters for Python compatibility.
|
|
// This is a getter instead of a property because when it's a property, it
|
|
// prevents the entire class from being tree-shaken.
|
|
return "Adadelta";
|
|
}
|
|
constructor(learningRate, rho, epsilon = null){
|
|
super();
|
|
this.learningRate = learningRate;
|
|
this.rho = rho;
|
|
this.epsilon = epsilon;
|
|
this.accumulatedGrads = [];
|
|
this.accumulatedUpdates = [];
|
|
if (epsilon == null) this.epsilon = (0, _engine.ENGINE).backend.epsilon();
|
|
}
|
|
applyGradients(variableGradients) {
|
|
const variableNames = Array.isArray(variableGradients) ? variableGradients.map((item)=>item.name) : Object.keys(variableGradients);
|
|
variableNames.forEach((name, i)=>{
|
|
const value = (0, _engine.ENGINE).registeredVariables[name];
|
|
const trainable = false;
|
|
if (this.accumulatedGrads[i] == null) this.accumulatedGrads[i] = {
|
|
originalName: `${name}/accum_grad`,
|
|
variable: (0, _globals.tidy)(()=>(0, _zerosLike.zerosLike)(value).variable(trainable))
|
|
};
|
|
if (this.accumulatedUpdates[i] == null) this.accumulatedUpdates[i] = {
|
|
originalName: `${name}/accum_var`,
|
|
variable: (0, _globals.tidy)(()=>(0, _zerosLike.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;
|
|
(0, _globals.tidy)(()=>{
|
|
const newAccumulatedGrad = (0, _add.add)((0, _mul.mul)(accumulatedGrad, this.rho), (0, _mul.mul)((0, _square.square)(gradient), 1 - this.rho));
|
|
const updates = (0, _mul.mul)((0, _div.div)((0, _ops.sqrt)((0, _add.add)(accumulatedUpdate, this.epsilon)), (0, _ops.sqrt)((0, _add.add)(accumulatedGrad, this.epsilon))), gradient);
|
|
const newAccumulatedUpdate = (0, _add.add)((0, _mul.mul)(accumulatedUpdate, this.rho), (0, _mul.mul)((0, _square.square)(updates), 1 - this.rho));
|
|
accumulatedGrad.assign(newAccumulatedGrad);
|
|
accumulatedUpdate.assign(newAccumulatedUpdate);
|
|
const newValue = (0, _add.add)((0, _mul.mul)(updates, -this.learningRate), value);
|
|
value.assign(newValue);
|
|
});
|
|
});
|
|
this.incrementIterations();
|
|
}
|
|
dispose() {
|
|
if (this.accumulatedUpdates != null) {
|
|
(0, _globals.dispose)(this.accumulatedGrads.map((v)=>v.variable));
|
|
(0, _globals.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"]);
|
|
}
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../globals":"eO1Ja","../ops/add":"aynh7","../ops/div":"5ZT1h","../ops/mul":"fOWrC","../ops/ops":"13k1e","../ops/square":"cOosW","../ops/zeros_like":"1Xjct","./optimizer":"1b69z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aynh7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "add", ()=>add);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "add");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "add");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Add), inputs);
|
|
}
|
|
const add = /* @__PURE__ */ (0, _operation.op)({
|
|
add_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5ZT1h":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "div", ()=>div);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _floorDiv = require("./floorDiv");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "div");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "div");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
if ($a.dtype === "int32" && $b.dtype === "int32") return (0, _floorDiv.floorDiv)($a, $b);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
const attrs = {};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.RealDiv), inputs, attrs);
|
|
}
|
|
const div = /* @__PURE__ */ (0, _operation.op)({
|
|
div_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./floorDiv":"jboDF","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jboDF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "floorDiv", ()=>floorDiv);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "floorDiv");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "floorDiv");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.FloorDiv), inputs);
|
|
}
|
|
const floorDiv = /* @__PURE__ */ (0, _operation.op)({
|
|
floorDiv_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fOWrC":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mul", ()=>mul);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "mul");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "mul");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Multiply), inputs);
|
|
}
|
|
const mul = /* @__PURE__ */ (0, _operation.op)({
|
|
mul_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"13k1e":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // Modularized ops.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "abs", ()=>(0, _abs.abs));
|
|
parcelHelpers.export(exports, "acos", ()=>(0, _acos.acos));
|
|
parcelHelpers.export(exports, "acosh", ()=>(0, _acosh.acosh));
|
|
parcelHelpers.export(exports, "add", ()=>(0, _add.add));
|
|
parcelHelpers.export(exports, "addN", ()=>(0, _addN.addN));
|
|
parcelHelpers.export(exports, "all", ()=>(0, _all.all));
|
|
parcelHelpers.export(exports, "any", ()=>(0, _any.any));
|
|
parcelHelpers.export(exports, "argMax", ()=>(0, _argMax.argMax));
|
|
parcelHelpers.export(exports, "argMin", ()=>(0, _argMin.argMin));
|
|
parcelHelpers.export(exports, "asin", ()=>(0, _asin.asin));
|
|
parcelHelpers.export(exports, "asinh", ()=>(0, _asinh.asinh));
|
|
parcelHelpers.export(exports, "atan", ()=>(0, _atan.atan));
|
|
parcelHelpers.export(exports, "atan2", ()=>(0, _atan2.atan2));
|
|
parcelHelpers.export(exports, "atanh", ()=>(0, _atanh.atanh));
|
|
parcelHelpers.export(exports, "avgPool", ()=>(0, _avgPool.avgPool));
|
|
parcelHelpers.export(exports, "avgPool3d", ()=>(0, _avgPool3D.avgPool3d));
|
|
parcelHelpers.export(exports, "basicLSTMCell", ()=>(0, _basicLstmCell.basicLSTMCell));
|
|
parcelHelpers.export(exports, "batchToSpaceND", ()=>(0, _batchToSpaceNd.batchToSpaceND));
|
|
parcelHelpers.export(exports, "batchNorm", ()=>(0, _batchnorm.batchNorm));
|
|
parcelHelpers.export(exports, "batchNorm2d", ()=>(0, _batchnorm2D.batchNorm2d));
|
|
parcelHelpers.export(exports, "batchNorm3d", ()=>(0, _batchnorm3D.batchNorm3d));
|
|
parcelHelpers.export(exports, "batchNorm4d", ()=>(0, _batchnorm4D.batchNorm4d));
|
|
parcelHelpers.export(exports, "bincount", ()=>(0, _bincount.bincount));
|
|
parcelHelpers.export(exports, "bitwiseAnd", ()=>(0, _bitwiseAnd.bitwiseAnd));
|
|
parcelHelpers.export(exports, "broadcastArgs", ()=>(0, _broadcastArgs.broadcastArgs));
|
|
parcelHelpers.export(exports, "broadcastTo", ()=>(0, _broadcastTo.broadcastTo));
|
|
parcelHelpers.export(exports, "buffer", ()=>(0, _buffer.buffer));
|
|
parcelHelpers.export(exports, "cast", ()=>(0, _cast.cast));
|
|
parcelHelpers.export(exports, "ceil", ()=>(0, _ceil.ceil));
|
|
parcelHelpers.export(exports, "clipByValue", ()=>(0, _clipByValue.clipByValue));
|
|
parcelHelpers.export(exports, "clone", ()=>(0, _clone.clone));
|
|
parcelHelpers.export(exports, "complex", ()=>(0, _complex.complex));
|
|
parcelHelpers.export(exports, "concat", ()=>(0, _concat.concat));
|
|
parcelHelpers.export(exports, "concat1d", ()=>(0, _concat1D.concat1d));
|
|
parcelHelpers.export(exports, "concat2d", ()=>(0, _concat2D.concat2d));
|
|
parcelHelpers.export(exports, "concat3d", ()=>(0, _concat3D.concat3d));
|
|
parcelHelpers.export(exports, "concat4d", ()=>(0, _concat4D.concat4d));
|
|
parcelHelpers.export(exports, "conv1d", ()=>(0, _conv1D.conv1d));
|
|
parcelHelpers.export(exports, "conv2d", ()=>(0, _conv2D.conv2d));
|
|
parcelHelpers.export(exports, "conv2dTranspose", ()=>(0, _conv2DTranspose.conv2dTranspose));
|
|
parcelHelpers.export(exports, "conv3d", ()=>(0, _conv3D.conv3d));
|
|
parcelHelpers.export(exports, "conv3dTranspose", ()=>(0, _conv3DTranspose.conv3dTranspose));
|
|
parcelHelpers.export(exports, "cos", ()=>(0, _cos.cos));
|
|
parcelHelpers.export(exports, "cosh", ()=>(0, _cosh.cosh));
|
|
parcelHelpers.export(exports, "cumprod", ()=>(0, _cumprod.cumprod));
|
|
parcelHelpers.export(exports, "cumsum", ()=>(0, _cumsum.cumsum));
|
|
parcelHelpers.export(exports, "denseBincount", ()=>(0, _denseBincount.denseBincount));
|
|
parcelHelpers.export(exports, "depthToSpace", ()=>(0, _depthToSpace.depthToSpace));
|
|
parcelHelpers.export(exports, "depthwiseConv2d", ()=>(0, _depthwiseConv2D.depthwiseConv2d));
|
|
parcelHelpers.export(exports, "diag", ()=>(0, _diag.diag));
|
|
parcelHelpers.export(exports, "dilation2d", ()=>(0, _dilation2D.dilation2d));
|
|
parcelHelpers.export(exports, "div", ()=>(0, _div.div));
|
|
parcelHelpers.export(exports, "divNoNan", ()=>(0, _divNoNan.divNoNan));
|
|
parcelHelpers.export(exports, "dot", ()=>(0, _dot.dot));
|
|
parcelHelpers.export(exports, "einsum", ()=>(0, _einsum.einsum));
|
|
parcelHelpers.export(exports, "elu", ()=>(0, _elu.elu));
|
|
parcelHelpers.export(exports, "ensureShape", ()=>(0, _ensureShape.ensureShape));
|
|
parcelHelpers.export(exports, "equal", ()=>(0, _equal.equal));
|
|
parcelHelpers.export(exports, "erf", ()=>(0, _erf.erf));
|
|
parcelHelpers.export(exports, "euclideanNorm", ()=>(0, _euclideanNorm.euclideanNorm));
|
|
parcelHelpers.export(exports, "exp", ()=>(0, _exp.exp));
|
|
parcelHelpers.export(exports, "expandDims", ()=>(0, _expandDims.expandDims));
|
|
parcelHelpers.export(exports, "expm1", ()=>(0, _expm1.expm1));
|
|
parcelHelpers.export(exports, "eye", ()=>(0, _eye.eye));
|
|
parcelHelpers.export(exports, "fill", ()=>(0, _fill.fill));
|
|
parcelHelpers.export(exports, "floor", ()=>(0, _floor.floor));
|
|
parcelHelpers.export(exports, "floorDiv", ()=>(0, _floorDiv.floorDiv));
|
|
parcelHelpers.export(exports, "gather", ()=>(0, _gather.gather));
|
|
parcelHelpers.export(exports, "greater", ()=>(0, _greater.greater));
|
|
parcelHelpers.export(exports, "greaterEqual", ()=>(0, _greaterEqual.greaterEqual));
|
|
parcelHelpers.export(exports, "imag", ()=>(0, _imag.imag));
|
|
parcelHelpers.export(exports, "isFinite", ()=>(0, _isFinite.isFinite));
|
|
parcelHelpers.export(exports, "isInf", ()=>(0, _isInf.isInf));
|
|
parcelHelpers.export(exports, "isNaN", ()=>(0, _isNan.isNaN));
|
|
parcelHelpers.export(exports, "leakyRelu", ()=>(0, _leakyRelu.leakyRelu));
|
|
parcelHelpers.export(exports, "less", ()=>(0, _less.less));
|
|
parcelHelpers.export(exports, "lessEqual", ()=>(0, _lessEqual.lessEqual));
|
|
parcelHelpers.export(exports, "linspace", ()=>(0, _linspace.linspace));
|
|
parcelHelpers.export(exports, "localResponseNormalization", ()=>(0, _localResponseNormalization.localResponseNormalization));
|
|
parcelHelpers.export(exports, "log", ()=>(0, _log.log));
|
|
parcelHelpers.export(exports, "log1p", ()=>(0, _log1P.log1p));
|
|
parcelHelpers.export(exports, "logSigmoid", ()=>(0, _logSigmoid.logSigmoid));
|
|
parcelHelpers.export(exports, "logSoftmax", ()=>(0, _logSoftmax.logSoftmax));
|
|
parcelHelpers.export(exports, "logSumExp", ()=>(0, _logSumExp.logSumExp));
|
|
parcelHelpers.export(exports, "logicalAnd", ()=>(0, _logicalAnd.logicalAnd));
|
|
parcelHelpers.export(exports, "logicalNot", ()=>(0, _logicalNot.logicalNot));
|
|
parcelHelpers.export(exports, "logicalOr", ()=>(0, _logicalOr.logicalOr));
|
|
parcelHelpers.export(exports, "logicalXor", ()=>(0, _logicalXor.logicalXor));
|
|
parcelHelpers.export(exports, "lowerBound", ()=>(0, _lowerBound.lowerBound));
|
|
parcelHelpers.export(exports, "matMul", ()=>(0, _matMul.matMul));
|
|
parcelHelpers.export(exports, "max", ()=>(0, _max.max));
|
|
parcelHelpers.export(exports, "maxPool", ()=>(0, _maxPool.maxPool));
|
|
parcelHelpers.export(exports, "maxPool3d", ()=>(0, _maxPool3D.maxPool3d));
|
|
parcelHelpers.export(exports, "maxPoolWithArgmax", ()=>(0, _maxPoolWithArgmax.maxPoolWithArgmax));
|
|
parcelHelpers.export(exports, "maximum", ()=>(0, _maximum.maximum));
|
|
parcelHelpers.export(exports, "mean", ()=>(0, _mean.mean));
|
|
parcelHelpers.export(exports, "meshgrid", ()=>(0, _meshgrid.meshgrid));
|
|
parcelHelpers.export(exports, "min", ()=>(0, _min.min));
|
|
parcelHelpers.export(exports, "minimum", ()=>(0, _minimum.minimum));
|
|
parcelHelpers.export(exports, "mirrorPad", ()=>(0, _mirrorPad.mirrorPad));
|
|
parcelHelpers.export(exports, "mod", ()=>(0, _mod.mod));
|
|
parcelHelpers.export(exports, "moments", ()=>(0, _moments.moments));
|
|
parcelHelpers.export(exports, "mul", ()=>(0, _mul.mul));
|
|
parcelHelpers.export(exports, "multiRNNCell", ()=>(0, _multiRnnCell.multiRNNCell));
|
|
parcelHelpers.export(exports, "multinomial", ()=>(0, _multinomial.multinomial));
|
|
parcelHelpers.export(exports, "neg", ()=>(0, _neg.neg));
|
|
parcelHelpers.export(exports, "notEqual", ()=>(0, _notEqual.notEqual));
|
|
parcelHelpers.export(exports, "oneHot", ()=>(0, _oneHot.oneHot));
|
|
parcelHelpers.export(exports, "ones", ()=>(0, _ones.ones));
|
|
parcelHelpers.export(exports, "onesLike", ()=>(0, _onesLike.onesLike));
|
|
parcelHelpers.export(exports, "outerProduct", ()=>(0, _outerProduct.outerProduct));
|
|
parcelHelpers.export(exports, "pad", ()=>(0, _pad.pad));
|
|
parcelHelpers.export(exports, "pad1d", ()=>(0, _pad1D.pad1d));
|
|
parcelHelpers.export(exports, "pad2d", ()=>(0, _pad2D.pad2d));
|
|
parcelHelpers.export(exports, "pad3d", ()=>(0, _pad3D.pad3d));
|
|
parcelHelpers.export(exports, "pad4d", ()=>(0, _pad4D.pad4d));
|
|
parcelHelpers.export(exports, "pool", ()=>(0, _pool.pool));
|
|
parcelHelpers.export(exports, "pow", ()=>(0, _pow.pow));
|
|
parcelHelpers.export(exports, "prelu", ()=>(0, _prelu.prelu));
|
|
parcelHelpers.export(exports, "print", ()=>(0, _print.print));
|
|
parcelHelpers.export(exports, "prod", ()=>(0, _prod.prod));
|
|
parcelHelpers.export(exports, "raggedGather", ()=>(0, _raggedGather.raggedGather));
|
|
parcelHelpers.export(exports, "raggedRange", ()=>(0, _raggedRange.raggedRange));
|
|
parcelHelpers.export(exports, "raggedTensorToTensor", ()=>(0, _raggedTensorToTensor.raggedTensorToTensor));
|
|
parcelHelpers.export(exports, "rand", ()=>(0, _rand.rand));
|
|
parcelHelpers.export(exports, "randomGamma", ()=>(0, _randomGamma.randomGamma));
|
|
parcelHelpers.export(exports, "randomNormal", ()=>(0, _randomNormal.randomNormal));
|
|
parcelHelpers.export(exports, "randomStandardNormal", ()=>(0, _randomStandardNormal.randomStandardNormal));
|
|
parcelHelpers.export(exports, "randomUniform", ()=>(0, _randomUniform.randomUniform));
|
|
parcelHelpers.export(exports, "randomUniformInt", ()=>(0, _randomUniformInt.randomUniformInt));
|
|
parcelHelpers.export(exports, "range", ()=>(0, _range.range));
|
|
parcelHelpers.export(exports, "real", ()=>(0, _real.real));
|
|
parcelHelpers.export(exports, "reciprocal", ()=>(0, _reciprocal.reciprocal));
|
|
parcelHelpers.export(exports, "relu", ()=>(0, _relu.relu));
|
|
parcelHelpers.export(exports, "relu6", ()=>(0, _relu6.relu6));
|
|
parcelHelpers.export(exports, "reshape", ()=>(0, _reshape.reshape));
|
|
parcelHelpers.export(exports, "reverse", ()=>(0, _reverse.reverse));
|
|
parcelHelpers.export(exports, "reverse1d", ()=>(0, _reverse1D.reverse1d));
|
|
parcelHelpers.export(exports, "reverse2d", ()=>(0, _reverse2D.reverse2d));
|
|
parcelHelpers.export(exports, "reverse3d", ()=>(0, _reverse3D.reverse3d));
|
|
parcelHelpers.export(exports, "reverse4d", ()=>(0, _reverse4D.reverse4d));
|
|
parcelHelpers.export(exports, "round", ()=>(0, _round.round));
|
|
parcelHelpers.export(exports, "rsqrt", ()=>(0, _rsqrt.rsqrt));
|
|
parcelHelpers.export(exports, "scalar", ()=>(0, _scalar.scalar));
|
|
parcelHelpers.export(exports, "selu", ()=>(0, _selu.selu));
|
|
parcelHelpers.export(exports, "separableConv2d", ()=>(0, _separableConv2D.separableConv2d));
|
|
parcelHelpers.export(exports, "setdiff1dAsync", ()=>(0, _setdiff1DAsync.setdiff1dAsync));
|
|
parcelHelpers.export(exports, "sigmoid", ()=>(0, _sigmoid.sigmoid));
|
|
parcelHelpers.export(exports, "sign", ()=>(0, _sign.sign));
|
|
parcelHelpers.export(exports, "sin", ()=>(0, _sin.sin));
|
|
parcelHelpers.export(exports, "sinh", ()=>(0, _sinh.sinh));
|
|
parcelHelpers.export(exports, "slice", ()=>(0, _slice.slice));
|
|
parcelHelpers.export(exports, "slice1d", ()=>(0, _slice1D.slice1d));
|
|
parcelHelpers.export(exports, "slice2d", ()=>(0, _slice2D.slice2d));
|
|
parcelHelpers.export(exports, "slice3d", ()=>(0, _slice3D.slice3d));
|
|
parcelHelpers.export(exports, "slice4d", ()=>(0, _slice4D.slice4d));
|
|
parcelHelpers.export(exports, "softmax", ()=>(0, _softmax.softmax));
|
|
parcelHelpers.export(exports, "softplus", ()=>(0, _softplus.softplus));
|
|
parcelHelpers.export(exports, "spaceToBatchND", ()=>(0, _spaceToBatchNd.spaceToBatchND));
|
|
parcelHelpers.export(exports, "fft", ()=>(0, _fft.fft));
|
|
parcelHelpers.export(exports, "ifft", ()=>(0, _ifft.ifft));
|
|
parcelHelpers.export(exports, "irfft", ()=>(0, _irfft.irfft));
|
|
parcelHelpers.export(exports, "rfft", ()=>(0, _rfft.rfft));
|
|
parcelHelpers.export(exports, "split", ()=>(0, _split.split));
|
|
parcelHelpers.export(exports, "sqrt", ()=>(0, _sqrt.sqrt));
|
|
parcelHelpers.export(exports, "square", ()=>(0, _square.square));
|
|
parcelHelpers.export(exports, "squaredDifference", ()=>(0, _squaredDifference.squaredDifference));
|
|
parcelHelpers.export(exports, "squeeze", ()=>(0, _squeeze.squeeze));
|
|
parcelHelpers.export(exports, "stack", ()=>(0, _stack.stack));
|
|
parcelHelpers.export(exports, "step", ()=>(0, _step.step));
|
|
parcelHelpers.export(exports, "stridedSlice", ()=>(0, _stridedSlice.stridedSlice));
|
|
parcelHelpers.export(exports, "sub", ()=>(0, _sub.sub));
|
|
parcelHelpers.export(exports, "sum", ()=>(0, _sum.sum));
|
|
parcelHelpers.export(exports, "tan", ()=>(0, _tan.tan));
|
|
parcelHelpers.export(exports, "tanh", ()=>(0, _tanh.tanh));
|
|
parcelHelpers.export(exports, "tensor", ()=>(0, _tensor.tensor));
|
|
parcelHelpers.export(exports, "tensor1d", ()=>(0, _tensor1D.tensor1d));
|
|
parcelHelpers.export(exports, "tensor2d", ()=>(0, _tensor2D.tensor2d));
|
|
parcelHelpers.export(exports, "tensor3d", ()=>(0, _tensor3D.tensor3d));
|
|
parcelHelpers.export(exports, "tensor4d", ()=>(0, _tensor4D.tensor4d));
|
|
parcelHelpers.export(exports, "tensor5d", ()=>(0, _tensor5D.tensor5d));
|
|
parcelHelpers.export(exports, "tensor6d", ()=>(0, _tensor6D.tensor6d));
|
|
parcelHelpers.export(exports, "tensorScatterUpdate", ()=>(0, _tensorScatterUpdate.tensorScatterUpdate));
|
|
parcelHelpers.export(exports, "tile", ()=>(0, _tile.tile));
|
|
parcelHelpers.export(exports, "topk", ()=>(0, _topk.topk));
|
|
parcelHelpers.export(exports, "truncatedNormal", ()=>(0, _truncatedNormal.truncatedNormal));
|
|
parcelHelpers.export(exports, "unique", ()=>(0, _unique.unique));
|
|
parcelHelpers.export(exports, "unsortedSegmentSum", ()=>(0, _unsortedSegmentSum.unsortedSegmentSum));
|
|
parcelHelpers.export(exports, "unstack", ()=>(0, _unstack.unstack));
|
|
parcelHelpers.export(exports, "upperBound", ()=>(0, _upperBound.upperBound));
|
|
parcelHelpers.export(exports, "variable", ()=>(0, _variable.variable));
|
|
parcelHelpers.export(exports, "where", ()=>(0, _where.where));
|
|
parcelHelpers.export(exports, "whereAsync", ()=>(0, _whereAsync.whereAsync));
|
|
parcelHelpers.export(exports, "zeros", ()=>(0, _zeros.zeros));
|
|
parcelHelpers.export(exports, "zerosLike", ()=>(0, _zerosLike.zerosLike));
|
|
parcelHelpers.export(exports, "op", ()=>(0, _operation.op));
|
|
parcelHelpers.export(exports, "OP_SCOPE_SUFFIX", ()=>(0, _operation.OP_SCOPE_SUFFIX));
|
|
// Second level exports.
|
|
parcelHelpers.export(exports, "image", ()=>image);
|
|
parcelHelpers.export(exports, "linalg", ()=>linalg);
|
|
parcelHelpers.export(exports, "losses", ()=>losses);
|
|
parcelHelpers.export(exports, "spectral", ()=>spectral);
|
|
parcelHelpers.export(exports, "fused", ()=>_fusedOps);
|
|
parcelHelpers.export(exports, "signal", ()=>signal);
|
|
parcelHelpers.export(exports, "sparse", ()=>sparse);
|
|
parcelHelpers.export(exports, "string", ()=>string);
|
|
var _abs = require("./abs");
|
|
var _acos = require("./acos");
|
|
var _acosh = require("./acosh");
|
|
var _add = require("./add");
|
|
var _addN = require("./add_n");
|
|
var _all = require("./all");
|
|
var _any = require("./any");
|
|
var _argMax = require("./arg_max");
|
|
var _argMin = require("./arg_min");
|
|
var _asin = require("./asin");
|
|
var _asinh = require("./asinh");
|
|
var _atan = require("./atan");
|
|
var _atan2 = require("./atan2");
|
|
var _atanh = require("./atanh");
|
|
var _avgPool = require("./avg_pool");
|
|
var _avgPool3D = require("./avg_pool_3d");
|
|
var _basicLstmCell = require("./basic_lstm_cell");
|
|
var _batchToSpaceNd = require("./batch_to_space_nd");
|
|
var _batchnorm = require("./batchnorm");
|
|
var _batchnorm2D = require("./batchnorm2d");
|
|
var _batchnorm3D = require("./batchnorm3d");
|
|
var _batchnorm4D = require("./batchnorm4d");
|
|
var _bincount = require("./bincount");
|
|
var _bitwiseAnd = require("./bitwise_and");
|
|
var _broadcastArgs = require("./broadcast_args");
|
|
var _broadcastTo = require("./broadcast_to");
|
|
var _buffer = require("./buffer");
|
|
var _cast = require("./cast");
|
|
var _ceil = require("./ceil");
|
|
var _clipByValue = require("./clip_by_value");
|
|
var _clone = require("./clone");
|
|
var _complex = require("./complex");
|
|
var _concat = require("./concat");
|
|
var _concat1D = require("./concat_1d");
|
|
var _concat2D = require("./concat_2d");
|
|
var _concat3D = require("./concat_3d");
|
|
var _concat4D = require("./concat_4d");
|
|
var _conv1D = require("./conv1d");
|
|
var _conv2D = require("./conv2d");
|
|
var _conv2DTranspose = require("./conv2d_transpose");
|
|
var _conv3D = require("./conv3d");
|
|
var _conv3DTranspose = require("./conv3d_transpose");
|
|
var _cos = require("./cos");
|
|
var _cosh = require("./cosh");
|
|
var _cumprod = require("./cumprod");
|
|
var _cumsum = require("./cumsum");
|
|
var _denseBincount = require("./dense_bincount");
|
|
var _depthToSpace = require("./depth_to_space");
|
|
var _depthwiseConv2D = require("./depthwise_conv2d");
|
|
var _diag = require("./diag");
|
|
var _dilation2D = require("./dilation2d");
|
|
var _div = require("./div");
|
|
var _divNoNan = require("./div_no_nan");
|
|
var _dot = require("./dot");
|
|
var _einsum = require("./einsum");
|
|
var _elu = require("./elu");
|
|
var _ensureShape = require("./ensure_shape");
|
|
var _equal = require("./equal");
|
|
var _erf = require("./erf");
|
|
var _euclideanNorm = require("./euclidean_norm");
|
|
var _exp = require("./exp");
|
|
var _expandDims = require("./expand_dims");
|
|
var _expm1 = require("./expm1");
|
|
var _eye = require("./eye");
|
|
var _fill = require("./fill");
|
|
var _floor = require("./floor");
|
|
var _floorDiv = require("./floorDiv");
|
|
var _gather = require("./gather");
|
|
var _greater = require("./greater");
|
|
var _greaterEqual = require("./greater_equal");
|
|
var _imag = require("./imag");
|
|
var _isFinite = require("./is_finite");
|
|
var _isInf = require("./is_inf");
|
|
var _isNan = require("./is_nan");
|
|
var _leakyRelu = require("./leaky_relu");
|
|
var _less = require("./less");
|
|
var _lessEqual = require("./less_equal");
|
|
var _linspace = require("./linspace");
|
|
var _localResponseNormalization = require("./local_response_normalization");
|
|
var _log = require("./log");
|
|
var _log1P = require("./log1p");
|
|
var _logSigmoid = require("./log_sigmoid");
|
|
var _logSoftmax = require("./log_softmax");
|
|
var _logSumExp = require("./log_sum_exp");
|
|
var _logicalAnd = require("./logical_and");
|
|
var _logicalNot = require("./logical_not");
|
|
var _logicalOr = require("./logical_or");
|
|
var _logicalXor = require("./logical_xor");
|
|
var _lowerBound = require("./lower_bound");
|
|
var _matMul = require("./mat_mul");
|
|
var _max = require("./max");
|
|
var _maxPool = require("./max_pool");
|
|
var _maxPool3D = require("./max_pool_3d");
|
|
var _maxPoolWithArgmax = require("./max_pool_with_argmax");
|
|
var _maximum = require("./maximum");
|
|
var _mean = require("./mean");
|
|
var _meshgrid = require("./meshgrid");
|
|
var _min = require("./min");
|
|
var _minimum = require("./minimum");
|
|
var _mirrorPad = require("./mirror_pad");
|
|
var _mod = require("./mod");
|
|
var _moments = require("./moments");
|
|
var _mul = require("./mul");
|
|
var _multiRnnCell = require("./multi_rnn_cell");
|
|
var _multinomial = require("./multinomial");
|
|
var _neg = require("./neg");
|
|
var _notEqual = require("./not_equal");
|
|
var _oneHot = require("./one_hot");
|
|
var _ones = require("./ones");
|
|
var _onesLike = require("./ones_like");
|
|
var _outerProduct = require("./outer_product");
|
|
var _pad = require("./pad");
|
|
var _pad1D = require("./pad1d");
|
|
var _pad2D = require("./pad2d");
|
|
var _pad3D = require("./pad3d");
|
|
var _pad4D = require("./pad4d");
|
|
var _pool = require("./pool");
|
|
var _pow = require("./pow");
|
|
var _prelu = require("./prelu");
|
|
var _print = require("./print");
|
|
var _prod = require("./prod");
|
|
var _raggedGather = require("./ragged_gather");
|
|
var _raggedRange = require("./ragged_range");
|
|
var _raggedTensorToTensor = require("./ragged_tensor_to_tensor");
|
|
var _rand = require("./rand");
|
|
var _randomGamma = require("./random_gamma");
|
|
var _randomNormal = require("./random_normal");
|
|
var _randomStandardNormal = require("./random_standard_normal");
|
|
var _randomUniform = require("./random_uniform");
|
|
var _randomUniformInt = require("./random_uniform_int");
|
|
var _range = require("./range");
|
|
var _real = require("./real");
|
|
var _reciprocal = require("./reciprocal");
|
|
var _relu = require("./relu");
|
|
var _relu6 = require("./relu6");
|
|
var _reshape = require("./reshape");
|
|
var _reverse = require("./reverse");
|
|
var _reverse1D = require("./reverse_1d");
|
|
var _reverse2D = require("./reverse_2d");
|
|
var _reverse3D = require("./reverse_3d");
|
|
var _reverse4D = require("./reverse_4d");
|
|
var _round = require("./round");
|
|
var _rsqrt = require("./rsqrt");
|
|
var _scalar = require("./scalar");
|
|
var _selu = require("./selu");
|
|
var _separableConv2D = require("./separable_conv2d");
|
|
var _setdiff1DAsync = require("./setdiff1d_async");
|
|
var _sigmoid = require("./sigmoid");
|
|
var _sign = require("./sign");
|
|
var _sin = require("./sin");
|
|
var _sinh = require("./sinh");
|
|
var _slice = require("./slice");
|
|
var _slice1D = require("./slice1d");
|
|
var _slice2D = require("./slice2d");
|
|
var _slice3D = require("./slice3d");
|
|
var _slice4D = require("./slice4d");
|
|
var _softmax = require("./softmax");
|
|
var _softplus = require("./softplus");
|
|
var _spaceToBatchNd = require("./space_to_batch_nd");
|
|
var _fft = require("./spectral/fft");
|
|
var _ifft = require("./spectral/ifft");
|
|
var _irfft = require("./spectral/irfft");
|
|
var _rfft = require("./spectral/rfft");
|
|
var _split = require("./split");
|
|
var _sqrt = require("./sqrt");
|
|
var _square = require("./square");
|
|
var _squaredDifference = require("./squared_difference");
|
|
var _squeeze = require("./squeeze");
|
|
var _stack = require("./stack");
|
|
var _step = require("./step");
|
|
var _stridedSlice = require("./strided_slice");
|
|
var _sub = require("./sub");
|
|
var _sum = require("./sum");
|
|
var _tan = require("./tan");
|
|
var _tanh = require("./tanh");
|
|
var _tensor = require("./tensor");
|
|
var _tensor1D = require("./tensor1d");
|
|
var _tensor2D = require("./tensor2d");
|
|
var _tensor3D = require("./tensor3d");
|
|
var _tensor4D = require("./tensor4d");
|
|
var _tensor5D = require("./tensor5d");
|
|
var _tensor6D = require("./tensor6d");
|
|
var _tensorScatterUpdate = require("./tensor_scatter_update");
|
|
var _tile = require("./tile");
|
|
var _topk = require("./topk");
|
|
var _truncatedNormal = require("./truncated_normal");
|
|
var _unique = require("./unique");
|
|
var _unsortedSegmentSum = require("./unsorted_segment_sum");
|
|
var _unstack = require("./unstack");
|
|
var _upperBound = require("./upper_bound");
|
|
var _variable = require("./variable");
|
|
var _where = require("./where");
|
|
var _whereAsync = require("./where_async");
|
|
var _zeros = require("./zeros");
|
|
var _zerosLike = require("./zeros_like");
|
|
var _booleanMask = require("./boolean_mask");
|
|
parcelHelpers.exportAll(_booleanMask, exports);
|
|
var _transpose = require("./transpose");
|
|
parcelHelpers.exportAll(_transpose, exports);
|
|
var _norm = require("./norm");
|
|
parcelHelpers.exportAll(_norm, exports);
|
|
var _movingAverage = require("./moving_average");
|
|
parcelHelpers.exportAll(_movingAverage, exports);
|
|
var _scatterNd = require("./scatter_nd");
|
|
parcelHelpers.exportAll(_scatterNd, exports);
|
|
var _searchSorted = require("./search_sorted");
|
|
parcelHelpers.exportAll(_searchSorted, exports);
|
|
var _sparseToDense = require("./sparse_to_dense");
|
|
parcelHelpers.exportAll(_sparseToDense, exports);
|
|
var _gatherNd = require("./gather_nd");
|
|
parcelHelpers.exportAll(_gatherNd, exports);
|
|
var _dropout = require("./dropout");
|
|
parcelHelpers.exportAll(_dropout, exports);
|
|
var _signalOpsUtil = require("./signal_ops_util");
|
|
parcelHelpers.exportAll(_signalOpsUtil, exports);
|
|
var _inTopK = require("./in_top_k");
|
|
parcelHelpers.exportAll(_inTopK, exports);
|
|
var _operation = require("./operation");
|
|
var _fusedOps = require("./fused_ops");
|
|
var _hammingWindow = require("./signal/hamming_window");
|
|
var _hannWindow = require("./signal/hann_window");
|
|
var _frame = require("./signal/frame");
|
|
var _stft = require("./signal/stft");
|
|
// Image Ops namespace
|
|
var _cropAndResize = require("./image/crop_and_resize");
|
|
var _flipLeftRight = require("./image/flip_left_right");
|
|
var _grayscaleToRgb = require("./image/grayscale_to_rgb");
|
|
var _rgbToGrayscale = require("./image/rgb_to_grayscale");
|
|
var _rotateWithOffset = require("./image/rotate_with_offset");
|
|
var _nonMaxSuppression = require("./image/non_max_suppression");
|
|
var _nonMaxSuppressionAsync = require("./image/non_max_suppression_async");
|
|
var _nonMaxSuppressionWithScore = require("./image/non_max_suppression_with_score");
|
|
var _nonMaxSuppressionWithScoreAsync = require("./image/non_max_suppression_with_score_async");
|
|
var _nonMaxSuppressionPadded = require("./image/non_max_suppression_padded");
|
|
var _nonMaxSuppressionPaddedAsync = require("./image/non_max_suppression_padded_async");
|
|
var _resizeBilinear = require("./image/resize_bilinear");
|
|
var _resizeNearestNeighbor = require("./image/resize_nearest_neighbor");
|
|
var _threshold = require("./image/threshold");
|
|
var _transform = require("./image/transform");
|
|
// linalg namespace
|
|
var _bandPart = require("./linalg/band_part");
|
|
var _gramSchmidt = require("./linalg/gram_schmidt");
|
|
var _qr = require("./linalg/qr");
|
|
// losses namespace;
|
|
var _absoluteDifference = require("./losses/absolute_difference");
|
|
var _computeWeightedLoss = require("./losses/compute_weighted_loss");
|
|
var _cosineDistance = require("./losses/cosine_distance");
|
|
var _hingeLoss = require("./losses/hinge_loss");
|
|
var _huberLoss = require("./losses/huber_loss");
|
|
var _logLoss = require("./losses/log_loss");
|
|
var _meanSquaredError = require("./losses/mean_squared_error");
|
|
var _sigmoidCrossEntropy = require("./losses/sigmoid_cross_entropy");
|
|
var _softmaxCrossEntropy = require("./losses/softmax_cross_entropy");
|
|
var _sparseFillEmptyRows = require("./sparse/sparse_fill_empty_rows");
|
|
var _sparseReshape = require("./sparse/sparse_reshape");
|
|
var _sparseSegmentMean = require("./sparse/sparse_segment_mean");
|
|
var _sparseSegmentSum = require("./sparse/sparse_segment_sum");
|
|
var _stringNGrams = require("./string/string_n_grams");
|
|
var _stringSplit = require("./string/string_split");
|
|
var _stringToHashBucketFast = require("./string/string_to_hash_bucket_fast");
|
|
var _staticRegexReplace = require("./string/static_regex_replace");
|
|
const spectral = {
|
|
fft: (0, _fft.fft),
|
|
ifft: (0, _ifft.ifft),
|
|
rfft: (0, _rfft.rfft),
|
|
irfft: (0, _irfft.irfft)
|
|
};
|
|
const signal = {
|
|
hammingWindow: (0, _hammingWindow.hammingWindow),
|
|
hannWindow: (0, _hannWindow.hannWindow),
|
|
frame: (0, _frame.frame),
|
|
stft: (0, _stft.stft)
|
|
};
|
|
const image = {
|
|
flipLeftRight: (0, _flipLeftRight.flipLeftRight),
|
|
grayscaleToRGB: (0, _grayscaleToRgb.grayscaleToRGB),
|
|
resizeNearestNeighbor: (0, _resizeNearestNeighbor.resizeNearestNeighbor),
|
|
resizeBilinear: (0, _resizeBilinear.resizeBilinear),
|
|
rgbToGrayscale: (0, _rgbToGrayscale.rgbToGrayscale),
|
|
rotateWithOffset: (0, _rotateWithOffset.rotateWithOffset),
|
|
cropAndResize: (0, _cropAndResize.cropAndResize),
|
|
nonMaxSuppression: (0, _nonMaxSuppression.nonMaxSuppression),
|
|
nonMaxSuppressionAsync: (0, _nonMaxSuppressionAsync.nonMaxSuppressionAsync),
|
|
nonMaxSuppressionWithScore: (0, _nonMaxSuppressionWithScore.nonMaxSuppressionWithScore),
|
|
nonMaxSuppressionWithScoreAsync: (0, _nonMaxSuppressionWithScoreAsync.nonMaxSuppressionWithScoreAsync),
|
|
nonMaxSuppressionPadded: (0, _nonMaxSuppressionPadded.nonMaxSuppressionPadded),
|
|
nonMaxSuppressionPaddedAsync: (0, _nonMaxSuppressionPaddedAsync.nonMaxSuppressionPaddedAsync),
|
|
threshold: (0, _threshold.threshold),
|
|
transform: (0, _transform.transform)
|
|
};
|
|
const linalg = {
|
|
bandPart: (0, _bandPart.bandPart),
|
|
gramSchmidt: (0, _gramSchmidt.gramSchmidt),
|
|
qr: (0, _qr.qr)
|
|
};
|
|
const losses = {
|
|
absoluteDifference: (0, _absoluteDifference.absoluteDifference),
|
|
computeWeightedLoss: (0, _computeWeightedLoss.computeWeightedLoss),
|
|
cosineDistance: (0, _cosineDistance.cosineDistance),
|
|
hingeLoss: (0, _hingeLoss.hingeLoss),
|
|
huberLoss: (0, _huberLoss.huberLoss),
|
|
logLoss: (0, _logLoss.logLoss),
|
|
meanSquaredError: (0, _meanSquaredError.meanSquaredError),
|
|
sigmoidCrossEntropy: (0, _sigmoidCrossEntropy.sigmoidCrossEntropy),
|
|
softmaxCrossEntropy: (0, _softmaxCrossEntropy.softmaxCrossEntropy)
|
|
};
|
|
const sparse = {
|
|
sparseFillEmptyRows: (0, _sparseFillEmptyRows.sparseFillEmptyRows),
|
|
sparseReshape: (0, _sparseReshape.sparseReshape),
|
|
sparseSegmentMean: (0, _sparseSegmentMean.sparseSegmentMean),
|
|
sparseSegmentSum: (0, _sparseSegmentSum.sparseSegmentSum)
|
|
};
|
|
// tslint:disable-next-line:variable-name
|
|
const string = {
|
|
stringNGrams: (0, _stringNGrams.stringNGrams),
|
|
stringSplit: (0, _stringSplit.stringSplit),
|
|
stringToHashBucketFast: (0, _stringToHashBucketFast.stringToHashBucketFast),
|
|
staticRegexReplace: (0, _staticRegexReplace.staticRegexReplace)
|
|
};
|
|
|
|
},{"./abs":"iZQ4e","./acos":"dZHka","./acosh":"84Yuy","./add":"aynh7","./add_n":"cEtmn","./all":"a1yTA","./any":"9SyE5","./arg_max":"6RjBh","./arg_min":"ljaN9","./asin":"gHBQs","./asinh":"5c3gG","./atan":"a4WSB","./atan2":"3i20s","./atanh":"1G9hg","./avg_pool":"d8nrP","./avg_pool_3d":"bdrlT","./basic_lstm_cell":"581eT","./batch_to_space_nd":"5A2j5","./batchnorm":"5eVFD","./batchnorm2d":"9ULx9","./batchnorm3d":"y3kug","./batchnorm4d":"4l9oM","./bincount":"gW00L","./bitwise_and":"jmT4J","./broadcast_args":"d9ZLh","./broadcast_to":"iMuoF","./buffer":"dYyY7","./cast":"b4VDA","./ceil":"hVmez","./clip_by_value":"cKbfV","./clone":"jmQ7S","./complex":"bPDAx","./concat":"1NOyL","./concat_1d":"jI8Rd","./concat_2d":"2ZT6j","./concat_3d":"g5T4x","./concat_4d":"fsDG1","./conv1d":"2LKBX","./conv2d":"lmJyO","./conv2d_transpose":"kCheD","./conv3d":"3stvE","./conv3d_transpose":"4J2I2","./cos":"aBory","./cosh":"kFKmS","./cumprod":"gorKt","./cumsum":"8KDcI","./dense_bincount":"3PEDs","./depth_to_space":"ipPbw","./depthwise_conv2d":"cZHpb","./diag":"3orNc","./dilation2d":"7hUfK","./div":"5ZT1h","./div_no_nan":"aw8lb","./dot":"b1M9k","./einsum":"adKPG","./elu":"dE197","./ensure_shape":"f2yaA","./equal":"htEqc","./erf":"e0JJC","./euclidean_norm":"8OAGY","./exp":"1CsGu","./expand_dims":"lc7t7","./expm1":"lDAq4","./eye":"hDQ1U","./fill":"i7goe","./floor":"35qCf","./floorDiv":"jboDF","./gather":"5p5vK","./greater":"3Nh8O","./greater_equal":"f7S2c","./imag":"lDORm","./is_finite":"ddlWF","./is_inf":"2QZvv","./is_nan":"58UC5","./leaky_relu":"aRBcm","./less":"hCGN5","./less_equal":"j9Jhy","./linspace":"7Vd0v","./local_response_normalization":"eTOXs","./log":"iex5O","./log1p":"jKhH4","./log_sigmoid":"2X6mM","./log_softmax":"5yBCd","./log_sum_exp":"feRCM","./logical_and":"6zYjJ","./logical_not":"gSuOh","./logical_or":"dH6xG","./logical_xor":"7Y9m5","./lower_bound":"2XtFq","./mat_mul":"fiMp4","./max":"cb6Hb","./max_pool":"hx37d","./max_pool_3d":"z14HA","./max_pool_with_argmax":"hPUnJ","./maximum":"1nFpL","./mean":"hzzLs","./meshgrid":"jFI6G","./min":"fhwke","./minimum":"guwat","./mirror_pad":"1Sy5n","./mod":"g5efu","./moments":"ef1IE","./mul":"fOWrC","./multi_rnn_cell":"lNZ3B","./multinomial":"g1s8L","./neg":"3jQfI","./not_equal":"gUKb0","./one_hot":"91jNM","./ones":"2gdnE","./ones_like":"7TDfu","./outer_product":"emoMO","./pad":"89mWw","./pad1d":"gOSFg","./pad2d":"2QXo6","./pad3d":"6eqEc","./pad4d":"dP5zO","./pool":"sCTfp","./pow":"gezpC","./prelu":"azJEF","./print":"5RyfW","./prod":"hawIk","./ragged_gather":"a5cAV","./ragged_range":"9Z2C7","./ragged_tensor_to_tensor":"93163","./rand":"eyCJc","./random_gamma":"4v8VB","./random_normal":"72nVa","./random_standard_normal":"eOkY1","./random_uniform":"8LDYI","./random_uniform_int":"a0IEB","./range":"3seHd","./real":"8i3Ch","./reciprocal":"bxIjM","./relu":"lcv3E","./relu6":"cvYLK","./reshape":"ew3wZ","./reverse":"9yp4z","./reverse_1d":"1LPYc","./reverse_2d":"7RrO2","./reverse_3d":"jdnrR","./reverse_4d":"7dqzq","./round":"4aCvQ","./rsqrt":"7D6sy","./scalar":"7lhC8","./selu":"kGS0T","./separable_conv2d":"1MPx9","./setdiff1d_async":"8tR1Z","./sigmoid":"81E16","./sign":"3bcO0","./sin":"gSMA7","./sinh":"5VZJu","./slice":"dr7Gq","./slice1d":"4krOi","./slice2d":"2Dy3M","./slice3d":"3DCYE","./slice4d":"bMRWt","./softmax":"5C9bA","./softplus":"4zLJS","./space_to_batch_nd":"dDwiy","./spectral/fft":"2vcIN","./spectral/ifft":"4lzNl","./spectral/irfft":"hzbzS","./spectral/rfft":"hnd5A","./split":"l0HF2","./sqrt":"cOGi9","./square":"cOosW","./squared_difference":"iHBgt","./squeeze":"VbY6Z","./stack":"jeh7M","./step":"bBBT4","./strided_slice":"9Kwrw","./sub":"jBBQ2","./sum":"5awd0","./tan":"c36dQ","./tanh":"jXQuL","./tensor":"jdbb1","./tensor1d":"aEL9e","./tensor2d":"faX5H","./tensor3d":"lVDsd","./tensor4d":"5QFb1","./tensor5d":"7LoZX","./tensor6d":"jFXe2","./tensor_scatter_update":"1L18R","./tile":"gzqG2","./topk":"jUBl9","./truncated_normal":"jsVmm","./unique":"kc2B3","./unsorted_segment_sum":"8ZRDN","./unstack":"90Kbb","./upper_bound":"csQSE","./variable":"c3Bg5","./where":"47cKc","./where_async":"2KVsP","./zeros":"fcPHR","./zeros_like":"1Xjct","./boolean_mask":"jnpjK","./transpose":"2bqbS","./norm":"eOnCA","./moving_average":"hLPKe","./scatter_nd":"2xMWX","./search_sorted":"4gaGh","./sparse_to_dense":"gXN1p","./gather_nd":"9KIwq","./dropout":"6nVzD","./signal_ops_util":"1EuF4","./in_top_k":"9rwSr","./operation":"ip64W","./fused_ops":"jqlvt","./signal/hamming_window":"crMwx","./signal/hann_window":"lwQEl","./signal/frame":"3ntgK","./signal/stft":"gUBf5","./image/crop_and_resize":"kQOfI","./image/flip_left_right":"7xdFd","./image/grayscale_to_rgb":"hbmqN","./image/rgb_to_grayscale":"hrZfi","./image/rotate_with_offset":"df6QK","./image/non_max_suppression":"bQBrw","./image/non_max_suppression_async":"8ps8b","./image/non_max_suppression_with_score":"khN9i","./image/non_max_suppression_with_score_async":"bH9TE","./image/non_max_suppression_padded":"3Hdah","./image/non_max_suppression_padded_async":"dJg2S","./image/resize_bilinear":"h5fgY","./image/resize_nearest_neighbor":"6vytD","./image/threshold":"d58R4","./image/transform":"sijU0","./linalg/band_part":"cLsM5","./linalg/gram_schmidt":"dmmpK","./linalg/qr":"dhxAc","./losses/absolute_difference":"5sJon","./losses/compute_weighted_loss":"1agzr","./losses/cosine_distance":"enn6x","./losses/hinge_loss":"1aaXc","./losses/huber_loss":"1c06w","./losses/log_loss":"UdKNC","./losses/mean_squared_error":"8Mugj","./losses/sigmoid_cross_entropy":"77Q3C","./losses/softmax_cross_entropy":"cGUog","./sparse/sparse_fill_empty_rows":"1MyfF","./sparse/sparse_reshape":"f6fUL","./sparse/sparse_segment_mean":"d0IYG","./sparse/sparse_segment_sum":"7MtJg","./string/string_n_grams":"gELNE","./string/string_split":"3z1cj","./string/string_to_hash_bucket_fast":"8mVop","./string/static_regex_replace":"dLgGV","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iZQ4e":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "abs", ()=>abs);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "abs");
|
|
if ($x.dtype === "complex64") {
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.ComplexAbs), inputs);
|
|
} else {
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Abs), inputs);
|
|
}
|
|
}
|
|
const abs = /* @__PURE__ */ (0, _operation.op)({
|
|
abs_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dZHka":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "acos", ()=>acos);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "acos");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Acos), inputs);
|
|
}
|
|
const acos = /* @__PURE__ */ (0, _operation.op)({
|
|
acos_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"84Yuy":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "acosh", ()=>acosh);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "acosh");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Acosh), inputs);
|
|
}
|
|
const acosh = /* @__PURE__ */ (0, _operation.op)({
|
|
acosh_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cEtmn":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "addN", ()=>addN);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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)=>(0, _tensorUtilEnv.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 inputs = $tensors;
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.AddN), inputs);
|
|
}
|
|
const addN = /* @__PURE__ */ (0, _operation.op)({
|
|
addN_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a1yTA":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "all", ()=>all);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 a
|
|
* `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) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "all", "bool");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
keepDims
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.All), inputs, attrs);
|
|
}
|
|
const all = /* @__PURE__ */ (0, _operation.op)({
|
|
all_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9SyE5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "any", ()=>any);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 a
|
|
* `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) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "any", "bool");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
keepDims
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Any), inputs, attrs);
|
|
}
|
|
const any = /* @__PURE__ */ (0, _operation.op)({
|
|
any_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6RjBh":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "argMax", ()=>argMax);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "argMax");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.ArgMax), inputs, attrs);
|
|
}
|
|
const argMax = /* @__PURE__ */ (0, _operation.op)({
|
|
argMax_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ljaN9":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "argMin", ()=>argMin);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "argMin");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.ArgMin), inputs, attrs);
|
|
}
|
|
const argMin = /* @__PURE__ */ (0, _operation.op)({
|
|
argMin_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gHBQs":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "asin", ()=>asin);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "asin");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Asin), inputs);
|
|
}
|
|
const asin = /* @__PURE__ */ (0, _operation.op)({
|
|
asin_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5c3gG":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "asinh", ()=>asinh);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "asinh");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Asinh), inputs);
|
|
}
|
|
const asinh = /* @__PURE__ */ (0, _operation.op)({
|
|
asinh_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a4WSB":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atan", ()=>atan);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "atan");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Atan), inputs);
|
|
}
|
|
const atan = /* @__PURE__ */ (0, _operation.op)({
|
|
atan_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3i20s":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atan2", ()=>atan2);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "atan2");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "atan2");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Atan2), inputs);
|
|
}
|
|
const atan2 = /* @__PURE__ */ (0, _operation.op)({
|
|
atan2_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1G9hg":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atanh", ()=>atanh);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "atanh");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Atanh), inputs);
|
|
}
|
|
const atanh = /* @__PURE__ */ (0, _operation.op)({
|
|
atanh_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"d8nrP":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPool", ()=>avgPool);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _cast = require("./cast");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
|
|
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function avgPool_(x, filterSize, strides, pad, dimRoundingMode) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "avgPool", "float32");
|
|
const dilations = 1;
|
|
_util.assert(_convUtil.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 = (0, _reshape.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}.`);
|
|
_convUtil.checkPadOnDimRoundingMode("avgPool", pad, dimRoundingMode);
|
|
const inputs = {
|
|
x: x4D
|
|
};
|
|
const attrs = {
|
|
filterSize,
|
|
strides,
|
|
pad,
|
|
dimRoundingMode
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
let res = (0, _engine.ENGINE).runKernel((0, _kernelNames.AvgPool), inputs, attrs);
|
|
res = (0, _cast.cast)(res, $x.dtype);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const avgPool = /* @__PURE__ */ (0, _operation.op)({
|
|
avgPool_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./cast":"b4VDA","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bf4MH":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
*
|
|
* @param inputShape Input tensor shape is of the following dimensions:
|
|
* `[batch, height, width, inChannels]`.
|
|
* @param filterShape The filter shape is of the following dimensions:
|
|
* `[filterHeight, filterWidth, depth]`.
|
|
* @param strides The strides of the sliding window for each dimension of the
|
|
* input tensor: `[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 1*1x1.
|
|
* - For more info, see this guide:
|
|
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
|
|
* @param dataFormat The data format of the input and output data.
|
|
* Defaults to 'NHWC'.
|
|
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`.
|
|
* Defaults to `[1, 1]`. If `dilations` is a single number, then
|
|
* `dilationHeight == dilationWidth`.
|
|
*/ parcelHelpers.export(exports, "computeDilation2DInfo", ()=>computeDilation2DInfo);
|
|
parcelHelpers.export(exports, "computePool2DInfo", ()=>computePool2DInfo);
|
|
/**
|
|
* Computes the information for a forward pass of a pooling3D operation.
|
|
*/ parcelHelpers.export(exports, "computePool3DInfo", ()=>computePool3DInfo);
|
|
/**
|
|
* Computes the information for a forward pass of a convolution/pooling
|
|
* operation.
|
|
*/ parcelHelpers.export(exports, "computeConv2DInfo", ()=>computeConv2DInfo);
|
|
/**
|
|
* Computes the information for a forward pass of a 3D convolution/pooling
|
|
* operation.
|
|
*/ parcelHelpers.export(exports, "computeConv3DInfo", ()=>computeConv3DInfo);
|
|
parcelHelpers.export(exports, "computeDefaultPad", ()=>computeDefaultPad);
|
|
parcelHelpers.export(exports, "tupleValuesAreOne", ()=>tupleValuesAreOne);
|
|
parcelHelpers.export(exports, "eitherStridesOrDilationsAreOne", ()=>eitherStridesOrDilationsAreOne);
|
|
parcelHelpers.export(exports, "stridesOrDilationsArePositive", ()=>stridesOrDilationsArePositive);
|
|
/**
|
|
* Convert Conv2D dataFormat from 'NHWC'|'NCHW' to
|
|
* 'channelsLast'|'channelsFirst'
|
|
* @param dataFormat in 'NHWC'|'NCHW' mode
|
|
* @return dataFormat in 'channelsLast'|'channelsFirst' mode
|
|
* @throws unknown dataFormat
|
|
*/ parcelHelpers.export(exports, "convertConv2DDataFormat", ()=>convertConv2DDataFormat);
|
|
/**
|
|
* Check validity of pad when using dimRoundingMode.
|
|
* @param opDesc A string of op description
|
|
* @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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
|
|
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
* @throws unknown padding parameter
|
|
*/ parcelHelpers.export(exports, "checkPadOnDimRoundingMode", ()=>checkPadOnDimRoundingMode);
|
|
var _util = require("../util");
|
|
function computeDilation2DInfo(inputShape, filterShape, strides, pad, dataFormat = "NHWC", dilations) {
|
|
// `computerConv2DInfo` require filterShape to be in the dimension of:
|
|
// `[filterHeight, filterWidth, depth, outDepth]`, dilation2d doesn't have
|
|
// outDepth, it should have the same depth as the input.
|
|
// Input shape: [batch, height, width, inChannels]
|
|
const inputChannels = inputShape[3];
|
|
const $filterShape = [
|
|
...filterShape,
|
|
inputChannels
|
|
];
|
|
const $dataFormat = convertConv2DDataFormat(dataFormat);
|
|
return computeConv2DInfo(inputShape, $filterShape, strides, dilations, pad, null, null, $dataFormat);
|
|
}
|
|
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);
|
|
}
|
|
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);
|
|
}
|
|
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
|
|
};
|
|
}
|
|
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 = round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
|
|
const outputCols = round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
|
|
return [
|
|
outputRows,
|
|
outputCols
|
|
];
|
|
}
|
|
function computeOutputShape4D(inShape, filterShape, outChannels, strides, zeroPad, roundingMode) {
|
|
if (zeroPad == null) zeroPad = computeDefaultPad(inShape, filterShape[0], strides[0]);
|
|
const outShape = [
|
|
0,
|
|
0,
|
|
0,
|
|
outChannels
|
|
];
|
|
for(let index = 0; index < 3; index++)if (inShape[index] + 2 * zeroPad >= filterShape[index]) outShape[index] = round((inShape[index] - filterShape[index] + 2 * zeroPad) / strides[index] + 1, roundingMode);
|
|
return outShape;
|
|
}
|
|
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 = round((inHeight - filterHeight + top + bottom) / strideHeight + 1, roundingMode);
|
|
outWidth = round((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 (pad === "valid") pad = 0;
|
|
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,
|
|
filterHeight,
|
|
filterWidth
|
|
], 1, [
|
|
strideDepth,
|
|
strideHeight,
|
|
strideWidth
|
|
], 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 throw Error(`Unknown padding parameter: ${pad}`);
|
|
return {
|
|
padInfo,
|
|
outDepth,
|
|
outHeight,
|
|
outWidth
|
|
};
|
|
}
|
|
/**
|
|
* Rounds a value depending on the rounding mode
|
|
* @param value
|
|
* @param roundingMode A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*/ function round(value, roundingMode) {
|
|
if (!roundingMode) return Math.trunc(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);
|
|
}
|
|
function stridesOrDilationsArePositive(values) {
|
|
return parseTupleParam(values).every((value)=>value > 0);
|
|
}
|
|
function convertConv2DDataFormat(dataFormat) {
|
|
if (dataFormat === "NHWC") return "channelsLast";
|
|
else if (dataFormat === "NCHW") return "channelsFirst";
|
|
else throw new Error(`Unknown dataFormat ${dataFormat}`);
|
|
}
|
|
function checkPadOnDimRoundingMode(opDesc, pad, dimRoundingMode) {
|
|
if (dimRoundingMode != null) {
|
|
if (typeof pad === "string") throw Error(`Error in ${opDesc}: pad must be an integer when using ` + `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
|
|
else if (typeof pad === "number") _util.assert(_util.isInt(pad), ()=>`Error in ${opDesc}: pad must be an integer when using ` + `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
|
|
else if (typeof pad === "object") pad.forEach((p)=>{
|
|
p.forEach((v)=>{
|
|
_util.assert(_util.isInt(v), ()=>`Error in ${opDesc}: pad must be an integer when using ` + `dimRoundingMode ${dimRoundingMode} but got pad ${v}.`);
|
|
});
|
|
});
|
|
else throw Error(`Error in ${opDesc}: Unknown padding parameter: ${pad}`);
|
|
}
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ew3wZ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reshape", ()=>reshape);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "reshape", "string_or_numeric");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
shape
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Reshape), inputs, attrs);
|
|
}
|
|
const reshape = /* @__PURE__ */ (0, _operation.op)({
|
|
reshape_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bdrlT":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPool3d", ()=>avgPool3d);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _cast = require("./cast");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
|
|
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
* @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.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function avgPool3d_(x, filterSize, strides, pad, dimRoundingMode, dataFormat = "NDHWC") {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "avgPool3d", "float32");
|
|
let x5D = $x;
|
|
let reshapedTo5D = false;
|
|
if ($x.rank === 4) {
|
|
reshapedTo5D = true;
|
|
x5D = (0, _reshape.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(typeof strides === "number" && strides > 0 || Array.isArray(strides) && strides[0] > 0 && strides[1] > 0 && strides[2] > 0, ()=>`Error in avgPool3d: Stride must be > 0, but got '${strides}'`);
|
|
(0, _convUtil.checkPadOnDimRoundingMode)("avgPool3d", pad, dimRoundingMode);
|
|
const inputs = {
|
|
x: x5D
|
|
};
|
|
const attrs = {
|
|
filterSize,
|
|
strides,
|
|
pad,
|
|
dimRoundingMode,
|
|
dataFormat
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
let res = (0, _engine.ENGINE).runKernel((0, _kernelNames.AvgPool3D), inputs, attrs);
|
|
res = (0, _cast.cast)(res, x5D.dtype);
|
|
if (reshapedTo5D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3],
|
|
res.shape[4]
|
|
]);
|
|
return res;
|
|
}
|
|
const avgPool3d = /* @__PURE__ */ (0, _operation.op)({
|
|
avgPool3d_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./cast":"b4VDA","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"581eT":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "basicLSTMCell", ()=>basicLSTMCell);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _add = require("./add");
|
|
var _concat = require("./concat");
|
|
var _matMul = require("./mat_mul");
|
|
var _mul = require("./mul");
|
|
var _operation = require("./operation");
|
|
var _sigmoid = require("./sigmoid");
|
|
var _slice = require("./slice");
|
|
var _tanh = require("./tanh");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(forgetBias, "forgetBias", "basicLSTMCell");
|
|
const $lstmKernel = (0, _tensorUtilEnv.convertToTensor)(lstmKernel, "lstmKernel", "basicLSTMCell");
|
|
const $lstmBias = (0, _tensorUtilEnv.convertToTensor)(lstmBias, "lstmBias", "basicLSTMCell");
|
|
const $data = (0, _tensorUtilEnv.convertToTensor)(data, "data", "basicLSTMCell");
|
|
const $c = (0, _tensorUtilEnv.convertToTensor)(c, "c", "basicLSTMCell");
|
|
const $h = (0, _tensorUtilEnv.convertToTensor)(h, "h", "basicLSTMCell");
|
|
const combined = (0, _concat.concat)([
|
|
$data,
|
|
$h
|
|
], 1);
|
|
const weighted = (0, _matMul.matMul)(combined, $lstmKernel);
|
|
const res = (0, _add.add)(weighted, $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 = (0, _slice.slice)(res, [
|
|
0,
|
|
0
|
|
], sliceSize);
|
|
const j = (0, _slice.slice)(res, [
|
|
0,
|
|
sliceCols
|
|
], sliceSize);
|
|
const f = (0, _slice.slice)(res, [
|
|
0,
|
|
sliceCols * 2
|
|
], sliceSize);
|
|
const o = (0, _slice.slice)(res, [
|
|
0,
|
|
sliceCols * 3
|
|
], sliceSize);
|
|
const newC = (0, _add.add)((0, _mul.mul)((0, _sigmoid.sigmoid)(i), (0, _tanh.tanh)(j)), (0, _mul.mul)($c, (0, _sigmoid.sigmoid)((0, _add.add)($forgetBias, f))));
|
|
const newH = (0, _mul.mul)((0, _tanh.tanh)(newC), (0, _sigmoid.sigmoid)(o));
|
|
return [
|
|
newC,
|
|
newH
|
|
];
|
|
}
|
|
const basicLSTMCell = /* @__PURE__ */ (0, _operation.op)({
|
|
basicLSTMCell_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","./add":"aynh7","./concat":"1NOyL","./mat_mul":"fiMp4","./mul":"fOWrC","./operation":"ip64W","./sigmoid":"81E16","./slice":"dr7Gq","./tanh":"jXQuL","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1NOyL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concat", ()=>concat);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _clone = require("./clone");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 concatenate along. Defaults to 0 (the first dim).
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
|
|
*/ function concat_(tensors, axis = 0) {
|
|
(0, _util.assert)(tensors.length >= 1, ()=>"Pass at least one tensor to concat");
|
|
const $tensors = (0, _tensorUtilEnv.convertToTensorArray)(tensors, "tensors", "concat", "string_or_numeric");
|
|
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}. `);
|
|
});
|
|
if ($tensors.length === 1) return (0, _clone.clone)($tensors[0]);
|
|
const inputs = $tensors;
|
|
const attr = {
|
|
axis
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Concat), inputs, attr);
|
|
}
|
|
const concat = /* @__PURE__ */ (0, _operation.op)({
|
|
concat_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./clone":"jmQ7S","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fiMp4":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "matMul", ()=>matMul);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "matMul");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "matMul");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
const attrs = {
|
|
transposeA,
|
|
transposeB
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.BatchMatMul), inputs, attrs);
|
|
}
|
|
const matMul = /* @__PURE__ */ (0, _operation.op)({
|
|
matMul_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"81E16":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sigmoid", ()=>sigmoid);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "sigmoid", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Sigmoid), inputs);
|
|
}
|
|
const sigmoid = /* @__PURE__ */ (0, _operation.op)({
|
|
sigmoid_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dr7Gq":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "slice", ()=>slice);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "slice", "string_or_numeric");
|
|
if ($x.rank === 0) throw new Error("Slicing scalar is not possible");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
begin,
|
|
size
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Slice), inputs, attrs);
|
|
}
|
|
const slice = /* @__PURE__ */ (0, _operation.op)({
|
|
slice_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jXQuL":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tanh", ()=>tanh);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "tanh", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Tanh), inputs);
|
|
}
|
|
const tanh = /* @__PURE__ */ (0, _operation.op)({
|
|
tanh_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5A2j5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchToSpaceND", ()=>batchToSpaceND);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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 inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
blockShape,
|
|
crops
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.BatchToSpaceND), inputs, attrs);
|
|
}
|
|
const batchToSpaceND = /* @__PURE__ */ (0, _operation.op)({
|
|
batchToSpaceND_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5eVFD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchNorm", ()=>batchNorm);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _batchnormUtil = require("./batchnorm_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 a `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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "batchNorm");
|
|
const $mean = (0, _tensorUtilEnv.convertToTensor)(mean, "mean", "batchNorm");
|
|
const $variance = (0, _tensorUtilEnv.convertToTensor)(variance, "variance", "batchNorm");
|
|
let $scale;
|
|
if (scale != null) $scale = (0, _tensorUtilEnv.convertToTensor)(scale, "scale", "batchNorm");
|
|
let $offset;
|
|
if (offset != null) $offset = (0, _tensorUtilEnv.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 = (0, _batchnormUtil.xAs4D)($x);
|
|
const inputs = {
|
|
x: x4D,
|
|
scale: $scale,
|
|
offset: $offset,
|
|
mean: $mean,
|
|
variance: $variance
|
|
};
|
|
const attrs = {
|
|
varianceEpsilon
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.FusedBatchNorm), inputs, attrs);
|
|
return (0, _reshape.reshape)(res, $x.shape);
|
|
}
|
|
const batchNorm = /* @__PURE__ */ (0, _operation.op)({
|
|
batchNorm_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./batchnorm_util":"bTZAD","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bTZAD":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "xAs4D", ()=>xAs4D);
|
|
var _reshape = require("./reshape");
|
|
function xAs4D(x) {
|
|
let x4D;
|
|
if (x.rank === 0 || x.rank === 1) x4D = (0, _reshape.reshape)(x, [
|
|
1,
|
|
1,
|
|
1,
|
|
x.size
|
|
]);
|
|
else if (x.rank === 2) x4D = (0, _reshape.reshape)(x, [
|
|
1,
|
|
1,
|
|
x.shape[0],
|
|
x.shape[1]
|
|
]);
|
|
else if (x.rank === 3) x4D = (0, _reshape.reshape)(x, [
|
|
1,
|
|
x.shape[0],
|
|
x.shape[1],
|
|
x.shape[2]
|
|
]);
|
|
else x4D = x;
|
|
return x4D;
|
|
}
|
|
|
|
},{"./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9ULx9":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchNorm2d", ()=>batchNorm2d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _batchnorm = require("./batchnorm");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "batchNorm");
|
|
const $mean = (0, _tensorUtilEnv.convertToTensor)(mean, "mean", "batchNorm");
|
|
const $variance = (0, _tensorUtilEnv.convertToTensor)(variance, "variance", "batchNorm");
|
|
let $scale;
|
|
if (scale != null) $scale = (0, _tensorUtilEnv.convertToTensor)(scale, "scale", "batchNorm");
|
|
let $offset;
|
|
if (offset != null) $offset = (0, _tensorUtilEnv.convertToTensor)(offset, "offset", "batchNorm");
|
|
_util.assert($x.rank === 2, ()=>`Error in batchNorm2D: x must be rank 2 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 (0, _batchnorm.batchNorm)($x, $mean, $variance, $offset, $scale, varianceEpsilon);
|
|
}
|
|
const batchNorm2d = /* @__PURE__ */ (0, _operation.op)({
|
|
batchNorm2d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./batchnorm":"5eVFD","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"y3kug":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchNorm3d", ()=>batchNorm3d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _batchnorm = require("./batchnorm");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "batchNorm");
|
|
const $mean = (0, _tensorUtilEnv.convertToTensor)(mean, "mean", "batchNorm");
|
|
const $variance = (0, _tensorUtilEnv.convertToTensor)(variance, "variance", "batchNorm");
|
|
let $scale;
|
|
if (scale != null) $scale = (0, _tensorUtilEnv.convertToTensor)(scale, "scale", "batchNorm");
|
|
let $offset;
|
|
if (offset != null) $offset = (0, _tensorUtilEnv.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 (0, _batchnorm.batchNorm)($x, $mean, $variance, $offset, $scale, varianceEpsilon);
|
|
}
|
|
const batchNorm3d = /* @__PURE__ */ (0, _operation.op)({
|
|
batchNorm3d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./batchnorm":"5eVFD","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4l9oM":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchNorm4d", ()=>batchNorm4d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _batchnorm = require("./batchnorm");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "batchNorm");
|
|
const $mean = (0, _tensorUtilEnv.convertToTensor)(mean, "mean", "batchNorm");
|
|
const $variance = (0, _tensorUtilEnv.convertToTensor)(variance, "variance", "batchNorm");
|
|
let $scale;
|
|
if (scale != null) $scale = (0, _tensorUtilEnv.convertToTensor)(scale, "scale", "batchNorm");
|
|
let $offset;
|
|
if (offset != null) $offset = (0, _tensorUtilEnv.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 (0, _batchnorm.batchNorm)($x, $mean, $variance, $offset, $scale, varianceEpsilon);
|
|
}
|
|
const batchNorm4d = /* @__PURE__ */ (0, _operation.op)({
|
|
batchNorm4d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./batchnorm":"5eVFD","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gW00L":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "bincount", ()=>bincount);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Outputs a vector with length `size` and the same dtype as `weights`.
|
|
*
|
|
* If `weights` are empty, then index `i` stores the number of times the value
|
|
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
|
|
* sum of the value in `weights` at each index where the corresponding value in
|
|
* `x` is `i`.
|
|
*
|
|
* Values in `x` outside of the range [0, size) are ignored.
|
|
*
|
|
* @param x The input int tensor, rank 1.
|
|
* @param weights The weights tensor, must have the same shape as x, or a
|
|
* length-0 Tensor, in which case it acts as all weights equal to 1.
|
|
* @param size Non-negative integer.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Reduction'}
|
|
*/ function bincount_(x, weights, size) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "bincount");
|
|
const $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "bincount");
|
|
_util.assert($x.dtype === "int32", ()=>`Error in bincount: input ` + `dtype must be int32, but got ${$x.dtype}`);
|
|
_util.assert(size >= 0, ()=>`size must be non-negative, but got ${size}.`);
|
|
_util.assert($weights.size === $x.size || $weights.size === 0, ()=>`Error in bincount: weights must have the same size as input or` + `0-length, but got input shape: ${$x.shape}, weights shape: ` + `${$weights.shape}.`);
|
|
const inputs = {
|
|
x: $x,
|
|
weights: $weights
|
|
};
|
|
const attrs = {
|
|
size
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Bincount), inputs, attrs);
|
|
}
|
|
const bincount = /* @__PURE__ */ (0, _operation.op)({
|
|
bincount_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jmT4J":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "bitwiseAnd", ()=>bitwiseAnd);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _utilBase = require("../util_base");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Bitwise `AND` operation for input tensors.
|
|
*
|
|
* Given two input tensors, returns a new tensor
|
|
* with the `AND` calculated values.
|
|
*
|
|
* The method supports int32 values
|
|
*
|
|
*
|
|
* ```js
|
|
* const x = tf.tensor1d([0, 5, 3, 14], 'int32');
|
|
* const y = tf.tensor1d([5, 0, 7, 11], 'int32');
|
|
* tf.bitwiseAnd(x, y).print();
|
|
* ```
|
|
*
|
|
* @param x The input tensor to be calculated.
|
|
* @param y The input tensor to be calculated.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Logical'}
|
|
*/ function bitwiseAnd_(x, y) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "bitwiseAnd");
|
|
const $y = (0, _tensorUtilEnv.convertToTensor)(y, "y", "bitwiseAnd");
|
|
if (!(0, _utilBase.arraysEqual)($x.shape, $y.shape)) throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${$x.shape}, y: ${$y.shape}`);
|
|
if ($x.dtype !== "int32" || $y.dtype !== "int32") throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${$x.dtype} and type of y: ${$y.dtype}`);
|
|
const inputs = {
|
|
a: $x,
|
|
b: $y
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.BitwiseAnd), inputs);
|
|
}
|
|
const bitwiseAnd = /* @__PURE__ */ (0, _operation.op)({
|
|
bitwiseAnd_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util_base":"4Vo4a","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"d9ZLh":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "broadcastArgs", ()=>broadcastArgs);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Return the shape of s0 op s1 with broadcast.
|
|
*
|
|
* compute r0, the broadcasted shape as a tensor.
|
|
* s0, s1 and r0 are all integer vectors.
|
|
*
|
|
* This function returns the shape of the result of an operation between
|
|
* two tensors of size s0 and s1 performed with broadcast.
|
|
*
|
|
* @param s0 A tensor representing a shape
|
|
* @param s1 A tensor representing a shape
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Transformations'}
|
|
*/ function broadcastArgs_(s0, s1) {
|
|
const shape1Input = (0, _tensorUtilEnv.convertToTensor)(s0, "s0", "broadcastArgs", "int32");
|
|
const shape2Input = (0, _tensorUtilEnv.convertToTensor)(s1, "s1", "broadcastArgs", "int32");
|
|
if (shape1Input.rank !== 1) throw new Error("broadcastArgs(): first input must be a vector (rank=1). " + `Has rank ${shape1Input.rank}`);
|
|
if (shape2Input.rank !== 1) throw new Error("broadcastArgs(): second input must be a vector (rank=1). " + `Has rank ${shape2Input.rank}`);
|
|
const inputs = {
|
|
s0: shape1Input,
|
|
s1: shape2Input
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.BroadcastArgs), inputs);
|
|
}
|
|
const broadcastArgs = /* @__PURE__ */ (0, _operation.op)({
|
|
broadcastArgs_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iMuoF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "broadcastTo", ()=>broadcastTo);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _utilBase = require("../util_base");
|
|
var _clone = require("./clone");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 it 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 = (0, _tensorUtilEnv.convertToTensor)(x, "broadcastTo", "x");
|
|
const xShape = input.shape;
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(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 = (0, _reshape.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 (0, _clone.clone)(input);
|
|
// TODO call broadcastTo kernel directly once backends implement broadcstTo
|
|
const inputs = {
|
|
x: input
|
|
};
|
|
const attrs = {
|
|
reps
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Tile), inputs, attrs);
|
|
}
|
|
const broadcastTo = /* @__PURE__ */ (0, _operation.op)({
|
|
broadcastTo_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util_base":"4Vo4a","./clone":"jmQ7S","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hVmez":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ceil", ()=>ceil);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "ceil", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Ceil), inputs);
|
|
}
|
|
const ceil = /* @__PURE__ */ (0, _operation.op)({
|
|
ceil_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cKbfV":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "clipByValue", ()=>clipByValue);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _fill = require("./fill");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "clipByValue");
|
|
_util.assert(clipValueMin <= clipValueMax, ()=>`Error in clip: min (${clipValueMin}) must be ` + `less than or equal to max (${clipValueMax}).`);
|
|
if (clipValueMin === clipValueMax) return (0, _fill.fill)($x.shape, clipValueMin, $x.dtype);
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
clipValueMin,
|
|
clipValueMax
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.ClipByValue), inputs, attrs);
|
|
}
|
|
const clipByValue = /* @__PURE__ */ (0, _operation.op)({
|
|
clipByValue_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./fill":"i7goe","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"i7goe":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fill", ()=>fill);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _util = require("../util");
|
|
var _utilBase = require("../util_base");
|
|
/**
|
|
* 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
|
|
* 'float32' if the given param value is a number, otherwise 'string'.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Creation'}
|
|
*/ function fill(shape, value, dtype) {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(shape);
|
|
dtype = dtype || (0, _util.inferDtype)(value);
|
|
const attrs = {
|
|
shape,
|
|
value,
|
|
dtype
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Fill), {}, attrs);
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../util":"ctavo","../util_base":"4Vo4a","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jI8Rd":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concat1d", ()=>concat1d);
|
|
var _concat = require("./concat");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 (0, _concat.concat)(tensors, 0 /* axis */ );
|
|
}
|
|
const concat1d = /* @__PURE__ */ (0, _operation.op)({
|
|
concat1d_
|
|
});
|
|
|
|
},{"./concat":"1NOyL","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2ZT6j":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concat2d", ()=>concat2d);
|
|
var _concat = require("./concat");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 (0, _concat.concat)(tensors, axis);
|
|
}
|
|
const concat2d = /* @__PURE__ */ (0, _operation.op)({
|
|
concat2d_
|
|
});
|
|
|
|
},{"./concat":"1NOyL","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g5T4x":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concat3d", ()=>concat3d);
|
|
var _concat = require("./concat");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 (0, _concat.concat)(tensors, axis);
|
|
}
|
|
const concat3d = /* @__PURE__ */ (0, _operation.op)({
|
|
concat3d_
|
|
});
|
|
|
|
},{"./concat":"1NOyL","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fsDG1":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concat4d", ()=>concat4d);
|
|
var _concat = require("./concat");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 (0, _concat.concat)(tensors, axis);
|
|
}
|
|
const concat4d = /* @__PURE__ */ (0, _operation.op)({
|
|
concat4d_
|
|
});
|
|
|
|
},{"./concat":"1NOyL","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2LKBX":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv1d", ()=>conv1d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _conv2D = require("./conv2d");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/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 A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function conv1d_(x, filter, stride, pad, dataFormat = "NWC", dilation = 1, dimRoundingMode) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "conv1d");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "conv1d");
|
|
let x3D = $x;
|
|
let reshapedTo3D = false;
|
|
if ($x.rank === 2) {
|
|
reshapedTo3D = true;
|
|
x3D = (0, _reshape.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}.`);
|
|
_convUtil.checkPadOnDimRoundingMode("conv1d", pad, dimRoundingMode);
|
|
_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(_convUtil.eitherStridesOrDilationsAreOne(stride, dilation), ()=>"Error in conv1D: Either stride or dilation must be 1. " + `Got stride ${stride} and dilation '${dilation}'`);
|
|
_util.assert(_convUtil.stridesOrDilationsArePositive(dilation), ()=>"Error in conv1D: Dilated rates should be larger than 0.");
|
|
_util.assert(_convUtil.stridesOrDilationsArePositive(stride), ()=>"Error in conv1D: Stride should be larger than 0.");
|
|
_util.assert(dataFormat === "NWC", ()=>`Error in conv1d: got dataFormat of ${dataFormat} but only NWC is currently supported.`);
|
|
const filter4D = (0, _reshape.reshape)($filter, [
|
|
1,
|
|
$filter.shape[0],
|
|
$filter.shape[1],
|
|
$filter.shape[2]
|
|
]);
|
|
const input4D = (0, _reshape.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 = (0, _conv2D.conv2d)(input4D, filter4D, strides, pad, conv2dDataFormat, dilations, dimRoundingMode);
|
|
if (reshapedTo3D) return (0, _reshape.reshape)(res, [
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return (0, _reshape.reshape)(res, [
|
|
res.shape[0],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
}
|
|
const conv1d = /* @__PURE__ */ (0, _operation.op)({
|
|
conv1d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./conv2d":"lmJyO","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lmJyO":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2d", ()=>conv2d);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/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 A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function conv2d_(x, filter, strides, pad, dataFormat = "NHWC", dilations = [
|
|
1,
|
|
1
|
|
], dimRoundingMode) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "conv2d", "float32");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "conv2d", "float32");
|
|
let x4D = $x;
|
|
let reshapedTo4D = false;
|
|
if ($x.rank === 3) {
|
|
reshapedTo4D = true;
|
|
x4D = (0, _reshape.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}.`);
|
|
_convUtil.checkPadOnDimRoundingMode("conv2d", pad, dimRoundingMode);
|
|
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(_convUtil.eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in conv2D: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
_util.assert(_convUtil.stridesOrDilationsArePositive(dilations), ()=>"Error in conv2D: Dilated rates should be larger than 0.");
|
|
_util.assert(_convUtil.stridesOrDilationsArePositive(strides), ()=>"Error in conv2D: Strides should be larger than 0.");
|
|
const inputs = {
|
|
x: x4D,
|
|
filter: $filter
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dilations,
|
|
dimRoundingMode
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.Conv2D), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const conv2d = /* @__PURE__ */ (0, _operation.op)({
|
|
conv2d_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kCheD":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2dTranspose", ()=>conv2dTranspose);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _conv2DBackpropInput = require("./conv2d_backprop_input");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function conv2dTranspose_(x, filter, outputShape, strides, pad, dimRoundingMode) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "conv2dTranspose");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "conv2dTranspose");
|
|
return (0, _conv2DBackpropInput.conv2DBackpropInput)(outputShape, $x, $filter, strides, pad, "NHWC", dimRoundingMode);
|
|
}
|
|
const conv2dTranspose = /* @__PURE__ */ (0, _operation.op)({
|
|
conv2dTranspose_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","./conv2d_backprop_input":"l0Ec6","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"l0Ec6":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2DBackpropInput", ()=>conv2DBackpropInput);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _util = require("../util");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*/ 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 = (0, _reshape.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]}.`);
|
|
_convUtil.checkPadOnDimRoundingMode("conv2dDerInput", pad, dimRoundingMode);
|
|
const inputs = {
|
|
dy: dy4D,
|
|
filter
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dimRoundingMode,
|
|
inputShape: xShape4D
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.Conv2DBackpropInput), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const conv2DBackpropInput = /* @__PURE__ */ (0, _operation.op)({
|
|
conv2DBackpropInput_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../util":"ctavo","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3stvE":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3d", ()=>conv3d);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "conv3d");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "conv3d");
|
|
let x5D = $x;
|
|
let reshapedTo5D = false;
|
|
if ($x.rank === 4) {
|
|
reshapedTo5D = true;
|
|
x5D = (0, _reshape.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((0, _convUtil.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.`);
|
|
_util.assert((0, _convUtil.stridesOrDilationsArePositive)(dilations), ()=>"Error in conv3D: Dilated rates should be larger than 0.");
|
|
_util.assert((0, _convUtil.stridesOrDilationsArePositive)(strides), ()=>"Error in conv3D: Strides should be larger than 0.");
|
|
const inputs = {
|
|
x: x5D,
|
|
filter: $filter
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dilations
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.Conv3D), inputs, attrs);
|
|
if (reshapedTo5D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3],
|
|
res.shape[4]
|
|
]);
|
|
return res;
|
|
}
|
|
const conv3d = /* @__PURE__ */ (0, _operation.op)({
|
|
conv3d_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4J2I2":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3dTranspose", ()=>conv3dTranspose);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _conv3DBackpropInput = require("./conv3d_backprop_input");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "conv3dTranspose");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "conv3dTranspose");
|
|
return (0, _conv3DBackpropInput.conv3DBackpropInput)(outputShape, $x, $filter, strides, pad);
|
|
}
|
|
const conv3dTranspose = /* @__PURE__ */ (0, _operation.op)({
|
|
conv3dTranspose_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","./conv3d_backprop_input":"fyxX7","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fyxX7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3DBackpropInput", ()=>conv3DBackpropInput);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 = (0, _reshape.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 inputs = {
|
|
dy: dy5D,
|
|
filter
|
|
};
|
|
const attrs = {
|
|
pad,
|
|
strides,
|
|
inputShape: xShape5D
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.Conv3DBackpropInputV2), inputs, attrs);
|
|
if (reshapedTo5D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3],
|
|
res.shape[4]
|
|
]);
|
|
return res;
|
|
}
|
|
const conv3DBackpropInput = /* @__PURE__ */ (0, _operation.op)({
|
|
conv3DBackpropInput_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../util":"ctavo","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aBory":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cos", ()=>cos);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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. Must be float32 type.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Basic math'}
|
|
*/ function cos_(x) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "cos", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Cos), inputs);
|
|
}
|
|
const cos = /* @__PURE__ */ (0, _operation.op)({
|
|
cos_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kFKmS":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cosh", ()=>cosh);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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. Must be float32 type.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Basic math'}
|
|
*/ function cosh_(x) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "cosh", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Cosh), inputs);
|
|
}
|
|
const cosh = /* @__PURE__ */ (0, _operation.op)({
|
|
cosh_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gorKt":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cumprod", ()=>cumprod);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Computes the cumulative product of a `tf.Tensor` along `axis`.
|
|
*
|
|
* ```js
|
|
* const x = tf.tensor([1, 2, 3, 4]);
|
|
* x.cumprod().print();
|
|
* ```
|
|
* ```js
|
|
* const x = tf.tensor([[1, 2], [3, 4]]);
|
|
* x.cumprod().print();
|
|
* ```
|
|
*
|
|
* @param x The input tensor to cumulatively multiply.
|
|
* @param axis The axis along which to multiply. Optional. Defaults to 0.
|
|
* @param exclusive Whether to perform exclusive cumulative product. Optional.
|
|
* Defaults to false. If set to true then the product 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 multiply in the opposite direction. Optional.
|
|
* Defaults to false.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Scan'}
|
|
*/ function cumprod_(x, axis = 0, exclusive = false, reverse = false) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "cumprod");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
exclusive,
|
|
reverse
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Cumprod), inputs, attrs);
|
|
}
|
|
const cumprod = /* @__PURE__ */ (0, _operation.op)({
|
|
cumprod_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8KDcI":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cumsum", ()=>cumsum);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "cumsum");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
exclusive,
|
|
reverse
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Cumsum), inputs, attrs);
|
|
}
|
|
const cumsum = /* @__PURE__ */ (0, _operation.op)({
|
|
cumsum_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3PEDs":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "denseBincount", ()=>denseBincount);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Outputs a vector with length `size` and the same dtype as `weights`.
|
|
*
|
|
* If `weights` are empty, then index `i` stores the number of times the value
|
|
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
|
|
* sum of the value in `weights` at each index where the corresponding value in
|
|
* `x` is `i`.
|
|
*
|
|
* Values in `x` outside of the range [0, size) are ignored.
|
|
*
|
|
* @param x The input int tensor, rank 1 or rank 2.
|
|
* @param weights The weights tensor, must have the same shape as x, or a
|
|
* length-0 Tensor, in which case it acts as all weights equal to 1.
|
|
* @param size Non-negative integer.
|
|
* @param binaryOutput Optional. Whether the kernel should count the appearance
|
|
* or number of occurrences. Defaults to False.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Reduction'}
|
|
*/ function denseBincount_(x, weights, size, binaryOutput = false) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "denseBincount");
|
|
const $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "denseBincount");
|
|
_util.assert($x.dtype === "int32", ()=>`Error in denseBincount: input ` + `dtype must be int32, but got ${$x.dtype}`);
|
|
_util.assert($x.rank <= 2, ()=>`Error in denseBincount: input must be at most rank 2, but got ` + `rank ${$x.rank}.`);
|
|
_util.assert(size >= 0, ()=>`size must be non-negative, but got ${size}.`);
|
|
_util.assert($weights.size === $x.size || $weights.size === 0, ()=>`Error in denseBincount: weights must have the same shape as x or ` + `0-length, but got x shape: ${$x.shape}, weights shape: ` + `${$weights.shape}.`);
|
|
const inputs = {
|
|
x: $x,
|
|
weights: $weights
|
|
};
|
|
const attrs = {
|
|
size,
|
|
binaryOutput
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.DenseBincount), inputs, attrs);
|
|
}
|
|
const denseBincount = /* @__PURE__ */ (0, _operation.op)({
|
|
denseBincount_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ipPbw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthToSpace", ()=>depthToSpace);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "depthToSpace", "float32");
|
|
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(blockSize > 1, ()=>`blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);
|
|
_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 inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
blockSize,
|
|
dataFormat
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.DepthToSpace), inputs, attrs);
|
|
}
|
|
const depthToSpace = /* @__PURE__ */ (0, _operation.op)({
|
|
depthToSpace_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cZHpb":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2d", ()=>depthwiseConv2d);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/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 A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function depthwiseConv2d_(x, filter, strides, pad, dataFormat = "NHWC", dilations = [
|
|
1,
|
|
1
|
|
], dimRoundingMode) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "depthwiseConv2d", "float32");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "depthwiseConv2d", "float32");
|
|
let x4D = $x;
|
|
let reshapedTo4D = false;
|
|
if ($x.rank === 3) {
|
|
reshapedTo4D = true;
|
|
x4D = (0, _reshape.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}.`);
|
|
const inChannels = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
|
|
_util.assert(inChannels === $filter.shape[2], ()=>`Error in depthwiseConv2d: number of input channels ` + `(${inChannels}) must match the inChannels dimension in ` + `filter ${$filter.shape[2]}.`);
|
|
_convUtil.checkPadOnDimRoundingMode("depthwiseConv2d", pad, dimRoundingMode);
|
|
const inputs = {
|
|
x: x4D,
|
|
filter: $filter
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dilations,
|
|
dimRoundingMode
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.DepthwiseConv2dNative), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const depthwiseConv2d = /* @__PURE__ */ (0, _operation.op)({
|
|
depthwiseConv2d_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3orNc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "diag", ()=>diag);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Returns a diagonal tensor with 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.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [4, 2])
|
|
*
|
|
* tf.diag(x).print()
|
|
* ```
|
|
* @param x The input tensor.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Creation'}
|
|
*/ function diag_(x) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "diag");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Diag), inputs);
|
|
}
|
|
const diag = /* @__PURE__ */ (0, _operation.op)({
|
|
diag_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7hUfK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "dilation2d", ()=>dilation2d);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* Computes the grayscale dilation over the input `x`.
|
|
*
|
|
* @param x The input tensor, rank 3 or rank 4 of shape
|
|
* `[batch, height, width, depth]`. If rank 3, batch of 1 is assumed.
|
|
* @param filter The filter tensor, rank 3, of shape
|
|
* `[filterHeight, filterWidth, depth]`.
|
|
* @param strides The strides of the sliding window for each dimension of the
|
|
* input tensor: `[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 1*1x1.
|
|
* - For more info, see this guide:
|
|
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
|
|
* @param dataFormat Specify the data format of the input and output data.
|
|
* Defaults to 'NHWC'. Only 'NHWC' is currently supported. 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
|
|
* for atrous morphological dilation. 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.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function dilation2d_(x, filter, strides, pad, dilations = [
|
|
1,
|
|
1
|
|
], dataFormat = "NHWC") {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "dilation2d");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "dilation2d");
|
|
_util.assert($x.rank === 3 || $x.rank === 4, ()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ` + `${$x.rank}.`);
|
|
_util.assert($filter.rank === 3, ()=>`Error in dilation2d: filter must be rank 3, but got rank ` + `${$filter.rank}.`);
|
|
_util.assert(dataFormat === "NHWC", ()=>`Error in dilation2d: Only NHWC is currently supported, ` + `but got dataFormat of ${dataFormat}`);
|
|
let x4D = $x;
|
|
let reshapedTo4D = false;
|
|
if ($x.rank === 3) {
|
|
x4D = (0, _reshape.reshape)($x, [
|
|
1,
|
|
$x.shape[0],
|
|
$x.shape[1],
|
|
$x.shape[2]
|
|
]);
|
|
reshapedTo4D = true;
|
|
}
|
|
_util.assert(x4D.shape[3] === $filter.shape[2], ()=>`Error in dilation2d: input and filter must have the same depth: ${x4D.shape[3]} vs ${$filter.shape[2]}`);
|
|
const inputs = {
|
|
x: x4D,
|
|
filter: $filter
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dilations
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.Dilation2D), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const dilation2d = /* @__PURE__ */ (0, _operation.op)({
|
|
dilation2d_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aw8lb":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "divNoNan", ()=>divNoNan);
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _div = require("./div");
|
|
var _equal = require("./equal");
|
|
var _operation = require("./operation");
|
|
var _where = require("./where");
|
|
var _zerosLike = require("./zeros_like");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "div");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "div");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
const divResult = (0, _div.div)($a, $b);
|
|
const zeros = (0, _zerosLike.zerosLike)(divResult);
|
|
const bEqualsZero = (0, _equal.equal)($b, zeros);
|
|
return (0, _where.where)(bEqualsZero, zeros, divResult);
|
|
}
|
|
const divNoNan = /* @__PURE__ */ (0, _operation.op)({
|
|
divNoNan_
|
|
});
|
|
|
|
},{"../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./div":"5ZT1h","./equal":"htEqc","./operation":"ip64W","./where":"47cKc","./zeros_like":"1Xjct","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"htEqc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "equal", ()=>equal);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "equal", "string_or_numeric");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "equal", "string_or_numeric");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Equal), inputs);
|
|
}
|
|
const equal = /* @__PURE__ */ (0, _operation.op)({
|
|
equal_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eLo4J":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getBroadcastDims", ()=>getBroadcastDims);
|
|
/**
|
|
* Returns the axes in the output space that should be reduced to produce
|
|
* the input space.
|
|
*/ parcelHelpers.export(exports, "getReductionAxes", ()=>getReductionAxes);
|
|
parcelHelpers.export(exports, "assertAndGetBroadcastShape", ()=>assertAndGetBroadcastShape);
|
|
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;
|
|
}
|
|
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 l = Math.max(shapeA.length, shapeB.length);
|
|
const result = new Array(l);
|
|
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[l - i - 1] = b;
|
|
else if (b === 1) result[l - i - 1] = a;
|
|
else if (a !== b) {
|
|
const errMsg = `Operands could not be broadcast together with shapes ` + `${shapeA} and ${shapeB}.`;
|
|
throw Error(errMsg);
|
|
} else result[l - i - 1] = a;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"47cKc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "where", ()=>where);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastTo = require("./broadcast_to");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 dtype as `a` and with shape that is
|
|
* compatible with `a`.
|
|
* @return A tensor with same dtype as `a` and `b`, and shape that is
|
|
* broadcastable from `a` and `b`.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Logical'}
|
|
*/ function where_(condition, a, b) {
|
|
const $a = (0, _tensorUtilEnv.convertToTensor)(a, "a", "where");
|
|
const $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "where");
|
|
const $condition = (0, _tensorUtilEnv.convertToTensor)(condition, "condition", "where", "bool");
|
|
// TODO: move this logic to forward function when the broadcastTo op is
|
|
// implemented in WASM.
|
|
// Find the broadcastable shape for $condition, $a, and $b.
|
|
const broadcastShape = (0, _broadcastUtil.assertAndGetBroadcastShape)((0, _broadcastUtil.assertAndGetBroadcastShape)($condition.shape, $a.shape), $b.shape);
|
|
const $broadcastedCondition = (0, _broadcastTo.broadcastTo)($condition, broadcastShape);
|
|
const $broadcastedA = (0, _broadcastTo.broadcastTo)($a, broadcastShape);
|
|
const $broadcastedB = (0, _broadcastTo.broadcastTo)($b, broadcastShape);
|
|
const inputs = {
|
|
condition: $broadcastedCondition,
|
|
t: $broadcastedA,
|
|
e: $broadcastedB
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Select), inputs);
|
|
}
|
|
const where = /* @__PURE__ */ (0, _operation.op)({
|
|
where_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./broadcast_to":"iMuoF","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1Xjct":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "zerosLike", ()=>zerosLike);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "zerosLike");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.ZerosLike), inputs);
|
|
}
|
|
const zerosLike = /* @__PURE__ */ (0, _operation.op)({
|
|
zerosLike_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b1M9k":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "dot", ()=>dot);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _matMul = require("./mat_mul");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(t1, "t1", "dot");
|
|
const $t2 = (0, _tensorUtilEnv.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 = (0, _reshape.reshape)($t1, [
|
|
1,
|
|
-1
|
|
]);
|
|
const t22D = (0, _reshape.reshape)($t2, [
|
|
-1,
|
|
1
|
|
]);
|
|
const t1t2 = (0, _matMul.matMul)(t12D, t22D);
|
|
return (0, _reshape.reshape)(t1t2, []);
|
|
} else if ($t1.rank === 1 && $t2.rank === 2) {
|
|
const t12D = (0, _reshape.reshape)($t1, [
|
|
1,
|
|
-1
|
|
]);
|
|
const t22D = (0, _reshape.reshape)($t2, [
|
|
$t2.shape[0],
|
|
$t2.shape[1]
|
|
]);
|
|
const t1t2 = (0, _matMul.matMul)(t12D, t22D);
|
|
return (0, _reshape.reshape)(t1t2, [
|
|
t1t2.size
|
|
]);
|
|
} else if ($t1.rank === 2 && $t2.rank === 1) {
|
|
const t22D = (0, _reshape.reshape)($t2, [
|
|
-1,
|
|
1
|
|
]);
|
|
const t1t2 = (0, _matMul.matMul)($t1, t22D);
|
|
return (0, _reshape.reshape)(t1t2, [
|
|
t1t2.size
|
|
]);
|
|
} else {
|
|
const t22D = (0, _reshape.reshape)($t2, [
|
|
$t2.shape[0],
|
|
$t2.shape[1]
|
|
]);
|
|
const t1t2 = (0, _matMul.matMul)($t1, t22D);
|
|
return t1t2;
|
|
}
|
|
}
|
|
const dot = /* @__PURE__ */ (0, _operation.op)({
|
|
dot_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./mat_mul":"fiMp4","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"adKPG":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Tensor contraction over specified indices and outer product.
|
|
*
|
|
* `einsum` allows defining Tensors by defining their element-wise computation.
|
|
* This computation is based on
|
|
* [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).
|
|
*
|
|
* Some special cases include:
|
|
*
|
|
* Matrix multiplication:
|
|
* ```js
|
|
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
|
|
* const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);
|
|
* x.print();
|
|
* y.print();
|
|
* tf.einsum('ij,jk->ik', x, y).print();
|
|
* ```
|
|
*
|
|
* Dot product:
|
|
* ```js
|
|
* const x = tf.tensor1d([1, 2, 3]);
|
|
* const y = tf.tensor1d([0, 1, 2]);
|
|
* x.print();
|
|
* y.print();
|
|
* tf.einsum('i,i->', x, y).print();
|
|
* ```
|
|
*
|
|
* Batch dot product:
|
|
* ```js
|
|
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
|
|
* const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);
|
|
* x.print();
|
|
* y.print();
|
|
* tf.einsum('bi,bi->b', x, y).print();
|
|
* ```
|
|
*
|
|
* Outer prouduct:
|
|
* ```js
|
|
* const x = tf.tensor1d([1, 3, 5]);
|
|
* const y = tf.tensor1d([2, 4, 6]);
|
|
* x.print();
|
|
* y.print();
|
|
* tf.einsum('i,j->ij', x, y).print();
|
|
* ```
|
|
*
|
|
* Matrix transpose:
|
|
* ```js
|
|
* const x = tf.tensor2d([[1, 2], [3, 4]]);
|
|
* x.print();
|
|
* tf.einsum('ij->ji', x).print();
|
|
* ```
|
|
*
|
|
* Batch matrix transpose:
|
|
* ```js
|
|
* const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);
|
|
* x.print();
|
|
* tf.einsum('bij->bji', x).print();
|
|
* ```
|
|
*
|
|
* Limitations:
|
|
*
|
|
* This implementation of einsum has the following limitations:
|
|
*
|
|
* - Does not support >2 input tensors.
|
|
* - Does not support duplicate axes for any given input tensor. E.g., equation
|
|
* 'ii->' is not supported.
|
|
* - The `...` notation is not supported.
|
|
*
|
|
* @param equation a string describing the contraction, in the same format as
|
|
* [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).
|
|
* @param tensors the input(s) to contract (each one a Tensor), whose shapes
|
|
* should be consistent with equation.
|
|
* @returns The output tensor.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Matrices'}
|
|
*/ parcelHelpers.export(exports, "einsum_", ()=>einsum_);
|
|
parcelHelpers.export(exports, "einsum", ()=>einsum);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
function einsum_(equation, ...tensors) {
|
|
const $tensors = tensors.map((t, i)=>(0, _tensorUtilEnv.convertToTensor)(t, `tensors${i}`, "einsum"));
|
|
const attrs = {
|
|
equation
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Einsum), $tensors, attrs);
|
|
}
|
|
const einsum = /* @__PURE__ */ (0, _operation.op)({
|
|
einsum_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dE197":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "elu", ()=>elu);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Computes exponential linear element-wise: `x > 0 ? x : (e ^ x) - 1`.
|
|
*
|
|
* ```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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "elu", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Elu), inputs);
|
|
}
|
|
const elu = /* @__PURE__ */ (0, _operation.op)({
|
|
elu_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"f2yaA":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ensureShape", ()=>ensureShape);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _utilBase = require("../util_base");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Checks the input tensor mathes the given shape.
|
|
*
|
|
* Given an input tensor, returns a new tensor with the same values as the
|
|
* input tensor with shape `shape`.
|
|
*
|
|
* The method supports the null value in tensor. It will still check the shapes,
|
|
* and null is a placeholder.
|
|
*
|
|
*
|
|
* ```js
|
|
* const x = tf.tensor1d([1, 2, 3, 4]);
|
|
* const y = tf.tensor1d([1, null, 3, 4]);
|
|
* const z = tf.tensor2d([1, 2, 3, 4], [2,2]);
|
|
* tf.ensureShape(x, [4]).print();
|
|
* tf.ensureShape(y, [4]).print();
|
|
* tf.ensureShape(z, [null, 2]).print();
|
|
* ```
|
|
*
|
|
* @param x The input tensor to be ensured.
|
|
* @param shape A TensorShape representing the shape of this tensor, an array
|
|
* or null.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Transformations'}
|
|
*/ function ensureShape_(x, shape) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "ensureShape", "string_or_numeric");
|
|
if (!(0, _utilBase.arraysEqualWithNull)($x.shape, shape)) throw new Error(`EnsureShape: Shape of tensor ${$x.shape} is not compatible with expected shape ${shape}`);
|
|
return x;
|
|
}
|
|
const ensureShape = /* @__PURE__ */ (0, _operation.op)({
|
|
ensureShape_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util_base":"4Vo4a","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"e0JJC":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "erf", ()=>erf);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _cast = require("./cast");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Computes Gauss 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "erf");
|
|
_util.assert($x.dtype === "int32" || $x.dtype === "float32", ()=>"Input dtype must be `int32` or `float32`.");
|
|
if ($x.dtype === "int32") $x = (0, _cast.cast)($x, "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Erf), inputs);
|
|
}
|
|
const erf = /* @__PURE__ */ (0, _operation.op)({
|
|
erf_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./cast":"b4VDA","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8OAGY":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "euclideanNorm", ()=>euclideanNorm);
|
|
var _norm = require("./norm");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Computes the Euclidean norm of scalar, vectors, and matrices.
|
|
*
|
|
* ```js
|
|
* const x = tf.tensor1d([1, 2, 3, 4]);
|
|
*
|
|
* x.euclideanNorm().print(); // or tf.euclideanNorm(x)
|
|
* ```
|
|
*
|
|
* @param x The input array.
|
|
* @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. euclideanNorm(x) is equivalent
|
|
* to euclideanNorm(x.reshape([-1])). If axis is an 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 has the same dimensionality
|
|
* as the input.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Matrices'}
|
|
*/ function euclideanNorm_(x, axis = null, keepDims = false) {
|
|
return (0, _norm.norm)(x, "euclidean", axis, keepDims);
|
|
}
|
|
const euclideanNorm = /* @__PURE__ */ (0, _operation.op)({
|
|
euclideanNorm_
|
|
});
|
|
|
|
},{"./norm":"eOnCA","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eOnCA":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "norm", ()=>norm);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _abs = require("./abs");
|
|
var _axisUtil = require("./axis_util");
|
|
var _max = require("./max");
|
|
var _min = require("./min");
|
|
var _operation = require("./operation");
|
|
var _pow = require("./pow");
|
|
var _reshape = require("./reshape");
|
|
var _scalar = require("./scalar");
|
|
var _sqrt = require("./sqrt");
|
|
var _square = require("./square");
|
|
var _sum = require("./sum");
|
|
/**
|
|
* 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 an 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 has the same dimensionality
|
|
* as the input.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Matrices'}
|
|
*/ function norm_(x, ord = "euclidean", axis = null, keepDims = false) {
|
|
x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "norm");
|
|
const norm = normImpl(x, ord, axis);
|
|
let keepDimsShape = norm.shape;
|
|
if (keepDims) {
|
|
const axes = (0, _util.parseAxisParam)(axis, x.shape);
|
|
keepDimsShape = _axisUtil.expandShapeToKeepDim(norm.shape, axes);
|
|
}
|
|
return (0, _reshape.reshape)(norm, keepDimsShape);
|
|
}
|
|
function normImpl(x, p, axis = null) {
|
|
if (x.rank === 0) return (0, _abs.abs)(x);
|
|
// consider vector when no axis is specified
|
|
if (x.rank !== 1 && axis === null) return normImpl((0, _reshape.reshape)(x, [
|
|
-1
|
|
]), p, axis);
|
|
// vector
|
|
if (x.rank === 1 || typeof axis === "number" || Array.isArray(axis) && axis.length === 1) {
|
|
if (p === 1) return (0, _sum.sum)((0, _abs.abs)(x), axis);
|
|
if (p === Infinity) return (0, _max.max)((0, _abs.abs)(x), axis);
|
|
if (p === -Infinity) return (0, _min.min)((0, _abs.abs)(x), axis);
|
|
if (p === "euclidean" || p === 2) // norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2
|
|
return (0, _sqrt.sqrt)((0, _sum.sum)((0, _pow.pow)((0, _abs.abs)(x), (0, _scalar.scalar)(2, "int32")), axis));
|
|
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 (0, _max.max)((0, _sum.sum)((0, _abs.abs)(x), axis[0]), axis[1] - 1);
|
|
if (p === Infinity) return (0, _max.max)((0, _sum.sum)((0, _abs.abs)(x), axis[1]), axis[0]);
|
|
if (p === -Infinity) return (0, _min.min)((0, _sum.sum)((0, _abs.abs)(x), axis[1]), axis[0]);
|
|
if (p === "fro" || p === "euclidean") // norm(x) = sqrt(sum(pow(x, 2)))
|
|
return (0, _sqrt.sqrt)((0, _sum.sum)((0, _square.square)(x), axis));
|
|
throw new Error(`Error in norm: invalid ord value: ${p}`);
|
|
}
|
|
throw new Error(`Error in norm: invalid axis: ${axis}`);
|
|
}
|
|
const norm = /* @__PURE__ */ (0, _operation.op)({
|
|
norm_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./abs":"iZQ4e","./axis_util":"hzS4B","./max":"cb6Hb","./min":"fhwke","./operation":"ip64W","./pow":"gezpC","./reshape":"ew3wZ","./scalar":"7lhC8","./sqrt":"cOGi9","./square":"cOosW","./sum":"5awd0","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hzS4B":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Returns true if the axis specifies the inner most dimensions of the
|
|
* array.
|
|
*/ parcelHelpers.export(exports, "axesAreInnerMostDims", ()=>axesAreInnerMostDims);
|
|
parcelHelpers.export(exports, "combineLocations", ()=>combineLocations);
|
|
parcelHelpers.export(exports, "computeOutAndReduceShapes", ()=>computeOutAndReduceShapes);
|
|
parcelHelpers.export(exports, "expandShapeToKeepDim", ()=>expandShapeToKeepDim);
|
|
parcelHelpers.export(exports, "assertAxesAreInnerMostDims", ()=>assertAxesAreInnerMostDims);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getAxesPermutation", ()=>getAxesPermutation);
|
|
/** Returns the axes permutation that undoes the original permutation. */ parcelHelpers.export(exports, "getUndoAxesPermutation", ()=>getUndoAxesPermutation);
|
|
parcelHelpers.export(exports, "getInnerMostAxes", ()=>getInnerMostAxes);
|
|
var _util = require("../util");
|
|
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.`);
|
|
}
|
|
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;
|
|
}
|
|
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;
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cb6Hb":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "max", ()=>max);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 a
|
|
* `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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "max");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
reductionIndices: axis,
|
|
keepDims
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Max), inputs, attrs);
|
|
}
|
|
const max = /* @__PURE__ */ (0, _operation.op)({
|
|
max_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fhwke":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "min", ()=>min);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "min");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
keepDims
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Min), inputs, attrs);
|
|
}
|
|
const min = /* @__PURE__ */ (0, _operation.op)({
|
|
min_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gezpC":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pow", ()=>pow);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(base, "base", "pow");
|
|
let $exp = (0, _tensorUtilEnv.convertToTensor)(exp, "exp", "pow");
|
|
[$base, $exp] = (0, _tensorUtil.makeTypesMatch)($base, $exp);
|
|
const inputs = {
|
|
a: $base,
|
|
b: $exp
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Pow), inputs);
|
|
}
|
|
const pow = /* @__PURE__ */ (0, _operation.op)({
|
|
pow_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7lhC8":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "scalar", ()=>scalar);
|
|
var _util = require("../util");
|
|
var _tensorOpsUtil = require("./tensor_ops_util");
|
|
function scalar(value, dtype) {
|
|
if (((0, _util.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" && (0, _util.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 (0, _tensorOpsUtil.makeTensor)(value, shape, inferredShape, dtype);
|
|
}
|
|
|
|
},{"../util":"ctavo","./tensor_ops_util":"adYmX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cOGi9":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sqrt", ()=>sqrt);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "sqrt", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Sqrt), inputs);
|
|
}
|
|
const sqrt = /* @__PURE__ */ (0, _operation.op)({
|
|
sqrt_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cOosW":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "square", ()=>square);
|
|
var _engine = require("../engine");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "square");
|
|
const attrs = {};
|
|
return (0, _engine.ENGINE).runKernel("Square", {
|
|
x: $x
|
|
}, attrs);
|
|
}
|
|
const square = /* @__PURE__ */ (0, _operation.op)({
|
|
square_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5awd0":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sum", ()=>sum);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _cast = require("./cast");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "sum");
|
|
if ($x.dtype === "bool") $x = (0, _cast.cast)($x, "int32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
keepDims
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Sum), inputs, attrs);
|
|
}
|
|
const sum = /* @__PURE__ */ (0, _operation.op)({
|
|
sum_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./cast":"b4VDA","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1CsGu":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "exp", ()=>exp);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "exp");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Exp), inputs);
|
|
}
|
|
const exp = /* @__PURE__ */ (0, _operation.op)({
|
|
exp_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lc7t7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "expandDims", ()=>expandDims);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 are 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 $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "expandDims", "string_or_numeric");
|
|
_util.assert(axis <= $x.rank, ()=>"Axis must be <= rank of the tensor");
|
|
const inputs = {
|
|
input: $x
|
|
};
|
|
const attrs = {
|
|
dim: axis
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.ExpandDims), inputs, attrs);
|
|
}
|
|
const expandDims = /* @__PURE__ */ (0, _operation.op)({
|
|
expandDims_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lDAq4":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "expm1", ()=>expm1);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "expm1");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Expm1), inputs);
|
|
}
|
|
const expm1 = /* @__PURE__ */ (0, _operation.op)({
|
|
expm1_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hDQ1U":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "eye", ()=>eye);
|
|
var _buffer = require("./buffer");
|
|
var _expandDims = require("./expand_dims");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
var _tile = require("./tile");
|
|
/**
|
|
* 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 = (0, _buffer.buffer)([
|
|
numRows,
|
|
numColumns
|
|
], dtype);
|
|
const n = numRows <= numColumns ? numRows : numColumns;
|
|
for(let i = 0; i < n; ++i)buff.set(1, i, i);
|
|
const out = (0, _reshape.reshape)(buff.toTensor(), [
|
|
numRows,
|
|
numColumns
|
|
]);
|
|
if (batchShape == null) return out;
|
|
else {
|
|
if (batchShape.length === 1) return (0, _tile.tile)((0, _expandDims.expandDims)(out, 0), [
|
|
batchShape[0],
|
|
1,
|
|
1
|
|
]);
|
|
else if (batchShape.length === 2) // tslint:disable-next-line:no-unnecessary-type-assertion
|
|
return (0, _tile.tile)((0, _expandDims.expandDims)((0, _expandDims.expandDims)(out, 0), 0), [
|
|
batchShape[0],
|
|
batchShape[1],
|
|
1,
|
|
1
|
|
]);
|
|
else if (batchShape.length === 3) // tslint:disable-next-line:no-unnecessary-type-assertion
|
|
return (0, _tile.tile)((0, _expandDims.expandDims)((0, _expandDims.expandDims)((0, _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 = /* @__PURE__ */ (0, _operation.op)({
|
|
eye_
|
|
});
|
|
|
|
},{"./buffer":"dYyY7","./expand_dims":"lc7t7","./operation":"ip64W","./reshape":"ew3wZ","./tile":"gzqG2","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gzqG2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tile", ()=>tile);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 tf.tile(a, [2])
|
|
* ```
|
|
*
|
|
* ```js
|
|
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
|
|
*
|
|
* a.tile([1, 2]).print(); // or tf.tile(a, [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 $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "tile", "string_or_numeric");
|
|
_util.assert($x.rank === reps.length, ()=>`Error in transpose: rank of input ${$x.rank} ` + `must match length of reps ${reps}.`);
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
reps
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Tile), inputs, attrs);
|
|
}
|
|
const tile = /* @__PURE__ */ (0, _operation.op)({
|
|
tile_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"35qCf":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "floor", ()=>floor);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "floor", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Floor), inputs);
|
|
}
|
|
const floor = /* @__PURE__ */ (0, _operation.op)({
|
|
floor_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5p5vK":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gather", ()=>gather);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 are to be gathered.
|
|
* @param indices The indices of the values to extract.
|
|
* @param axis The axis over which to select values. Defaults to 0.
|
|
* @param batchDims Optional. The number of batch dimensions. It must be less
|
|
* than or equal to rank(indices). Defaults to 0.
|
|
* The output tensor will have shape of
|
|
* `x.shape[:axis] + indices.shape[batchDims:] + x.shape[axis + 1:]`
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
|
|
*/ function gather_(x, indices, axis = 0, batchDims = 0) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "gather");
|
|
const $indices = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "gather", "int32");
|
|
const inputs = {
|
|
x: $x,
|
|
indices: $indices
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
batchDims
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.GatherV2), inputs, attrs);
|
|
}
|
|
const gather = /* @__PURE__ */ (0, _operation.op)({
|
|
gather_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3Nh8O":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "greater", ()=>greater);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "greater", "string_or_numeric");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "greater", "string_or_numeric");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Greater), inputs);
|
|
}
|
|
const greater = /* @__PURE__ */ (0, _operation.op)({
|
|
greater_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"f7S2c":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "greaterEqual", ()=>greaterEqual);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "greaterEqual", "string_or_numeric");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "greaterEqual", "string_or_numeric");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.GreaterEqual), inputs);
|
|
}
|
|
const greaterEqual = /* @__PURE__ */ (0, _operation.op)({
|
|
greaterEqual_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lDORm":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "imag", ()=>imag);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(input, "input", "imag");
|
|
const inputs = {
|
|
input: $input
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Imag), inputs);
|
|
}
|
|
const imag = /* @__PURE__ */ (0, _operation.op)({
|
|
imag_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ddlWF":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isFinite", ()=>isFinite);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "isFinite");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.IsFinite), inputs);
|
|
}
|
|
const isFinite = /* @__PURE__ */ (0, _operation.op)({
|
|
isFinite_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2QZvv":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isInf", ()=>isInf);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "isInf");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.IsInf), inputs);
|
|
}
|
|
const isInf = /* @__PURE__ */ (0, _operation.op)({
|
|
isInf_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"58UC5":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isNaN", ()=>isNaN);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Returns 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "isNaN");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.IsNan), inputs);
|
|
}
|
|
const isNaN = /* @__PURE__ */ (0, _operation.op)({
|
|
isNaN_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aRBcm":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "leakyRelu", ()=>leakyRelu);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "leakyRelu");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
alpha
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.LeakyRelu), inputs, attrs);
|
|
}
|
|
const leakyRelu = /* @__PURE__ */ (0, _operation.op)({
|
|
leakyRelu_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hCGN5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "less", ()=>less);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "less", "string_or_numeric");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "less", "string_or_numeric");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Less), inputs);
|
|
}
|
|
const less = /* @__PURE__ */ (0, _operation.op)({
|
|
less_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"j9Jhy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "lessEqual", ()=>lessEqual);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "lessEqual", "string_or_numeric");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "lessEqual", "string_or_numeric");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.LessEqual), inputs);
|
|
}
|
|
const lessEqual = /* @__PURE__ */ (0, _operation.op)({
|
|
lessEqual_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7Vd0v":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "linspace", ()=>linspace);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
function linspace(start, stop, num) {
|
|
if (num <= 0) throw new Error("The number of values should be positive.");
|
|
const attrs = {
|
|
start,
|
|
stop,
|
|
num
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.LinSpace), {}, attrs);
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eTOXs":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "localResponseNormalization", ()=>localResponseNormalization);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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 = (0, _reshape.reshape)($x, [
|
|
1,
|
|
$x.shape[0],
|
|
$x.shape[1],
|
|
$x.shape[2]
|
|
]);
|
|
}
|
|
const inputs = {
|
|
x: x4D
|
|
};
|
|
const attrs = {
|
|
depthRadius,
|
|
bias,
|
|
alpha,
|
|
beta
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.LRN), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
else return res;
|
|
}
|
|
const localResponseNormalization = /* @__PURE__ */ (0, _operation.op)({
|
|
localResponseNormalization_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iex5O":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "log", ()=>log);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "log", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Log), inputs);
|
|
}
|
|
const log = /* @__PURE__ */ (0, _operation.op)({
|
|
log_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jKhH4":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "log1p", ()=>log1p);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "log1p");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Log1p), inputs);
|
|
}
|
|
const log1p = /* @__PURE__ */ (0, _operation.op)({
|
|
log1p_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2X6mM":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logSigmoid", ()=>logSigmoid);
|
|
var _gradients = require("../gradients");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _mul = require("./mul");
|
|
var _neg = require("./neg");
|
|
var _operation = require("./operation");
|
|
var _sigmoid = require("./sigmoid");
|
|
var _softplus = require("./softplus");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "logSigmoid");
|
|
// Use a custom gradient to maintain previous implementation.
|
|
// There is no LogSigmoid kernel in TF so we can't use engine.runKernel
|
|
// directly
|
|
const customOp = (0, _gradients.customGrad)((x)=>{
|
|
// TODO(yassogba) we can remove the chained softplus call here only
|
|
// after backends have modualrized softplus at which point we can call
|
|
// engine runKernel(..., Sotfplus, ...) directly.
|
|
const value = (0, _neg.neg)((0, _softplus.softplus)((0, _neg.neg)(x)));
|
|
const gradFunc = (dy)=>{
|
|
const derX = (0, _mul.mul)(dy, (0, _sigmoid.sigmoid)((0, _neg.neg)(x)));
|
|
return derX;
|
|
};
|
|
return {
|
|
value,
|
|
gradFunc
|
|
};
|
|
});
|
|
return customOp($x);
|
|
}
|
|
const logSigmoid = /* @__PURE__ */ (0, _operation.op)({
|
|
logSigmoid_
|
|
});
|
|
|
|
},{"../gradients":"dDHpg","../tensor_util_env":"6vfHI","./mul":"fOWrC","./neg":"3jQfI","./operation":"ip64W","./sigmoid":"81E16","./softplus":"4zLJS","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dDHpg":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "customGrad", ()=>customGrad);
|
|
parcelHelpers.export(exports, "variableGrads", ()=>variableGrads);
|
|
parcelHelpers.export(exports, "valueAndGrad", ()=>valueAndGrad);
|
|
parcelHelpers.export(exports, "valueAndGrads", ()=>valueAndGrads);
|
|
parcelHelpers.export(exports, "grad", ()=>grad);
|
|
parcelHelpers.export(exports, "grads", ()=>grads);
|
|
var _engine = require("./engine");
|
|
var _tensor = require("./tensor");
|
|
var _tensorUtilEnv = require("./tensor_util_env");
|
|
var _util = require("./util");
|
|
/**
|
|
* 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 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "tf.grad", "string_or_numeric");
|
|
const $dy = dy != null ? (0, _tensorUtilEnv.convertToTensor)(dy, "dy", "tf.grad") : null;
|
|
return (0, _engine.ENGINE).tidy(()=>{
|
|
const { value, grads } = (0, _engine.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 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 = (0, _tensorUtilEnv.convertToTensorArray)(args, "args", "tf.grads", "string_or_numeric");
|
|
const $dy = dy != null ? (0, _tensorUtilEnv.convertToTensor)(dy, "dy", "tf.grads") : null;
|
|
return (0, _engine.ENGINE).tidy(()=>{
|
|
const { value, grads } = (0, _engine.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 (0, _tensor.Tensor), ()=>"The x passed in valueAndGrad(f)(x) must be a tensor");
|
|
_util.assert(dy == null || dy instanceof (0, _tensor.Tensor), ()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");
|
|
const { grads, value } = (0, _engine.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 (0, _tensor.Tensor)), ()=>"The args passed in valueAndGrads(f)(args) must be array of tensors");
|
|
_util.assert(dy == null || dy instanceof (0, _tensor.Tensor), ()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");
|
|
const res = (0, _engine.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 (0, _tensor.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 (0, _engine.ENGINE).registeredVariables)varList.push((0, _engine.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 } = (0, _engine.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 passed 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 tensors.
|
|
*
|
|
* ```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 (0, _engine.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.`);
|
|
}
|
|
|
|
},{"./engine":"1g2qo","./tensor":"cJNoh","./tensor_util_env":"6vfHI","./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3jQfI":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "neg", ()=>neg);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "neg");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Neg), inputs);
|
|
}
|
|
const neg = /* @__PURE__ */ (0, _operation.op)({
|
|
neg_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4zLJS":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "softplus", ()=>softplus);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "softplus");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Softplus), inputs);
|
|
}
|
|
const softplus = /* @__PURE__ */ (0, _operation.op)({
|
|
softplus_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5yBCd":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logSoftmax", ()=>logSoftmax);
|
|
var _gradients = require("../gradients");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _cast = require("./cast");
|
|
var _exp = require("./exp");
|
|
var _log = require("./log");
|
|
var _max = require("./max");
|
|
var _mul = require("./mul");
|
|
var _operation = require("./operation");
|
|
var _sub = require("./sub");
|
|
var _sum = require("./sum");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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 forward: ForwardFunc<Tensor> = (backend, save) => {
|
|
// const keepDims = true;
|
|
// const xMax = max(logits, axis, true);
|
|
// const shifted = sub(logits, xMax);
|
|
// const value =
|
|
// sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis,
|
|
// keepDims)));
|
|
// save([value]);
|
|
// return value;
|
|
// };
|
|
// Use a custom gradient for numerical stability.
|
|
const customOp = (0, _gradients.customGrad)((logits, save)=>{
|
|
const keepDims = true;
|
|
const xMax = (0, _max.max)(logits, axis, true);
|
|
const shifted = (0, _sub.sub)(logits, xMax);
|
|
const value = (0, _sub.sub)((0, _cast.cast)(shifted, "float32"), (0, _log.log)((0, _sum.sum)((0, _exp.exp)(shifted), axis, keepDims)));
|
|
save([
|
|
value
|
|
]);
|
|
const gradFunc = (dy, saved)=>{
|
|
const [value] = saved;
|
|
const keepDims = true;
|
|
const softmax = (0, _exp.exp)(value);
|
|
return (0, _sub.sub)(dy, (0, _mul.mul)((0, _sum.sum)(dy, axis, keepDims), softmax));
|
|
};
|
|
return {
|
|
value,
|
|
gradFunc
|
|
};
|
|
});
|
|
return customOp($logits);
|
|
// TODO Use Engine.runKernel when CPU/WebGL/WASM backends implement this.
|
|
// const inputs: LogSoftmaxInputs = {logits: $logits};
|
|
// const attrs: LogSoftmaxAttrs = {axis};
|
|
// return ENGINE.runKernel(
|
|
// LogSoftmax, inputs as unknown as NamedTensorMap,
|
|
// attrs as unknown as NamedAttrMap);
|
|
}
|
|
const logSoftmax = /* @__PURE__ */ (0, _operation.op)({
|
|
logSoftmax_
|
|
});
|
|
|
|
},{"../gradients":"dDHpg","../tensor_util_env":"6vfHI","./cast":"b4VDA","./exp":"1CsGu","./log":"iex5O","./max":"cb6Hb","./mul":"fOWrC","./operation":"ip64W","./sub":"jBBQ2","./sum":"5awd0","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jBBQ2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sub", ()=>sub);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "sub");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "sub");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Sub), inputs);
|
|
}
|
|
const sub = /* @__PURE__ */ (0, _operation.op)({
|
|
sub_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"feRCM":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logSumExp", ()=>logSumExp);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _add = require("./add");
|
|
var _axisUtil = require("./axis_util");
|
|
var _exp = require("./exp");
|
|
var _log = require("./log");
|
|
var _max = require("./max");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
var _sub = require("./sub");
|
|
var _sum = require("./sum");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "logSumExp");
|
|
const axes = (0, _util.parseAxisParam)(axis, $x.shape);
|
|
const xMax = (0, _max.max)($x, axes, true);
|
|
const a = (0, _sub.sub)($x, xMax);
|
|
const b = (0, _exp.exp)(a);
|
|
const c = (0, _sum.sum)(b, axes);
|
|
const d = (0, _log.log)(c);
|
|
const res = (0, _add.add)((0, _reshape.reshape)(xMax, d.shape), d);
|
|
if (keepDims) {
|
|
const newShape = (0, _axisUtil.expandShapeToKeepDim)(res.shape, axes);
|
|
return (0, _reshape.reshape)(res, newShape);
|
|
}
|
|
return res;
|
|
}
|
|
const logSumExp = /* @__PURE__ */ (0, _operation.op)({
|
|
logSumExp_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./add":"aynh7","./axis_util":"hzS4B","./exp":"1CsGu","./log":"iex5O","./max":"cb6Hb","./operation":"ip64W","./reshape":"ew3wZ","./sub":"jBBQ2","./sum":"5awd0","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6zYjJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalAnd", ()=>logicalAnd);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "logicalAnd", "bool");
|
|
const $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "logicalAnd", "bool");
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.LogicalAnd), inputs);
|
|
}
|
|
const logicalAnd = /* @__PURE__ */ (0, _operation.op)({
|
|
logicalAnd_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gSuOh":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalNot", ()=>logicalNot);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "logicalNot", "bool");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.LogicalNot), inputs);
|
|
}
|
|
const logicalNot = /* @__PURE__ */ (0, _operation.op)({
|
|
logicalNot_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dH6xG":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalOr", ()=>logicalOr);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "logicalOr", "bool");
|
|
const $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "logicalOr", "bool");
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.LogicalOr), inputs);
|
|
}
|
|
const logicalOr = /* @__PURE__ */ (0, _operation.op)({
|
|
logicalOr_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7Y9m5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalXor", ()=>logicalXor);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _logicalAnd = require("./logical_and");
|
|
var _logicalNot = require("./logical_not");
|
|
var _logicalOr = require("./logical_or");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "logicalXor", "bool");
|
|
const $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "logicalXor", "bool");
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
// x ^ y = (x | y) & ~(x & y)
|
|
return (0, _logicalAnd.logicalAnd)((0, _logicalOr.logicalOr)(a, b), (0, _logicalNot.logicalNot)((0, _logicalAnd.logicalAnd)(a, b)));
|
|
}
|
|
const logicalXor = /* @__PURE__ */ (0, _operation.op)({
|
|
logicalXor_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./logical_and":"6zYjJ","./logical_not":"gSuOh","./logical_or":"dH6xG","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2XtFq":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Searches for where a value would go in a sorted sequence.
|
|
*
|
|
* This is not a method for checking containment (like javascript in).
|
|
*
|
|
* The typical use case for this operation is "binning", "bucketing", or
|
|
* "discretizing". The values are assigned to bucket-indices based on the edges
|
|
* listed in 'sortedSequence'. This operation returns the bucket-index for each
|
|
* value.
|
|
*
|
|
* The index returned corresponds to the first edge greater than or equal to the
|
|
* value.
|
|
*
|
|
* The axis is not settable for this operation. It always operates on the
|
|
* innermost dimension (axis=-1). The operation will accept any number of outer
|
|
* dimensions.
|
|
*
|
|
* Note: This operation assumes that 'lowerBound' is sorted along the
|
|
* innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not
|
|
* sorted no error is raised and the content of the returned tensor is not well
|
|
* defined.
|
|
*
|
|
* ```js
|
|
* const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);
|
|
* let values = tf.tensor1d([0.0, 4.1, 12.0]);
|
|
* const result1 = tf.lowerBound(edges, values);
|
|
* result1.print(); // [1, 2, 4]
|
|
*
|
|
* const seq = tf.tensor1d([0, 3, 9, 10, 10]);
|
|
* values = tf.tensor1d([0, 4, 10]);
|
|
* const result2 = tf.lowerBound(seq, values);
|
|
* result2.print(); // [0, 2, 3]
|
|
*
|
|
* const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],
|
|
* [1., 2., 3., 4., 5.]]);
|
|
* values = tf.tensor2d([[9.8, 2.1, 4.3],
|
|
* [0.1, 6.6, 4.5, ]]);
|
|
* const result3 = tf.lowerBound(sortedSequence, values);
|
|
* result3.print(); // [[4, 1, 2], [0, 5, 4]]
|
|
* ```
|
|
* @param sortedSequence: N-D. Sorted sequence.
|
|
* @param values: N-D. Search values.
|
|
* @return An N-D int32 tensor the size of values containing the result of
|
|
* applying lower bound to each value. The result is not a global index to
|
|
* the entire Tensor, but the index in the last dimension.
|
|
* @doc {heading: 'Operations', subheading: 'Evaluation'}
|
|
*/ parcelHelpers.export(exports, "lowerBound", ()=>lowerBound);
|
|
var _searchSorted = require("./search_sorted");
|
|
function lowerBound(sortedSequence, values) {
|
|
return (0, _searchSorted.searchSorted)(sortedSequence, values, "left");
|
|
}
|
|
|
|
},{"./search_sorted":"4gaGh","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4gaGh":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "searchSorted", ()=>searchSorted);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _utilBase = require("../util_base");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
const INT32_MAX = 2147483648;
|
|
/**
|
|
* Searches for where a value would go in a sorted sequence.
|
|
*
|
|
* This is not a method for checking containment (like javascript in).
|
|
*
|
|
* The typical use case for this operation is "binning", "bucketing", or
|
|
* "discretizing". The values are assigned to bucket-indices based on the edges
|
|
* listed in 'sortedSequence'. This operation returns the bucket-index for each
|
|
* value.
|
|
*
|
|
* The side argument controls which index is returned if a value lands exactly
|
|
* on an edge.
|
|
*
|
|
* The axis is not settable for this operation. It always operates on the
|
|
* innermost dimension (axis=-1). The operation will accept any number of outer
|
|
* dimensions.
|
|
*
|
|
* Note: This operation assumes that 'sortedSequence' is sorted along the
|
|
* innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not
|
|
* sorted no error is raised and the content of the returned tensor is not well
|
|
* defined.
|
|
*
|
|
* ```js
|
|
* const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);
|
|
* let values = tf.tensor1d([0.0, 4.1, 12.0]);
|
|
* const result1 = tf.searchSorted(edges, values, 'left');
|
|
* result1.print(); // [1, 2, 4]
|
|
*
|
|
* const seq = tf.tensor1d([0, 3, 9, 10, 10]);
|
|
* values = tf.tensor1d([0, 4, 10]);
|
|
* const result2 = tf.searchSorted(seq, values, 'left');
|
|
* result2.print(); // [0, 2, 3]
|
|
* const result3 = tf.searchSorted(seq, values, 'right');
|
|
* result3.print(); // [1, 2, 5]
|
|
*
|
|
* const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],
|
|
* [1., 2., 3., 4., 5.]]);
|
|
* values = tf.tensor2d([[9.8, 2.1, 4.3],
|
|
* [0.1, 6.6, 4.5, ]]);
|
|
* const result4 = tf.searchSorted(sortedSequence, values, 'left');
|
|
* result4.print(); // [[4, 1, 2], [0, 5, 4]]
|
|
* ```
|
|
* @param sortedSequence: N-D. Sorted sequence.
|
|
* @param values: N-D. Search values.
|
|
* @param side: 'left'|'right'. Defaults to 'left'. 'left' corresponds to lower
|
|
* bound and 'right' to upper bound.
|
|
* @return An N-D int32 tensor the size of values containing the result of
|
|
* applying either lower bound or upper bound (depending on side) to each
|
|
* value. The result is not a global index to the entire Tensor, but the
|
|
* index in the last dimension.
|
|
* @doc {heading: 'Operations', subheading: 'Evaluation'}
|
|
*/ function searchSorted_(sortedSequence, values, side = "left") {
|
|
const $sortedSequence = (0, _tensorUtilEnv.convertToTensor)(sortedSequence, "sortedSequence", "searchSorted");
|
|
const $values = (0, _tensorUtilEnv.convertToTensor)(values, "values", "searchSorted");
|
|
const sequenceSize = $sortedSequence.shape[$sortedSequence.shape.length - 1];
|
|
const valuesSize = $values.shape[$values.shape.length - 1];
|
|
const $sortedSequence2D = (0, _reshape.reshape)($sortedSequence, [
|
|
-1,
|
|
sequenceSize
|
|
]);
|
|
const $values2D = (0, _reshape.reshape)($values, [
|
|
-1,
|
|
valuesSize
|
|
]);
|
|
if ($sortedSequence2D.rank < 2) throw new Error(`Sorted input argument must be at least 2-dimensional`);
|
|
if ($sortedSequence2D.shape[0] !== $values2D.shape[0]) throw new Error(`Leading dimension of 'sortedSequence' and 'values' must match.`);
|
|
if ((0, _utilBase.sizeFromShape)($values2D.shape) >= INT32_MAX) throw new Error(`values tensor size must less than ${INT32_MAX}`);
|
|
if ($sortedSequence2D.shape[1] >= INT32_MAX) throw new Error(`trailing dim_size must less than ${INT32_MAX} for int32 output type, was ${$sortedSequence2D.shape[1]}`);
|
|
const inputs = {
|
|
sortedSequence: $sortedSequence2D,
|
|
values: $values2D
|
|
};
|
|
const attrs = {
|
|
side
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.SearchSorted), inputs, attrs);
|
|
}
|
|
const searchSorted = /* @__PURE__ */ (0, _operation.op)({
|
|
searchSorted_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util_base":"4Vo4a","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hx37d":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPool", ()=>maxPool);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
|
|
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*/ function maxPool_(x, filterSize, strides, pad, dimRoundingMode) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "maxPool");
|
|
const dilations = 1;
|
|
let x4D = $x;
|
|
let reshapedTo4D = false;
|
|
if ($x.rank === 3) {
|
|
reshapedTo4D = true;
|
|
x4D = (0, _reshape.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(_convUtil.eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in maxPool: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
_convUtil.checkPadOnDimRoundingMode("maxPool", pad, dimRoundingMode);
|
|
const inputs = {
|
|
x: x4D
|
|
};
|
|
const attrs = {
|
|
filterSize,
|
|
strides,
|
|
pad,
|
|
dimRoundingMode
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.MaxPool), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const maxPool = /* @__PURE__ */ (0, _operation.op)({
|
|
maxPool_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"z14HA":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPool3d", ()=>maxPool3d);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
|
|
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
* @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.
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function maxPool3d_(x, filterSize = [
|
|
1,
|
|
1,
|
|
1
|
|
], strides, pad, dimRoundingMode, dataFormat = "NDHWC") {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "maxPool3d");
|
|
let x5D = $x;
|
|
let reshapedTo5D = false;
|
|
if ($x.rank === 4) {
|
|
reshapedTo5D = true;
|
|
x5D = (0, _reshape.reshape)($x, [
|
|
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}`);
|
|
(0, _convUtil.checkPadOnDimRoundingMode)("maxPool3d", pad, dimRoundingMode);
|
|
const inputs = {
|
|
x: x5D
|
|
};
|
|
const attrs = {
|
|
filterSize,
|
|
strides,
|
|
pad,
|
|
dimRoundingMode,
|
|
dataFormat
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.MaxPool3D), inputs, attrs);
|
|
if (reshapedTo5D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3],
|
|
res.shape[4]
|
|
]);
|
|
return res;
|
|
}
|
|
const maxPool3d = /* @__PURE__ */ (0, _operation.op)({
|
|
maxPool3d_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hPUnJ":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPoolWithArgmax", ()=>maxPoolWithArgmax);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
|
|
* @param includeBatchIndex Defaults to False. Whether to include batch
|
|
* dimension in flattened index of argmax.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function maxPoolWithArgmax_(x, filterSize, strides, pad, includeBatchInIndex = false) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "maxPoolWithArgmax");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
filterSize,
|
|
strides,
|
|
pad,
|
|
includeBatchInIndex
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.MaxPoolWithArgmax), inputs, attrs);
|
|
return {
|
|
result: result[0],
|
|
indexes: result[1]
|
|
};
|
|
}
|
|
const maxPoolWithArgmax = /* @__PURE__ */ (0, _operation.op)({
|
|
maxPoolWithArgmax_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1nFpL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maximum", ()=>maximum);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _cast = require("./cast");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "maximum");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "maximum");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
if ($a.dtype === "bool") {
|
|
$a = (0, _cast.cast)($a, "int32");
|
|
$b = (0, _cast.cast)($b, "int32");
|
|
}
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Maximum), inputs);
|
|
}
|
|
const maximum = /* @__PURE__ */ (0, _operation.op)({
|
|
maximum_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./cast":"b4VDA","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hzzLs":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mean", ()=>mean);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "mean");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
keepDims
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Mean), inputs, attrs);
|
|
}
|
|
const mean = /* @__PURE__ */ (0, _operation.op)({
|
|
mean_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jFI6G":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Broadcasts parameters for evaluation on an N-D grid.
|
|
*
|
|
* Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`
|
|
* of N-D coordinate arrays for evaluating expressions on an N-D grid.
|
|
*
|
|
* Notes:
|
|
* `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.
|
|
* When the `indexing` argument is set to 'xy' (the default), the broadcasting
|
|
* instructions for the first two dimensions are swapped.
|
|
* Examples:
|
|
* Calling `const [X, Y] = meshgrid(x, y)` with the tensors
|
|
*
|
|
* ```javascript
|
|
* const x = [1, 2, 3];
|
|
* const y = [4, 5, 6];
|
|
* const [X, Y] = tf.meshgrid(x, y);
|
|
* // X = [[1, 2, 3],
|
|
* // [1, 2, 3],
|
|
* // [1, 2, 3]]
|
|
* // Y = [[4, 4, 4],
|
|
* // [5, 5, 5],
|
|
* // [6, 6, 6]]
|
|
* ```
|
|
*
|
|
* @param x Tensor with rank geq 1.
|
|
* @param y Tensor with rank geq 1.
|
|
* @param indexing
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
|
|
*/ parcelHelpers.export(exports, "meshgrid", ()=>meshgrid);
|
|
var _matMul = require("./mat_mul");
|
|
var _ones = require("./ones");
|
|
var _reshape = require("./reshape");
|
|
var _tensor = require("../tensor");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _utilBase = require("../util_base");
|
|
function meshgrid(x, y, { indexing = "xy" } = {}) {
|
|
if (indexing !== "xy" && indexing !== "ij") throw new TypeError(`${indexing} is not a valid third argument to meshgrid`);
|
|
if (x === undefined) return [];
|
|
let $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "meshgrid", x instanceof (0, _tensor.Tensor) ? x.dtype : "float32");
|
|
if (y === undefined) return [
|
|
$x
|
|
];
|
|
let $y = (0, _tensorUtilEnv.convertToTensor)(y, "y", "meshgrid", y instanceof (0, _tensor.Tensor) ? y.dtype : "float32");
|
|
const w = (0, _utilBase.sizeFromShape)($x.shape);
|
|
const h = (0, _utilBase.sizeFromShape)($y.shape);
|
|
if (indexing === "xy") {
|
|
$x = (0, _reshape.reshape)($x, [
|
|
1,
|
|
-1
|
|
]);
|
|
$y = (0, _reshape.reshape)($y, [
|
|
-1,
|
|
1
|
|
]);
|
|
return [
|
|
(0, _matMul.matMul)((0, _ones.ones)([
|
|
h,
|
|
1
|
|
], $x.dtype), $x),
|
|
(0, _matMul.matMul)($y, (0, _ones.ones)([
|
|
1,
|
|
w
|
|
], $y.dtype))
|
|
];
|
|
}
|
|
$x = (0, _reshape.reshape)($x, [
|
|
-1,
|
|
1
|
|
]);
|
|
$y = (0, _reshape.reshape)($y, [
|
|
1,
|
|
-1
|
|
]);
|
|
return [
|
|
(0, _matMul.matMul)($x, (0, _ones.ones)([
|
|
1,
|
|
h
|
|
], $x.dtype)),
|
|
(0, _matMul.matMul)((0, _ones.ones)([
|
|
w,
|
|
1
|
|
], $y.dtype), $y)
|
|
];
|
|
}
|
|
|
|
},{"./mat_mul":"fiMp4","./ones":"2gdnE","./reshape":"ew3wZ","../tensor":"cJNoh","../tensor_util_env":"6vfHI","../util_base":"4Vo4a","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2gdnE":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "ones", ()=>ones);
|
|
var _engine = require("../engine");
|
|
var _util = require("../util");
|
|
var _utilBase = require("../util_base");
|
|
var _complex = require("./complex");
|
|
var _zeros = require("./zeros");
|
|
function ones(shape, dtype = "float32") {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(shape);
|
|
if (dtype === "complex64") {
|
|
const real = ones(shape, "float32");
|
|
const imag = (0, _zeros.zeros)(shape, "float32");
|
|
return (0, _complex.complex)(real, imag);
|
|
}
|
|
const values = (0, _util.makeOnesTypedArray)((0, _util.sizeFromShape)(shape), dtype);
|
|
return (0, _engine.ENGINE).makeTensor(values, shape, dtype);
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../util":"ctavo","../util_base":"4Vo4a","./complex":"bPDAx","./zeros":"fcPHR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fcPHR":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "zeros", ()=>zeros);
|
|
var _engine = require("../engine");
|
|
var _util = require("../util");
|
|
var _complex = require("./complex");
|
|
function zeros(shape, dtype = "float32") {
|
|
(0, _util.assertNonNegativeIntegerDimensions)(shape);
|
|
if (dtype === "complex64") {
|
|
const real = zeros(shape, "float32");
|
|
const imag = zeros(shape, "float32");
|
|
return (0, _complex.complex)(real, imag);
|
|
}
|
|
const values = (0, _util.makeZerosTypedArray)((0, _util.sizeFromShape)(shape), dtype);
|
|
return (0, _engine.ENGINE).makeTensor(values, shape, dtype);
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../util":"ctavo","./complex":"bPDAx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"guwat":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "minimum", ()=>minimum);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _cast = require("./cast");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "minimum");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "minimum");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
if ($a.dtype === "bool") {
|
|
$a = (0, _cast.cast)($a, "int32");
|
|
$b = (0, _cast.cast)($b, "int32");
|
|
}
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Minimum), inputs);
|
|
}
|
|
const minimum = /* @__PURE__ */ (0, _operation.op)({
|
|
minimum_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./cast":"b4VDA","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1Sy5n":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mirrorPad", ()=>mirrorPad);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Pads a `tf.Tensor` using mirror padding.
|
|
*
|
|
* This operation implements the `REFLECT` and `SYMMETRIC` modes of pad.
|
|
*
|
|
* ```js
|
|
* const x = tf.range(0, 9).reshape([1, 1, 3, 3]);
|
|
* x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').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.
|
|
* In "reflect" mode, the padded regions do not include the borders,
|
|
* while in "symmetric" mode the padded regions do include the borders.
|
|
* For example, if the input is `[1, 2, 3]` and paddings is `[0, 2]`,
|
|
* then the output is `[1, 2, 3, 2, 1]` in "reflect" mode, and
|
|
* `[1, 2, 3, 3, 2]` in "symmetric" mode.
|
|
* If `mode` is "reflect" then both `paddings[D, 0]` and `paddings[D, 1]`
|
|
* must be no greater than `x.shape[D] - 1`. If mode is "symmetric"
|
|
* then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than
|
|
* `x.shape[D]`
|
|
* @param mode String to specify padding mode. Can be `'reflect' | 'symmetric'`
|
|
*/ /** @doc {heading: 'Tensors', subheading: 'Transformations'} */ function mirrorPad_(x, paddings, mode) {
|
|
_util.assert(mode === "reflect" || mode === "symmetric", ()=>`Invalid mode. Mode must be either reflect or symmetric. ` + `Got ${mode}.`);
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "mirrorPad");
|
|
if ($x.rank === 0) throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");
|
|
_util.assert(paddings.length === $x.rank, ()=>`Padding doesn't match input. Must be ${$x.rank}. ` + `Got ${paddings.length}.`);
|
|
const shapeOffset = mode === "reflect" ? 1 : 0;
|
|
for(let i = 0; i < $x.rank; i++){
|
|
_util.assert(paddings[i].length === 2, ()=>`Invalid number of paddings. Must be length of 2 each.`);
|
|
_util.assert(paddings[i][0] >= 0 && paddings[i][0] <= $x.shape[i] - shapeOffset && paddings[i][1] >= 0 && paddings[i][1] <= $x.shape[i] - shapeOffset, ()=>`Padding in dimension ${i} cannot be greater than or equal ` + `to ${$x.shape[i] - shapeOffset} or less than 0 for input of ` + `shape ${$x.shape}`);
|
|
}
|
|
const attrs = {
|
|
paddings,
|
|
mode
|
|
};
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.MirrorPad), inputs, attrs);
|
|
}
|
|
const mirrorPad = /* @__PURE__ */ (0, _operation.op)({
|
|
mirrorPad_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g5efu":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mod", ()=>mod);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "mod");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "mod");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Mod), inputs);
|
|
}
|
|
const mod = /* @__PURE__ */ (0, _operation.op)({
|
|
mod_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ef1IE":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "moments", ()=>moments);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _axisUtil = require("./axis_util");
|
|
var _cast = require("./cast");
|
|
var _mean = require("./mean");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
var _square = require("./square");
|
|
var _sub = require("./sub");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "moments");
|
|
const axes = (0, _util.parseAxisParam)(axis, x.shape);
|
|
const xMean = (0, _mean.mean)(x, axes, keepDims);
|
|
let keepDimsShape = xMean.shape;
|
|
if (!keepDims) keepDimsShape = (0, _axisUtil.expandShapeToKeepDim)(xMean.shape, axes);
|
|
const devSquared = (0, _square.square)((0, _sub.sub)((0, _cast.cast)(x, "float32"), (0, _reshape.reshape)(xMean, keepDimsShape)));
|
|
const variance = (0, _mean.mean)(devSquared, axes, keepDims);
|
|
return {
|
|
mean: xMean,
|
|
variance
|
|
};
|
|
}
|
|
const moments = /* @__PURE__ */ (0, _operation.op)({
|
|
moments_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./axis_util":"hzS4B","./cast":"b4VDA","./mean":"hzzLs","./operation":"ip64W","./reshape":"ew3wZ","./square":"cOosW","./sub":"jBBQ2","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lNZ3B":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "multiRNNCell", ()=>multiRNNCell);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(data, "data", "multiRNNCell");
|
|
const $c = (0, _tensorUtilEnv.convertToTensorArray)(c, "c", "multiRNNCell");
|
|
const $h = (0, _tensorUtilEnv.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
|
|
];
|
|
}
|
|
const multiRNNCell = /* @__PURE__ */ (0, _operation.op)({
|
|
multiRNNCell_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g1s8L":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "multinomial", ()=>multinomial);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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}`);
|
|
// TODO(lina128): Investigate correct seed behavior. The code seems not allow
|
|
// setting see to 0.
|
|
seed = seed || Math.random();
|
|
// The kernel only accepts (and returns) rank 2 tensors.
|
|
const logits2D = origRank === 1 ? (0, _reshape.reshape)($logits, [
|
|
1,
|
|
-1
|
|
]) : $logits;
|
|
const inputs = {
|
|
logits: logits2D
|
|
};
|
|
const attrs = {
|
|
numSamples,
|
|
seed,
|
|
normalized
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.Multinomial), inputs, attrs);
|
|
// tslint:disable-next-line:no-unnecessary-type-assertion
|
|
return origRank === 1 ? (0, _reshape.reshape)(res, [
|
|
res.size
|
|
]) : res;
|
|
}
|
|
const multinomial = /* @__PURE__ */ (0, _operation.op)({
|
|
multinomial_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gUKb0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "notEqual", ()=>notEqual);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "notEqual", "string_or_numeric");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "notEqual", "string_or_numeric");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.NotEqual), inputs);
|
|
}
|
|
const notEqual = /* @__PURE__ */ (0, _operation.op)({
|
|
notEqual_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"91jNM":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "oneHot", ()=>oneHot);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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`.
|
|
* `indices` used to encode prediction class must start from 0. For example,
|
|
* if you have 3 classes of data, class 1 should be encoded as 0, class 2
|
|
* should be 1, and class 3 should be 2.
|
|
*
|
|
* ```js
|
|
* tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();
|
|
* ```
|
|
*
|
|
* @param indices `tf.Tensor` of indices with dtype `int32`. Indices must
|
|
* start from 0.
|
|
* @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.
|
|
* @param dtype The dtype of the output tensor, default to 'int32'.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Creation'}
|
|
*/ function oneHot_(indices, depth, onValue = 1, offValue = 0, dtype = "int32") {
|
|
if (depth < 2) throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);
|
|
const $indices = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "oneHot", "int32");
|
|
const inputs = {
|
|
indices: $indices
|
|
};
|
|
const attrs = {
|
|
dtype,
|
|
depth,
|
|
onValue,
|
|
offValue
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.OneHot), inputs, attrs);
|
|
}
|
|
const oneHot = /* @__PURE__ */ (0, _operation.op)({
|
|
oneHot_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7TDfu":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "onesLike", ()=>onesLike);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "onesLike");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.OnesLike), inputs);
|
|
}
|
|
const onesLike = /* @__PURE__ */ (0, _operation.op)({
|
|
onesLike_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"emoMO":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "outerProduct", ()=>outerProduct);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _matMul = require("./mat_mul");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(v1, "v1", "outerProduct");
|
|
const $v2 = (0, _tensorUtilEnv.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 = (0, _reshape.reshape)($v1, [
|
|
-1,
|
|
1
|
|
]);
|
|
const v22D = (0, _reshape.reshape)($v2, [
|
|
1,
|
|
-1
|
|
]);
|
|
return (0, _matMul.matMul)(v12D, v22D);
|
|
}
|
|
const outerProduct = /* @__PURE__ */ (0, _operation.op)({
|
|
outerProduct_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./mat_mul":"fiMp4","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"89mWw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pad", ()=>pad);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Pads a `tf.Tensor` with a given value and paddings.
|
|
*
|
|
* This operation implements `CONSTANT` mode. For `REFLECT` and `SYMMETRIC`,
|
|
* refer to `tf.mirrorPad`.
|
|
*
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "pad");
|
|
if ($x.rank === 0) throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
|
|
const attrs = {
|
|
paddings,
|
|
constantValue
|
|
};
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.PadV2), inputs, attrs);
|
|
}
|
|
const pad = /* @__PURE__ */ (0, _operation.op)({
|
|
pad_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gOSFg":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pad1d", ()=>pad1d);
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _pad = require("./pad");
|
|
/**
|
|
* Pads a `tf.Tensor1D` with a given value and paddings. See `pad` for details.
|
|
*/ function pad1d_(x, paddings, constantValue = 0) {
|
|
(0, _util.assert)(paddings.length === 2, ()=>"Invalid number of paddings. Must be length of 2.");
|
|
return (0, _pad.pad)(x, [
|
|
paddings
|
|
], constantValue);
|
|
}
|
|
const pad1d = /* @__PURE__ */ (0, _operation.op)({
|
|
pad1d_
|
|
});
|
|
|
|
},{"../util":"ctavo","./operation":"ip64W","./pad":"89mWw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2QXo6":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pad2d", ()=>pad2d);
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _pad = require("./pad");
|
|
/**
|
|
* Pads a `tf.Tensor2D` with a given value and paddings. See `pad` for details.
|
|
*/ function pad2d_(x, paddings, constantValue = 0) {
|
|
(0, _util.assert)(paddings.length === 2 && paddings[0].length === 2 && paddings[1].length === 2, ()=>"Invalid number of paddings. Must be length of 2 each.");
|
|
return (0, _pad.pad)(x, paddings, constantValue);
|
|
}
|
|
const pad2d = /* @__PURE__ */ (0, _operation.op)({
|
|
pad2d_
|
|
});
|
|
|
|
},{"../util":"ctavo","./operation":"ip64W","./pad":"89mWw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6eqEc":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pad3d", ()=>pad3d);
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _pad = require("./pad");
|
|
/**
|
|
* Pads a `tf.Tensor3D` with a given value and paddings. See `pad` for details.
|
|
*/ function pad3d_(x, paddings, constantValue = 0) {
|
|
(0, _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 (0, _pad.pad)(x, paddings, constantValue);
|
|
}
|
|
const pad3d = /* @__PURE__ */ (0, _operation.op)({
|
|
pad3d_
|
|
});
|
|
|
|
},{"../util":"ctavo","./operation":"ip64W","./pad":"89mWw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dP5zO":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pad4d", ()=>pad4d);
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _pad = require("./pad");
|
|
/**
|
|
* Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details.
|
|
*/ function pad4d_(x, paddings, constantValue = 0) {
|
|
(0, _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 (0, _pad.pad)(x, paddings, constantValue);
|
|
}
|
|
const pad4d = /* @__PURE__ */ (0, _operation.op)({
|
|
pad4d_
|
|
});
|
|
|
|
},{"../util":"ctavo","./operation":"ip64W","./pad":"89mWw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"sCTfp":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pool", ()=>pool);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _avgPool = require("./avg_pool");
|
|
var _batchToSpaceNd = require("./batch_to_space_nd");
|
|
var _convUtil = require("./conv_util");
|
|
var _maxPool = require("./max_pool");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
var _spaceToBatchNd = require("./space_to_batch_nd");
|
|
/**
|
|
* 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`.
|
|
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Convolution'}
|
|
*/ function pool_(input, windowShape, poolingType, pad, dilations, strides, dimRoundingMode) {
|
|
if (dilations == null) dilations = [
|
|
1,
|
|
1
|
|
];
|
|
if (strides == null) strides = 1;
|
|
if (pad === 0) pad = "valid";
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(input, "x", "maxPool");
|
|
let x4D = $x;
|
|
let reshapedTo4D = false;
|
|
if ($x.rank === 3) {
|
|
reshapedTo4D = true;
|
|
x4D = (0, _reshape.reshape)($x, [
|
|
1,
|
|
$x.shape[0],
|
|
$x.shape[1],
|
|
$x.shape[2]
|
|
]);
|
|
}
|
|
_util.assert(_convUtil.eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in pool: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
const convInfo = _convUtil.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 : (0, _spaceToBatchNd.spaceToBatchND)(x4D, dilation, adjustedPadding);
|
|
const forwardOp = poolingType === "avg" ? ()=>(0, _avgPool.avgPool)(convertedX, windowShape, strides, convertedPad, dimRoundingMode) : ()=>(0, _maxPool.maxPool)(convertedX, windowShape, strides, convertedPad, dimRoundingMode);
|
|
const y = forwardOp();
|
|
const res = isDilationOne ? y : (0, _batchToSpaceNd.batchToSpaceND)(y, dilation, adjustedCrops);
|
|
if (reshapedTo4D) return (0, _reshape.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 = /* @__PURE__ */ (0, _operation.op)({
|
|
pool_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./avg_pool":"d8nrP","./batch_to_space_nd":"5A2j5","./conv_util":"bf4MH","./max_pool":"hx37d","./operation":"ip64W","./reshape":"ew3wZ","./space_to_batch_nd":"dDwiy","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dDwiy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "spaceToBatchND", ()=>spaceToBatchND);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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 inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
blockShape,
|
|
paddings
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.SpaceToBatchND), inputs, attrs);
|
|
}
|
|
const spaceToBatchND = /* @__PURE__ */ (0, _operation.op)({
|
|
spaceToBatchND_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"azJEF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "prelu", ()=>prelu);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "prelu");
|
|
const $alpha = (0, _tensorUtilEnv.convertToTensor)(alpha, "alpha", "prelu");
|
|
const inputs = {
|
|
x: $x,
|
|
alpha: $alpha
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Prelu), inputs);
|
|
}
|
|
const prelu = /* @__PURE__ */ (0, _operation.op)({
|
|
prelu_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hawIk":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "prod", ()=>prod);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _cast = require("./cast");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "prod");
|
|
if ($x.dtype === "bool") // bool is not an allowed type for the underlying kernel.
|
|
$x = (0, _cast.cast)($x, "int32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis,
|
|
keepDims
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Prod), inputs, attrs);
|
|
}
|
|
const prod = /* @__PURE__ */ (0, _operation.op)({
|
|
prod_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./cast":"b4VDA","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a5cAV":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedGather", ()=>raggedGather);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
function raggedGather_(paramsNestedSplits, paramsDenseValues, indices, outputRaggedRank) {
|
|
const $paramsNestedSplits = paramsNestedSplits.map((t, i)=>(0, _tensorUtilEnv.convertToTensor)(t, `tensors${i}`, "raggedGather", "int32"));
|
|
const $paramsDenseValues = (0, _tensorUtilEnv.convertToTensor)(paramsDenseValues, "paramsDenseValues", "raggedGather");
|
|
const $indices = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "raggedGather", "int32");
|
|
const inputs = {
|
|
paramsNestedSplits: $paramsNestedSplits,
|
|
paramsDenseValues: $paramsDenseValues,
|
|
indices: $indices
|
|
};
|
|
const attrs = {
|
|
outputRaggedRank
|
|
};
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.RaggedGather), inputs, attrs);
|
|
return {
|
|
outputNestedSplits: result.slice(0, result.length - 1),
|
|
outputDenseValues: result[result.length - 1]
|
|
};
|
|
}
|
|
const raggedGather = /* @__PURE__ */ (0, _operation.op)({
|
|
raggedGather_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9Z2C7":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedRange", ()=>raggedRange);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Returns a RaggedTensor result composed from rtDenseValues and rtNestedSplits,
|
|
* such that result[i] = [starts[i], starts[i] + deltas[i], ..., limits[i]]).
|
|
*
|
|
* @param starts: A Tensor. Must be one of the following types:
|
|
* 'float32', 'int32'. The starts of each range.
|
|
* @param limits: A Tensor. Must have the same type as starts. The limits of
|
|
* each range.
|
|
* @param deltas: A Tensor. Must have the same type as starts. The deltas of
|
|
* each range.
|
|
* @return A map with the following properties:
|
|
* - rtNestedSplits: A Tensor of type 'int32'.
|
|
* - rtDenseValues: A Tensor. Has the same type as starts.
|
|
*/ function raggedRange_(starts, limits, deltas) {
|
|
const $starts = (0, _tensorUtilEnv.convertToTensor)(starts, "starts", "raggedRange");
|
|
const $limits = (0, _tensorUtilEnv.convertToTensor)(limits, "limits", "raggedRange", $starts.dtype);
|
|
const $deltas = (0, _tensorUtilEnv.convertToTensor)(deltas, "deltas", "raggedRange", $starts.dtype);
|
|
const inputs = {
|
|
starts: $starts,
|
|
limits: $limits,
|
|
deltas: $deltas
|
|
};
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.RaggedRange), inputs);
|
|
return {
|
|
rtNestedSplits: result[0],
|
|
rtDenseValues: result[1]
|
|
};
|
|
}
|
|
const raggedRange = /* @__PURE__ */ (0, _operation.op)({
|
|
raggedRange_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"93163":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedTensorToTensor", ()=>raggedTensorToTensor);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Create a dense tensor from a ragged tensor, possibly altering its shape.
|
|
*
|
|
* The raggedTensorToTensor op creates a dense tensor from am array of row
|
|
* partition tensors, a value vector, and default values. If the shape is
|
|
* unspecified, the minimal shape required to contain all the elements in the
|
|
* ragged tensor (the natural shape) will be used. If some dimensions are left
|
|
* unspecified, then the size of the natural shape is used in that dimension.
|
|
*
|
|
* The defaultValue will be broadcast to the output shape. After that, the
|
|
* values from the ragged tensor overwrite the default values. Note that the
|
|
* defaultValue must have less dimensions than the value.
|
|
*
|
|
* The row partition tensors are in the order of the dimensions. At present, the
|
|
* types can be: "ROW_SPLITS": the row_splits tensor from the ragged tensor.
|
|
* "VALUE_ROWIDS": the value_rowids tensor from the ragged tensor.
|
|
* "FIRST_DIM_SIZE": if value_rowids is used for the first dimension, then it
|
|
* is preceded by "FIRST_DIM_SIZE".
|
|
* ```
|
|
* @param shape: A Tensor. Must be one of the following types: 'int32'. The
|
|
* desired shape of the output tensor. If left unspecified (empty), the
|
|
* minimal shape required to contain all the elements in the ragged tensor
|
|
* (the natural shape) will be used. If some dimensions are left
|
|
* unspecified, then the size of the natural shape is used in that
|
|
* dimension.
|
|
*
|
|
* Note that dense dimensions cannot be modified by the shape argument.
|
|
* Trying to change the size of a dense dimension will cause the op to fail.
|
|
* Examples: natural shape: [4, 5, 6] shape: -1 output shape: [4, 5, 6]
|
|
*
|
|
* natural shape: [4, 5, 6] shape: [3, -1, 2] output shape: [3, 5, 2]
|
|
*
|
|
* natural shape: [4, 5, 6] shape: [3, 7, 2] output shape: [3, 7, 2]
|
|
* @param values: A Tensor. A 1D tensor representing the values of the ragged
|
|
* tensor.
|
|
* @param defaultValue: A Tensor. Must have the same type as values. The
|
|
* defaultValue when the shape is larger than the ragged tensor. The
|
|
* defaultValue is broadcast until it is the shape of the output tensor,
|
|
* and then overwritten by values in the ragged tensor. The default value
|
|
* must be compatible with this broadcast operation, and must have fewer
|
|
* dimensions than the value tensor.
|
|
* @param rowPartitionTensors: A list of at least 1 Tensor objects with the same
|
|
* type in: 'int32'.
|
|
* @param rowPartitionTypes: A list of strings. The types of the row partition
|
|
* tensors. At present, these can be:
|
|
* "ROW_SPLITS": the row_splits tensor from the ragged tensor.
|
|
* "VALUE_ROWIDS": the value_rowids tensor from the ragged tensor.
|
|
* "FIRST_DIM_SIZE": if value_rowids is used for the first dimension, then
|
|
* it is preceeded by "FIRST_DIM_SIZE". The tensors are in the order of
|
|
* the dimensions.
|
|
* @return A Tensor. Has the same type as values.
|
|
* @doc {heading: 'Operations', subheading: 'Ragged'}
|
|
*/ function raggedTensorToTensor_(shape, values, defaultValue, rowPartitionTensors, rowPartitionTypes) {
|
|
const $shape = (0, _tensorUtilEnv.convertToTensor)(shape, "shape", "raggedTensorToTensor", "int32");
|
|
const $values = (0, _tensorUtilEnv.convertToTensor)(values, "values", "raggedTensorToTensor");
|
|
const $defaultValue = (0, _tensorUtilEnv.convertToTensor)(defaultValue, "defaultValue", "raggedTensorToTensor", $values.dtype);
|
|
const $rowPartitionTensors = rowPartitionTensors.map((t, i)=>(0, _tensorUtilEnv.convertToTensor)(t, `tensors${i}`, "raggedTensorToTensor", "int32"));
|
|
const inputs = {
|
|
shape: $shape,
|
|
values: $values,
|
|
defaultValue: $defaultValue,
|
|
rowPartitionTensors: $rowPartitionTensors
|
|
};
|
|
const attrs = {
|
|
rowPartitionTypes
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.RaggedTensorToTensor), inputs, attrs);
|
|
}
|
|
const raggedTensorToTensor = /* @__PURE__ */ (0, _operation.op)({
|
|
raggedTensorToTensor_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eyCJc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rand", ()=>rand);
|
|
var _engine = require("../engine");
|
|
var _util = require("../util");
|
|
var _utilBase = require("../util_base");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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'.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Random'}
|
|
*/ function rand_(shape, randFunction, dtype) {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(shape);
|
|
const size = (0, _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 (0, _engine.ENGINE).makeTensor(values, shape, dtype);
|
|
}
|
|
const rand = /* @__PURE__ */ (0, _operation.op)({
|
|
rand_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../util":"ctavo","../util_base":"4Vo4a","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4v8VB":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "randomGamma", ()=>randomGamma);
|
|
var _utilBase = require("../util_base");
|
|
var _buffer = require("./buffer");
|
|
var _operation = require("./operation");
|
|
var _randUtil = require("./rand_util");
|
|
/**
|
|
* 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) {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(shape);
|
|
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 (0, _randUtil.RandGamma)(alpha, beta, dtype, seed);
|
|
const res = (0, _buffer.buffer)(shape, dtype);
|
|
for(let i = 0; i < res.values.length; i++)res.values[i] = rgamma.nextValue();
|
|
return res.toTensor();
|
|
}
|
|
const randomGamma = /* @__PURE__ */ (0, _operation.op)({
|
|
randomGamma_
|
|
});
|
|
|
|
},{"../util_base":"4Vo4a","./buffer":"dYyY7","./operation":"ip64W","./rand_util":"3z7XO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3z7XO":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
// https://en.wikipedia.org/wiki/Marsaglia_polar_method
|
|
parcelHelpers.export(exports, "MPRandGauss", ()=>MPRandGauss);
|
|
// Marsaglia, George, and Wai Wan Tsang. 2000. "A Simple Method for Generating
|
|
// Gamma Variables."
|
|
parcelHelpers.export(exports, "RandGamma", ()=>RandGamma);
|
|
parcelHelpers.export(exports, "UniformRandom", ()=>UniformRandom);
|
|
parcelHelpers.export(exports, "jarqueBeraNormalityTest", ()=>jarqueBeraNormalityTest);
|
|
parcelHelpers.export(exports, "expectArrayInMeanStdRange", ()=>expectArrayInMeanStdRange);
|
|
var _seedrandom = require("seedrandom");
|
|
var _testUtil = require("../test_util");
|
|
class 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 * 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;
|
|
}
|
|
}
|
|
class 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 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 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 = (0, _testUtil.testEpsilon)();
|
|
const actualMean = mean(actual);
|
|
(0, _testUtil.expectNumbersClose)(actualMean, expectedMean, epsilon);
|
|
(0, _testUtil.expectNumbersClose)(standardDeviation(actual, actualMean), expectedStdDev, epsilon);
|
|
}
|
|
function 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 = 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 = 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, 1.5);
|
|
}
|
|
|
|
},{"seedrandom":"9SiBG","../test_util":"3IEFi","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9SiBG":[function(require,module,exports) {
|
|
// 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 = require("12650d0e2f5e5e92");
|
|
// xor128, a pure xor-shift generator by George Marsaglia.
|
|
// Period: 2^128-1.
|
|
// Reported to fail: MatrixRank and LinearComp.
|
|
var xor128 = require("2e9ff46cdee4aab4");
|
|
// 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 = require("a04af32374227880");
|
|
// 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 = require("65d05f6db8da652c");
|
|
// 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 = require("1e972c6b140abbe7");
|
|
// 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 = require("286eb9753e804cda");
|
|
// The original ARC4-based prng included in this library.
|
|
// Period: ~2^1600
|
|
var sr = require("a0d0bb1ebcf7d3f9");
|
|
sr.alea = alea;
|
|
sr.xor128 = xor128;
|
|
sr.xorwow = xorwow;
|
|
sr.xorshift7 = xorshift7;
|
|
sr.xor4096 = xor4096;
|
|
sr.tychei = tychei;
|
|
module.exports = sr;
|
|
|
|
},{"12650d0e2f5e5e92":"cjnHc","2e9ff46cdee4aab4":"hD4Ju","a04af32374227880":"4UiN4","65d05f6db8da652c":"bOULY","1e972c6b140abbe7":"aTjJH","286eb9753e804cda":"7crAu","a0d0bb1ebcf7d3f9":"jDzc2"}],"cjnHc":[function(require,module,exports) {
|
|
// 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, module1, define1) {
|
|
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 = String(data);
|
|
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 (module1 && module1.exports) module1.exports = impl;
|
|
else if (define1 && define1.amd) define1(function() {
|
|
return impl;
|
|
});
|
|
else this.alea = impl;
|
|
})(this, module, typeof define == "function" && define // present with an AMD loader
|
|
);
|
|
|
|
},{}],"hD4Ju":[function(require,module,exports) {
|
|
// A Javascript implementaion of the "xor128" prng algorithm by
|
|
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
|
|
(function(global, module1, define1) {
|
|
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) / 2097152;
|
|
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 (module1 && module1.exports) module1.exports = impl;
|
|
else if (define1 && define1.amd) define1(function() {
|
|
return impl;
|
|
});
|
|
else this.xor128 = impl;
|
|
})(this, module, typeof define == "function" && define // present with an AMD loader
|
|
);
|
|
|
|
},{}],"4UiN4":[function(require,module,exports) {
|
|
// A Javascript implementaion of the "xorwow" prng algorithm by
|
|
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
|
|
(function(global, module1, define1) {
|
|
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) / 2097152;
|
|
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 (module1 && module1.exports) module1.exports = impl;
|
|
else if (define1 && define1.amd) define1(function() {
|
|
return impl;
|
|
});
|
|
else this.xorwow = impl;
|
|
})(this, module, typeof define == "function" && define // present with an AMD loader
|
|
);
|
|
|
|
},{}],"bOULY":[function(require,module,exports) {
|
|
// 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, module1, define1) {
|
|
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) / 2097152;
|
|
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 (module1 && module1.exports) module1.exports = impl;
|
|
else if (define1 && define1.amd) define1(function() {
|
|
return impl;
|
|
});
|
|
else this.xorshift7 = impl;
|
|
})(this, module, typeof define == "function" && define // present with an AMD loader
|
|
);
|
|
|
|
},{}],"aTjJH":[function(require,module,exports) {
|
|
// 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, module1, define1) {
|
|
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 = 512; 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) / 2097152;
|
|
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 (module1 && module1.exports) module1.exports = impl;
|
|
else if (define1 && define1.amd) define1(function() {
|
|
return impl;
|
|
});
|
|
else this.xor4096 = impl;
|
|
})(this, module, typeof define == "function" && define // present with an AMD loader
|
|
);
|
|
|
|
},{}],"7crAu":[function(require,module,exports) {
|
|
// 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, module1, define1) {
|
|
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 = -1640531527;
|
|
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) / 2097152;
|
|
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 (module1 && module1.exports) module1.exports = impl;
|
|
else if (define1 && define1.amd) define1(function() {
|
|
return impl;
|
|
});
|
|
else this.tychei = impl;
|
|
})(this, module, typeof define == "function" && define // present with an AMD loader
|
|
);
|
|
|
|
},{}],"jDzc2":[function(require,module,exports) {
|
|
/*
|
|
Copyright 2019 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(global, pool, math) {
|
|
//
|
|
// The following constants are related to IEEE 754 limits.
|
|
//
|
|
var width = 256, chunks = 6, digits = 52, rngname = "random", 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), d = startdenom, x = 0; // and no 'extra last byte'.
|
|
while(n < significance){
|
|
n = (n + x) * width; // shifting numerator and
|
|
d *= width; // denominator and generating a
|
|
x = arc4.g(1); // new least-significant-byte.
|
|
}
|
|
while(n >= overflow){
|
|
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;
|
|
} else return prng;
|
|
})(prng, shortseed, "global" in options ? options.global : this == math, options.state);
|
|
}
|
|
//
|
|
// 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 (0, module.exports) {
|
|
module.exports = seedrandom;
|
|
// When in node.js, try using crypto package for autoseeding.
|
|
try {
|
|
nodecrypto = require("55ffaba5e09143c0");
|
|
} catch (ex) {}
|
|
} else if (typeof define == "function" && define.amd) define(function() {
|
|
return seedrandom;
|
|
});
|
|
else // When included as a plain script, set up Math.seedrandom global.
|
|
math["seed" + rngname] = seedrandom;
|
|
// End anonymous scope, and pass initial values.
|
|
})(// global: `self` in browsers (including strict mode and web workers),
|
|
// otherwise `this` in Node and other environments
|
|
typeof self !== "undefined" ? self : this, [], Math // math: package containing random, pow, and seedrandom
|
|
);
|
|
|
|
},{"55ffaba5e09143c0":"1kJBy"}],"3IEFi":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "TEST_EPSILON_FLOAT16", ()=>TEST_EPSILON_FLOAT16);
|
|
parcelHelpers.export(exports, "expectArraysClose", ()=>expectArraysClose);
|
|
parcelHelpers.export(exports, "testEpsilon", ()=>testEpsilon);
|
|
parcelHelpers.export(exports, "expectPromiseToFail", ()=>expectPromiseToFail);
|
|
parcelHelpers.export(exports, "expectArraysEqual", ()=>expectArraysEqual);
|
|
parcelHelpers.export(exports, "expectNumbersClose", ()=>expectNumbersClose);
|
|
parcelHelpers.export(exports, "expectValuesInRange", ()=>expectValuesInRange);
|
|
parcelHelpers.export(exports, "expectArrayBuffersEqual", ()=>expectArrayBuffersEqual);
|
|
/** Encodes strings into utf-8 bytes. */ parcelHelpers.export(exports, "encodeStrings", ()=>encodeStrings);
|
|
/** Creates an HTMLVideoElement with autoplay-friendly default settings. */ parcelHelpers.export(exports, "createVideoElement", ()=>createVideoElement);
|
|
parcelHelpers.export(exports, "play", ()=>play);
|
|
var _engine = require("./engine");
|
|
var _tensorUtilEnv = require("./tensor_util_env");
|
|
var _util = require("./util");
|
|
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 (0, _engine.ENGINE).backend.floatPrecision() === 32 ? TEST_EPSILON_FLOAT32 : TEST_EPSILON_FLOAT16;
|
|
}
|
|
function expectArraysPredicate(actual, expected, predicate) {
|
|
let checkClassType = true;
|
|
if ((0, _util.isTypedArray)(actual) || (0, _util.isTypedArray)(expected)) checkClassType = false;
|
|
if ((0, _util.isTypedArray)(actual) && (0, _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 = (0, _tensorUtilEnv.inferShape)(actual);
|
|
const expectedShape = (0, _tensorUtilEnv.inferShape)(expected);
|
|
if (!(0, _util.arraysEqual)(actualShape, expectedShape)) throw new Error(`Arrays have different shapes. ` + `Actual: [${actualShape}]. Expected: [${expectedShape}]`);
|
|
}
|
|
const actualFlat = (0, _util.isTypedArray)(actual) ? actual : (0, _util.flatten)(actual);
|
|
const expectedFlat = (0, _util.isTypedArray)(expected) ? expected : (0, _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}.`);
|
|
}
|
|
if (typeof expect !== "undefined") expect().nothing();
|
|
}
|
|
function expectPromiseToFail(fn, done) {
|
|
fn().then(()=>done.fail(), ()=>done());
|
|
if (typeof expect !== "undefined") expect().nothing();
|
|
}
|
|
function expectArraysEqual(actual, expected) {
|
|
const exp = typeof expected === "string" || typeof expected === "number" || typeof expected === "boolean" ? [
|
|
expected
|
|
] : expected;
|
|
if ((0, _util.isString)(actual) || (0, _util.isString)(actual[0]) || (0, _util.isString)(expected) || (0, _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}`);
|
|
if (typeof expect !== "undefined") expect().nothing();
|
|
}
|
|
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 does not like comparing ArrayBuffers directly. Wrapping in
|
|
// a Float32Array solves this issue.
|
|
const actualArray = new Float32Array(actual);
|
|
const expectedArray = new Float32Array(expected);
|
|
if (actualArray.length !== expectedArray.length) throw new Error("Expected ArrayBuffer to be of length " + `${expectedArray.length}, but it was ${actualArray.length}`);
|
|
for(let i = 0; i < expectedArray.length; i++){
|
|
if (actualArray[i] !== expectedArray[i]) throw new Error(`Expected ArrayBuffer value at ${i} to be ` + `${expectedArray[i]} but got ${actualArray[i]} instead`);
|
|
}
|
|
}
|
|
function encodeStrings(a) {
|
|
for(let i = 0; i < a.length; i++){
|
|
const val = a[i];
|
|
if (Array.isArray(val)) encodeStrings(val);
|
|
else a[i] = (0, _util.encodeString)(val);
|
|
}
|
|
return a;
|
|
}
|
|
function createVideoElement(source) {
|
|
const video = document.createElement("video");
|
|
if ("playsInline" in video) // tslint:disable-next-line:no-any
|
|
video.playsInline = true;
|
|
video.muted = true;
|
|
video.loop = true;
|
|
video.style.position = "fixed";
|
|
video.style.left = "0px";
|
|
video.style.top = "0px";
|
|
video.preload = "auto";
|
|
video.appendChild(source);
|
|
return new Promise((resolve)=>{
|
|
video.addEventListener("loadeddata", (_)=>resolve(video));
|
|
video.load();
|
|
});
|
|
}
|
|
async function play(video) {
|
|
await video.play();
|
|
if ("requestVideoFrameCallback" in video) await new Promise((resolve)=>{
|
|
// tslint:disable-next-line:no-any
|
|
video.requestVideoFrameCallback(resolve);
|
|
});
|
|
}
|
|
|
|
},{"./engine":"1g2qo","./tensor_util_env":"6vfHI","./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"72nVa":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "randomNormal", ()=>randomNormal);
|
|
var _utilBase = require("../util_base");
|
|
var _buffer = require("./buffer");
|
|
var _operation = require("./operation");
|
|
var _randUtil = require("./rand_util");
|
|
/**
|
|
* 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) {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(shape);
|
|
if (dtype != null && dtype === "bool") throw new Error(`Unsupported data type ${dtype}`);
|
|
const randGauss = new (0, _randUtil.MPRandGauss)(mean, stdDev, dtype, false, seed);
|
|
const res = (0, _buffer.buffer)(shape, dtype);
|
|
for(let i = 0; i < res.values.length; i++)res.values[i] = randGauss.nextValue();
|
|
return res.toTensor();
|
|
}
|
|
const randomNormal = /* @__PURE__ */ (0, _operation.op)({
|
|
randomNormal_
|
|
});
|
|
|
|
},{"../util_base":"4Vo4a","./buffer":"dYyY7","./operation":"ip64W","./rand_util":"3z7XO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eOkY1":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "randomStandardNormal", ()=>randomStandardNormal);
|
|
var _operation = require("./operation");
|
|
var _randomNormal = require("./random_normal");
|
|
/**
|
|
* Creates a `tf.Tensor` with values sampled from a normal distribution.
|
|
*
|
|
* The generated values will have mean 0 and standard deviation 1.
|
|
*
|
|
* ```js
|
|
* tf.randomStandardNormal([2, 2]).print();
|
|
* ```
|
|
*
|
|
* @param shape An array of integers defining the output tensor shape.
|
|
* @param dtype The data type of the output.
|
|
* @param seed The seed for the random number generator.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Random'}
|
|
*/ function randomStandardNormal_(shape, dtype, seed) {
|
|
if (dtype != null && dtype === "bool") throw new Error(`Unsupported data type ${dtype}`);
|
|
return (0, _randomNormal.randomNormal)(shape, 0, 1, dtype, seed);
|
|
}
|
|
const randomStandardNormal = /* @__PURE__ */ (0, _operation.op)({
|
|
randomStandardNormal_
|
|
});
|
|
|
|
},{"./operation":"ip64W","./random_normal":"72nVa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8LDYI":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "randomUniform", ()=>randomUniform);
|
|
var _utilBase = require("../util_base");
|
|
var _buffer = require("./buffer");
|
|
var _operation = require("./operation");
|
|
var _randUtil = require("./rand_util");
|
|
/**
|
|
* 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'.
|
|
* @param seed An optional int. Defaults to 0. If seed is set to be non-zero,
|
|
* the random number generator is seeded by the given seed. Otherwise, it is
|
|
* seeded by a random seed.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Random'}
|
|
*/ function randomUniform_(shape, minval = 0, maxval = 1, dtype = "float32", seed) {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(shape);
|
|
const res = (0, _buffer.buffer)(shape, dtype);
|
|
const random = new (0, _randUtil.UniformRandom)(minval, maxval, null, seed);
|
|
for(let i = 0; i < res.values.length; i++)res.values[i] = random.nextValue();
|
|
return res.toTensor();
|
|
}
|
|
const randomUniform = /* @__PURE__ */ (0, _operation.op)({
|
|
randomUniform_
|
|
});
|
|
|
|
},{"../util_base":"4Vo4a","./buffer":"dYyY7","./operation":"ip64W","./rand_util":"3z7XO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a0IEB":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "randomUniformInt", ()=>randomUniformInt);
|
|
var _operation = require("./operation");
|
|
var _randomUniform = require("./random_uniform");
|
|
/**
|
|
* Creates a `tf.Tensor` with integers sampled from a uniform distribution.
|
|
*
|
|
* The generated values are uniform integers in the range [minval, maxval). The
|
|
* lower bound minval is included in the range, while the upper bound maxval is
|
|
* excluded.
|
|
*
|
|
* ```js
|
|
* tf.randomUniformInt([2, 2], 0, 10).print();
|
|
* ```
|
|
*
|
|
* @param shape An array of integers defining the output tensor shape.
|
|
* @param minval Inclusive lower bound on the generated integers.
|
|
* @param maxval Exclusive upper bound on the generated integers.
|
|
* @param seed An optional int. Defaults to 0. If seed is set to be non-zero,
|
|
* the random number generator is seeded by the given seed. Otherwise, it is
|
|
* seeded by a random seed.
|
|
*
|
|
* @doc {heading: 'Tensors', subheading: 'Random'}
|
|
*/ function randomUniformInt_(shape, minval, maxval, seed) {
|
|
// TODO(mattsoulanille): Handle optional seed2 input.
|
|
return (0, _randomUniform.randomUniform)(shape, minval, maxval, "int32", seed);
|
|
}
|
|
const randomUniformInt = /* @__PURE__ */ (0, _operation.op)({
|
|
randomUniformInt_
|
|
});
|
|
|
|
},{"./operation":"ip64W","./random_uniform":"8LDYI","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3seHd":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Creates a new `tf.Tensor1D` filled with the numbers in the range provided.
|
|
*
|
|
* The tensor is a 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'}
|
|
*/ parcelHelpers.export(exports, "range", ()=>range);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
function range(start, stop, step = 1, dtype = "float32") {
|
|
if (step === 0) throw new Error("Cannot have a step of zero");
|
|
const attrs = {
|
|
start,
|
|
stop,
|
|
step,
|
|
dtype
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Range), {} /* inputs */ , attrs);
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8i3Ch":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "real", ()=>real);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(input, "input", "real");
|
|
const inputs = {
|
|
input: $input
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Real), inputs);
|
|
}
|
|
const real = /* @__PURE__ */ (0, _operation.op)({
|
|
real_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bxIjM":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reciprocal", ()=>reciprocal);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "reciprocal");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Reciprocal), inputs);
|
|
}
|
|
const reciprocal = /* @__PURE__ */ (0, _operation.op)({
|
|
reciprocal_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lcv3E":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "relu", ()=>relu);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "relu");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Relu), inputs);
|
|
}
|
|
const relu = /* @__PURE__ */ (0, _operation.op)({
|
|
relu_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cvYLK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "relu6", ()=>relu6);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "relu6");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Relu6), inputs);
|
|
}
|
|
const relu6 = /* @__PURE__ */ (0, _operation.op)({
|
|
relu6_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9yp4z":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reverse", ()=>reverse);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "reverse");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
dims: axis
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Reverse), inputs, attrs);
|
|
}
|
|
const reverse = /* @__PURE__ */ (0, _operation.op)({
|
|
reverse_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1LPYc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reverse1d", ()=>reverse1d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _reverse = require("./reverse");
|
|
/**
|
|
* Reverses a `tf.Tensor1D`.
|
|
*
|
|
* @param x The input tensor.
|
|
*/ function reverse1d_(x) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "reverse");
|
|
_util.assert($x.rank === 1, ()=>`Error in reverse1D: x must be rank 1 but got rank ${$x.rank}.`);
|
|
return (0, _reverse.reverse)($x, 0);
|
|
}
|
|
const reverse1d = /* @__PURE__ */ (0, _operation.op)({
|
|
reverse1d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./reverse":"9yp4z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7RrO2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reverse2d", ()=>reverse2d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _reverse = require("./reverse");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "reverse");
|
|
_util.assert($x.rank === 2, ()=>`Error in reverse2D: x must be rank 2 but got rank ${$x.rank}.`);
|
|
return (0, _reverse.reverse)($x, axis);
|
|
}
|
|
const reverse2d = /* @__PURE__ */ (0, _operation.op)({
|
|
reverse2d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./reverse":"9yp4z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jdnrR":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reverse3d", ()=>reverse3d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _reverse = require("./reverse");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "reverse");
|
|
_util.assert($x.rank === 3, ()=>`Error in reverse3D: x must be rank 3 but got rank ${$x.rank}.`);
|
|
return (0, _reverse.reverse)($x, axis);
|
|
}
|
|
const reverse3d = /* @__PURE__ */ (0, _operation.op)({
|
|
reverse3d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./reverse":"9yp4z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7dqzq":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reverse4d", ()=>reverse4d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _reverse = require("./reverse");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "reverse");
|
|
_util.assert($x.rank === 4, ()=>`Error in reverse4D: x must be rank 4 but got rank ${$x.rank}.`);
|
|
return (0, _reverse.reverse)($x, axis);
|
|
}
|
|
const reverse4d = /* @__PURE__ */ (0, _operation.op)({
|
|
reverse4d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./reverse":"9yp4z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4aCvQ":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "round", ()=>round);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "round");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Round), inputs);
|
|
}
|
|
const round = /* @__PURE__ */ (0, _operation.op)({
|
|
round_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7D6sy":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rsqrt", ()=>rsqrt);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "rsqrt", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Rsqrt), inputs);
|
|
}
|
|
const rsqrt = /* @__PURE__ */ (0, _operation.op)({
|
|
rsqrt_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kGS0T":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "selu", ()=>selu);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Computes scaled exponential linear element-wise.
|
|
*
|
|
* `x < 0 ? scale * alpha * (exp(x) - 1) : scale * 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "selu");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Selu), inputs);
|
|
}
|
|
const selu = /* @__PURE__ */ (0, _operation.op)({
|
|
selu_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1MPx9":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "separableConv2d", ()=>separableConv2d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _conv2D = require("./conv2d");
|
|
var _depthwiseConv2D = require("./depthwise_conv2d");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "separableConv2d");
|
|
const $depthwiseFilter = (0, _tensorUtilEnv.convertToTensor)(depthwiseFilter, "depthwiseFilter", "separableConv2d");
|
|
const $pointwiseFilter = (0, _tensorUtilEnv.convertToTensor)(pointwiseFilter, "pointwiseFilter", "separableConv2d");
|
|
let x4D = $x;
|
|
let reshapedTo4D = false;
|
|
if ($x.rank === 3) {
|
|
reshapedTo4D = true;
|
|
x4D = (0, _reshape.reshape)($x, [
|
|
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 = (0, _depthwiseConv2D.depthwiseConv2d)(x4D, $depthwiseFilter, strides, pad, dataFormat, dilation);
|
|
const pointwiseStride = 1;
|
|
const res = (0, _conv2D.conv2d)(depthwise, $pointwiseFilter, pointwiseStride, "valid", dataFormat);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const separableConv2d = /* @__PURE__ */ (0, _operation.op)({
|
|
separableConv2d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./conv2d":"lmJyO","./depthwise_conv2d":"cZHpb","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8tR1Z":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "setdiff1dAsync", ()=>setdiff1dAsync);
|
|
var _tensor = require("../tensor");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "setdiff1d");
|
|
const $y = (0, _tensorUtilEnv.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 (0, _tensor.TensorBuffer)([
|
|
outputSize
|
|
], $x.dtype);
|
|
const indices = new (0, _tensor.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()
|
|
];
|
|
}
|
|
const setdiff1dAsync = setdiff1dAsync_;
|
|
|
|
},{"../tensor":"cJNoh","../tensor_util_env":"6vfHI","../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3bcO0":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sign", ()=>sign);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "sign");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Sign), inputs);
|
|
}
|
|
const sign = /* @__PURE__ */ (0, _operation.op)({
|
|
sign_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gSMA7":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sin", ()=>sin);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "sin", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Sin), inputs);
|
|
}
|
|
const sin = /* @__PURE__ */ (0, _operation.op)({
|
|
sin_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5VZJu":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sinh", ()=>sinh);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "sinh");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Sinh), inputs);
|
|
}
|
|
const sinh = /* @__PURE__ */ (0, _operation.op)({
|
|
sinh_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4krOi":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "slice1d", ()=>slice1d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _slice = require("./slice");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "slice1d");
|
|
_util.assert($x.rank === 1, ()=>`slice1d expects a rank-1 tensor, but got a rank-${$x.rank} tensor`);
|
|
return (0, _slice.slice)($x, [
|
|
begin
|
|
], [
|
|
size
|
|
]);
|
|
}
|
|
const slice1d = /* @__PURE__ */ (0, _operation.op)({
|
|
slice1d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./slice":"dr7Gq","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2Dy3M":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "slice2d", ()=>slice2d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _slice = require("./slice");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "slice2d");
|
|
_util.assert($x.rank === 2, ()=>`slice2d expects a rank-2 tensor, but got a rank-${$x.rank} tensor`);
|
|
return (0, _slice.slice)($x, begin, size);
|
|
}
|
|
const slice2d = /* @__PURE__ */ (0, _operation.op)({
|
|
slice2d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./slice":"dr7Gq","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3DCYE":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "slice3d", ()=>slice3d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _slice = require("./slice");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "slice3d");
|
|
_util.assert($x.rank === 3, ()=>`slice3d expects a rank-3 tensor, but got a rank-${$x.rank} tensor`);
|
|
return (0, _slice.slice)($x, begin, size);
|
|
}
|
|
const slice3d = /* @__PURE__ */ (0, _operation.op)({
|
|
slice3d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./slice":"dr7Gq","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bMRWt":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "slice4d", ()=>slice4d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _slice = require("./slice");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "slice4d");
|
|
_util.assert($x.rank === 4, ()=>`slice4d expects a rank-4 tensor, but got a rank-${$x.rank} tensor`);
|
|
return (0, _slice.slice)($x, begin, size);
|
|
}
|
|
const slice4d = /* @__PURE__ */ (0, _operation.op)({
|
|
slice4d_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./slice":"dr7Gq","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5C9bA":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "softmax", ()=>softmax);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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 inputs = {
|
|
logits: $logits
|
|
};
|
|
const attrs = {
|
|
dim
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Softmax), inputs, attrs);
|
|
}
|
|
const softmax = /* @__PURE__ */ (0, _operation.op)({
|
|
softmax_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2vcIN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fft", ()=>fft);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* 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) {
|
|
(0, _util.assert)(input.dtype === "complex64", ()=>`The dtype for tf.spectral.fft() must be complex64 ` + `but got ${input.dtype}.`);
|
|
const inputs = {
|
|
input
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.FFT), inputs);
|
|
}
|
|
const fft = /* @__PURE__ */ (0, _operation.op)({
|
|
fft_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../util":"ctavo","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4lzNl":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ifft", ()=>ifft);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* 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) {
|
|
(0, _util.assert)(input.dtype === "complex64", ()=>`The dtype for tf.spectral.ifft() must be complex64 ` + `but got ${input.dtype}.`);
|
|
const inputs = {
|
|
input
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.IFFT), inputs);
|
|
}
|
|
const ifft = /* @__PURE__ */ (0, _operation.op)({
|
|
ifft_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../util":"ctavo","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hzbzS":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "irfft", ()=>irfft);
|
|
var _complex = require("../complex");
|
|
var _concat = require("../concat");
|
|
var _imag = require("../imag");
|
|
var _mul = require("../mul");
|
|
var _operation = require("../operation");
|
|
var _real = require("../real");
|
|
var _reshape = require("../reshape");
|
|
var _reverse = require("../reverse");
|
|
var _scalar = require("../scalar");
|
|
var _slice = require("../slice");
|
|
var _ifft = require("./ifft");
|
|
/**
|
|
* 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;
|
|
let ret;
|
|
if (innerDimensionSize <= 2) {
|
|
const complexInput = (0, _reshape.reshape)(input, [
|
|
batch,
|
|
innerDimensionSize
|
|
]);
|
|
ret = (0, _ifft.ifft)(complexInput);
|
|
} 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 = (0, _reshape.reshape)((0, _real.real)(input), [
|
|
batch,
|
|
innerDimensionSize
|
|
]);
|
|
const imagInput = (0, _reshape.reshape)((0, _imag.imag)(input), [
|
|
batch,
|
|
innerDimensionSize
|
|
]);
|
|
const realConjugate = (0, _reverse.reverse)((0, _slice.slice)(realInput, [
|
|
0,
|
|
1
|
|
], [
|
|
batch,
|
|
innerDimensionSize - 2
|
|
]), 1);
|
|
const imagConjugate = (0, _mul.mul)((0, _reverse.reverse)((0, _slice.slice)(imagInput, [
|
|
0,
|
|
1
|
|
], [
|
|
batch,
|
|
innerDimensionSize - 2
|
|
]), 1), (0, _scalar.scalar)(-1));
|
|
const r = (0, _concat.concat)([
|
|
realInput,
|
|
realConjugate
|
|
], 1);
|
|
const i = (0, _concat.concat)([
|
|
imagInput,
|
|
imagConjugate
|
|
], 1);
|
|
const complexInput = (0, _reshape.reshape)((0, _complex.complex)(r, i), [
|
|
outputShape[0],
|
|
outputShape[1]
|
|
]);
|
|
ret = (0, _ifft.ifft)(complexInput);
|
|
}
|
|
ret = (0, _real.real)(ret);
|
|
// reshape the result if the input is 3D tensor.
|
|
if (input.rank === 3 && input.shape[0] !== 0) {
|
|
const temp = ret;
|
|
const batch = input.shape[0];
|
|
ret = (0, _reshape.reshape)(ret, [
|
|
batch,
|
|
ret.shape[0] / batch,
|
|
ret.shape[1]
|
|
]);
|
|
temp.dispose();
|
|
}
|
|
return ret;
|
|
}
|
|
const irfft = /* @__PURE__ */ (0, _operation.op)({
|
|
irfft_
|
|
});
|
|
|
|
},{"../complex":"bPDAx","../concat":"1NOyL","../imag":"lDORm","../mul":"fOWrC","../operation":"ip64W","../real":"8i3Ch","../reshape":"ew3wZ","../reverse":"9yp4z","../scalar":"7lhC8","../slice":"dr7Gq","./ifft":"4lzNl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hnd5A":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rfft", ()=>rfft);
|
|
var _util = require("../../util");
|
|
var _complex = require("../complex");
|
|
var _concat = require("../concat");
|
|
var _imag = require("../imag");
|
|
var _operation = require("../operation");
|
|
var _real = require("../real");
|
|
var _reshape = require("../reshape");
|
|
var _slice = require("../slice");
|
|
var _split = require("../split");
|
|
var _zeros = require("../zeros");
|
|
var _zerosLike = require("../zeros_like");
|
|
var _fft = require("./fft");
|
|
/**
|
|
* 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) {
|
|
(0, _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 = (0, _slice.slice)(input, 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 = (0, _concat.concat)([
|
|
input,
|
|
(0, _zeros.zeros)(zerosShape)
|
|
], input.shape.length - 1);
|
|
innerDimensionSize = fftLength;
|
|
} else adjustedInput = input;
|
|
// Complement the input with zero imaginary numbers.
|
|
const zerosInput = (0, _zerosLike.zerosLike)(adjustedInput);
|
|
const complexInput = (0, _reshape.reshape)((0, _complex.complex)(adjustedInput, zerosInput), [
|
|
batch,
|
|
innerDimensionSize
|
|
]);
|
|
const ret = (0, _fft.fft)(complexInput);
|
|
// Exclude complex conjugations. These conjugations are put symmetrically.
|
|
const half = Math.floor(innerDimensionSize / 2) + 1;
|
|
const realValues = (0, _real.real)(ret);
|
|
const imagValues = (0, _imag.imag)(ret);
|
|
const realComplexConjugate = (0, _split.split)(realValues, [
|
|
half,
|
|
innerDimensionSize - half
|
|
], realValues.shape.length - 1);
|
|
const imagComplexConjugate = (0, _split.split)(imagValues, [
|
|
half,
|
|
innerDimensionSize - half
|
|
], imagValues.shape.length - 1);
|
|
const outputShape = adjustedInput.shape.slice();
|
|
outputShape[adjustedInput.shape.length - 1] = half;
|
|
return (0, _reshape.reshape)((0, _complex.complex)(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);
|
|
}
|
|
const rfft = /* @__PURE__ */ (0, _operation.op)({
|
|
rfft_
|
|
});
|
|
|
|
},{"../../util":"ctavo","../complex":"bPDAx","../concat":"1NOyL","../imag":"lDORm","../operation":"ip64W","../real":"8i3Ch","../reshape":"ew3wZ","../slice":"dr7Gq","../split":"l0HF2","../zeros":"fcPHR","../zeros_like":"1Xjct","./fft":"2vcIN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"l0HF2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "split", ()=>split);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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]`.
|
|
* Can contain one -1 indicating that dimension is to be inferred.
|
|
* @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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "split");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attr = {
|
|
numOrSizeSplits,
|
|
axis
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.SplitV), inputs, attr);
|
|
}
|
|
const split = /* @__PURE__ */ (0, _operation.op)({
|
|
split_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iHBgt":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "squaredDifference", ()=>squaredDifference);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(a, "a", "squaredDifference");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "squaredDifference");
|
|
[$a, $b] = (0, _tensorUtil.makeTypesMatch)($a, $b);
|
|
(0, _broadcastUtil.assertAndGetBroadcastShape)($a.shape, $b.shape);
|
|
const inputs = {
|
|
a: $a,
|
|
b: $b
|
|
};
|
|
const attrs = {};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.SquaredDifference), inputs, attrs);
|
|
}
|
|
const squaredDifference = /* @__PURE__ */ (0, _operation.op)({
|
|
squaredDifference_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","./broadcast_util":"eLo4J","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"VbY6Z":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "squeeze", ()=>squeeze);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "squeeze", "string_or_numeric");
|
|
return (0, _reshape.reshape)($x, (0, _util.squeezeShape)($x.shape, axis).newShape);
|
|
}
|
|
const squeeze = /* @__PURE__ */ (0, _operation.op)({
|
|
squeeze_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jeh7M":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stack", ()=>stack);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensorArray)(tensors, "tensors", "stack", "string_or_numeric");
|
|
_util.assert($tensors.length >= 1, ()=>"Pass at least one tensor to tf.stack");
|
|
if ($tensors.length > 0) _util.assert(axis <= $tensors[0].rank, ()=>"Axis must be <= rank of the tensor");
|
|
const inputs = $tensors;
|
|
const attrs = {
|
|
axis
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Pack), inputs, attrs);
|
|
}
|
|
const stack = /* @__PURE__ */ (0, _operation.op)({
|
|
stack_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bBBT4":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "step", ()=>step);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha`
|
|
*
|
|
* ```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. Defaults to 0.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Basic math'}
|
|
*/ function step_(x, alpha = 0.0) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "step");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
alpha
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Step), inputs, attrs);
|
|
}
|
|
const step = /* @__PURE__ */ (0, _operation.op)({
|
|
step_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9Kwrw":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stridedSlice", ()=>stridedSlice);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "stridedSlice", "string_or_numeric");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
begin,
|
|
end,
|
|
strides,
|
|
beginMask,
|
|
endMask,
|
|
ellipsisMask,
|
|
newAxisMask,
|
|
shrinkAxisMask
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.StridedSlice), inputs, attrs);
|
|
}
|
|
const stridedSlice = /* @__PURE__ */ (0, _operation.op)({
|
|
stridedSlice_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c36dQ":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tan", ()=>tan);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "tan", "float32");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Tan), inputs);
|
|
}
|
|
const tan = /* @__PURE__ */ (0, _operation.op)({
|
|
tan_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aEL9e":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "tensor1d", ()=>tensor1d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _tensorOpsUtil = require("./tensor_ops_util");
|
|
function tensor1d(values, dtype) {
|
|
(0, _util.assertNonNull)(values);
|
|
const inferredShape = (0, _tensorUtilEnv.inferShape)(values, dtype);
|
|
if (inferredShape.length !== 1) throw new Error("tensor1d() requires values to be a flat/TypedArray");
|
|
const shape = null;
|
|
return (0, _tensorOpsUtil.makeTensor)(values, shape, inferredShape, dtype);
|
|
}
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./tensor_ops_util":"adYmX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"faX5H":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "tensor2d", ()=>tensor2d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _tensorOpsUtil = require("./tensor_ops_util");
|
|
function tensor2d(values, shape, dtype) {
|
|
(0, _util.assertNonNull)(values);
|
|
if (shape != null && shape.length !== 2) throw new Error("tensor2d() requires shape to have two numbers");
|
|
const inferredShape = (0, _tensorUtilEnv.inferShape)(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 (0, _tensorOpsUtil.makeTensor)(values, shape, inferredShape, dtype);
|
|
}
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./tensor_ops_util":"adYmX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lVDsd":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "tensor3d", ()=>tensor3d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _tensorOpsUtil = require("./tensor_ops_util");
|
|
function tensor3d(values, shape, dtype) {
|
|
(0, _util.assertNonNull)(values);
|
|
if (shape != null && shape.length !== 3) throw new Error("tensor3d() requires shape to have three numbers");
|
|
const inferredShape = (0, _tensorUtilEnv.inferShape)(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 (0, _tensorOpsUtil.makeTensor)(values, shape, inferredShape, dtype);
|
|
}
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./tensor_ops_util":"adYmX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5QFb1":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "tensor4d", ()=>tensor4d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _tensorOpsUtil = require("./tensor_ops_util");
|
|
function tensor4d(values, shape, dtype) {
|
|
(0, _util.assertNonNull)(values);
|
|
if (shape != null && shape.length !== 4) throw new Error("tensor4d() requires shape to have four numbers");
|
|
const inferredShape = (0, _tensorUtilEnv.inferShape)(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 (0, _tensorOpsUtil.makeTensor)(values, shape, inferredShape, dtype);
|
|
}
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./tensor_ops_util":"adYmX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7LoZX":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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]]],[[[5],[6]],[[7],[8]]]]]).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'}
|
|
*/ parcelHelpers.export(exports, "tensor5d", ()=>tensor5d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _tensorOpsUtil = require("./tensor_ops_util");
|
|
function tensor5d(values, shape, dtype) {
|
|
(0, _util.assertNonNull)(values);
|
|
if (shape != null && shape.length !== 5) throw new Error("tensor5d() requires shape to have five numbers");
|
|
const inferredShape = (0, _tensorUtilEnv.inferShape)(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 (0, _tensorOpsUtil.makeTensor)(values, shape, inferredShape, dtype);
|
|
}
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./tensor_ops_util":"adYmX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jFXe2":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "tensor6d", ()=>tensor6d);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _tensorOpsUtil = require("./tensor_ops_util");
|
|
function tensor6d(values, shape, dtype) {
|
|
(0, _util.assertNonNull)(values);
|
|
if (shape != null && shape.length !== 6) throw new Error("tensor6d() requires shape to have six numbers");
|
|
const inferredShape = (0, _tensorUtilEnv.inferShape)(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 (0, _tensorOpsUtil.makeTensor)(values, shape, inferredShape, dtype);
|
|
}
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./tensor_ops_util":"adYmX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1L18R":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tensorScatterUpdate", ()=>tensorScatterUpdate);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
var _scatterNdUtil = require("./scatter_nd_util");
|
|
/**
|
|
* Creates a new tensor by applying sparse updates to individual
|
|
* values or slices to the passed in tensor according to
|
|
* indices. This operator is the similar to scatterNd op, except that the
|
|
* udpates are scattered on an existing tensor (as opposed to a zero-tensor).
|
|
*
|
|
* If indices contains duplicates, then we pick the last update for the index.
|
|
*
|
|
* If an out of bound index is found on CPU, an error is returned.
|
|
*
|
|
* Warning: There are some GPU specific semantics for this operation.
|
|
* - If an out of bound index is found, the index is ignored.
|
|
* - The order in which updates are applied is nondeterministic, so the output
|
|
* will be nondeterministic if indices contains duplicates.
|
|
* ```js
|
|
* const shape = [8];
|
|
* const tensor = tf.ones(shape);
|
|
* const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');
|
|
* const updates = tf.tensor1d([9, 10, 11, 12]);
|
|
*
|
|
* tf.tensorScatterUpdate(tensor, indices, updates).print();
|
|
* //[1, 11, 1, 10, 9, 1, 1, 12]
|
|
* ```
|
|
*
|
|
* @param tensor A Tensor. Tensor to copy/update.
|
|
* @param indices The tensor contains the indices into the output tensor, must
|
|
* have at least 2 axes: (num_updates, index_depth).
|
|
* @param updates The tensor contains the value for the indices.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
|
|
*/ function tensorScatterUpdate_(tensor, indices, updates) {
|
|
const $tensor = (0, _tensorUtilEnv.convertToTensor)(tensor, "tensor", "tensorScatterupdate");
|
|
const $indices = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "tensorScatterupdate", "int32");
|
|
const $updates = (0, _tensorUtilEnv.convertToTensor)(updates, "updates", "tensorScatterupdate");
|
|
_scatterNdUtil.validateInput($updates, $indices, $tensor.shape);
|
|
if ($tensor.dtype !== $updates.dtype) throw new Error(`tensor and updates must have the same dtype, instead they are ${$tensor.dtype} and ${$updates.dtype}.`);
|
|
const inputs = {
|
|
tensor: $tensor,
|
|
indices: $indices,
|
|
updates: $updates
|
|
};
|
|
const attrs = {};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.TensorScatterUpdate), inputs, attrs);
|
|
}
|
|
const tensorScatterUpdate = (0, _operation.op)({
|
|
tensorScatterUpdate_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","./scatter_nd_util":"dDUQ5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dDUQ5":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Check whether updates.shape = indices.shape[:batchDim] +
|
|
* shape[sliceDim:]
|
|
*
|
|
* @param x The input tensor.
|
|
*/ parcelHelpers.export(exports, "validateUpdateShape", ()=>validateUpdateShape);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "validateInput", ()=>validateInput);
|
|
/**
|
|
* 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
|
|
*/ parcelHelpers.export(exports, "calculateShapes", ()=>calculateShapes);
|
|
var _util = require("../util");
|
|
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]})`);
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
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 = (0, _util.sizeFromShape)(indices.shape) / safeSliceDim;
|
|
const strides = [
|
|
...(0, _util.computeStrides)(shape.slice(0, sliceRank)),
|
|
1
|
|
];
|
|
const outputSize = (0, _util.sizeFromShape)(shape);
|
|
return {
|
|
sliceRank,
|
|
numUpdates,
|
|
sliceSize,
|
|
strides,
|
|
outputSize
|
|
};
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jUBl9":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "topk", ()=>topk);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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 < 0) throw new Error(`'k' passed to topk() must be >= 0 but got ${k}`);
|
|
if (k > lastDim) throw new Error(`'k' passed to topk() must be <= the last dimension (${lastDim}) ` + `but got ${k}`);
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
k,
|
|
sorted
|
|
};
|
|
const [values, indices] = (0, _engine.ENGINE).runKernel((0, _kernelNames.TopK), inputs, attrs);
|
|
return {
|
|
values,
|
|
indices
|
|
};
|
|
}
|
|
const topk = /* @__PURE__ */ (0, _operation.op)({
|
|
topk_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jsVmm":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "truncatedNormal", ()=>truncatedNormal);
|
|
var _utilBase = require("../util_base");
|
|
var _buffer = require("./buffer");
|
|
var _operation = require("./operation");
|
|
var _randUtil = require("./rand_util");
|
|
/**
|
|
* 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) {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(shape);
|
|
if (dtype != null && dtype === "bool") throw new Error(`Unsupported data type $ { dtype }`);
|
|
const randGauss = new (0, _randUtil.MPRandGauss)(mean, stdDev, dtype, true, seed);
|
|
const res = (0, _buffer.buffer)(shape, dtype);
|
|
for(let i = 0; i < res.values.length; i++)res.values[i] = randGauss.nextValue();
|
|
return res.toTensor();
|
|
}
|
|
const truncatedNormal = /* @__PURE__ */ (0, _operation.op)({
|
|
truncatedNormal_
|
|
});
|
|
|
|
},{"../util_base":"4Vo4a","./buffer":"dYyY7","./operation":"ip64W","./rand_util":"3z7XO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kc2B3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unique", ()=>unique);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Finds unique elements along an axis of a tensor.
|
|
*
|
|
* It returns a tensor `values` containing all of the unique elements along the
|
|
* `axis` of the given tensor `x` in the same order that they occur along the
|
|
* `axis` in `x`; `x` does not need to be sorted. It also returns a tensor
|
|
* `indices` the same size as the number of the elements in `x` along the `axis`
|
|
* dimension. It contains the index in the unique output `values`.
|
|
*
|
|
* ```js
|
|
* // A 1-D tensor
|
|
* const a = tf.tensor1d([1, 1, 2, 4, 4, 4, 7, 8, 8]);
|
|
* const {values, indices} = tf.unique(a);
|
|
* values.print(); // [1, 2, 4, 7, 8,]
|
|
* indices.print(); // [0, 0, 1, 2, 2, 2, 3, 4, 4]
|
|
* ```
|
|
*
|
|
* ```js
|
|
* // A 2-D tensor with axis=0
|
|
* //
|
|
* // 'a' is: [[1, 0, 0],
|
|
* // [1, 0, 0],
|
|
* // [2, 0, 0]]
|
|
* const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);
|
|
* const {values, indices} = tf.unique(a, 0)
|
|
* values.print(); // [[1, 0, 0],
|
|
* // [2, 0, 0]]
|
|
* indices.print(); // [0, 0, 1]
|
|
* ```
|
|
*
|
|
* ```js
|
|
* // A 2-D tensor with axis=1
|
|
* //
|
|
* // 'a' is: [[1, 0, 0],
|
|
* // [1, 0, 0],
|
|
* // [2, 0, 0]]
|
|
* const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);
|
|
* const {values, indices} = tf.unique(a, 1)
|
|
* values.print(); // [[1, 0],
|
|
* // [1, 0],
|
|
* // [2, 0]]
|
|
* indices.print(); // [0, 1, 1]
|
|
* ```
|
|
* @param x A tensor (int32, string, bool).
|
|
* @param axis The axis of the tensor to find the unique elements.
|
|
* @returns [uniqueElements, indices] (see above for details)
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Evaluation'}
|
|
*/ function unique_(x, axis = 0) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "unique", "string_or_numeric");
|
|
(0, _util.assert)($x.rank > 0, ()=>"The input tensor must be at least 1D");
|
|
const inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
axis
|
|
};
|
|
const [values, indices] = (0, _engine.ENGINE).runKernel((0, _kernelNames.Unique), inputs, attrs);
|
|
return {
|
|
values,
|
|
indices
|
|
};
|
|
}
|
|
const unique = /* @__PURE__ */ (0, _operation.op)({
|
|
unique_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8ZRDN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unsortedSegmentSum", ()=>unsortedSegmentSum);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(x, "x", "unsortedSegmentSum");
|
|
const $segmentIds = (0, _tensorUtilEnv.convertToTensor)(segmentIds, "segmentIds", "unsortedSegmentSum", "int32");
|
|
(0, _util.assert)((0, _util.isInt)(numSegments), ()=>"numSegments must be of dtype int");
|
|
const inputs = {
|
|
x: $x,
|
|
segmentIds: $segmentIds
|
|
};
|
|
const attrs = {
|
|
numSegments
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.UnsortedSegmentSum), inputs, attrs);
|
|
}
|
|
const unsortedSegmentSum = /* @__PURE__ */ (0, _operation.op)({
|
|
unsortedSegmentSum_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"90Kbb":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unstack", ()=>unstack);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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) {
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "unstack", "string_or_numeric");
|
|
_util.assert(axis >= -$x.shape.length && axis < $x.shape.length, ()=>`Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);
|
|
const inputs = {
|
|
value: $x
|
|
};
|
|
const attrs = {
|
|
axis
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Unpack), inputs, attrs);
|
|
}
|
|
const unstack = /* @__PURE__ */ (0, _operation.op)({
|
|
unstack_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"csQSE":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Searches for where a value would go in a sorted sequence.
|
|
*
|
|
* This is not a method for checking containment (like javascript in).
|
|
*
|
|
* The typical use case for this operation is "binning", "bucketing", or
|
|
* "discretizing". The values are assigned to bucket-indices based on the edges
|
|
* listed in 'sortedSequence'. This operation returns the bucket-index for each
|
|
* value.
|
|
*
|
|
* The index returned corresponds to the first edge greater than the value.
|
|
*
|
|
* The axis is not settable for this operation. It always operates on the
|
|
* innermost dimension (axis=-1). The operation will accept any number of outer
|
|
* dimensions.
|
|
*
|
|
* Note: This operation assumes that 'upperBound' is sorted along the
|
|
* innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not
|
|
* sorted no error is raised and the content of the returned tensor is not well
|
|
* defined.
|
|
*
|
|
* ```js
|
|
* const seq = tf.tensor1d([0, 3, 9, 10, 10]);
|
|
* const values = tf.tensor1d([0, 4, 10]);
|
|
* const result = tf.upperBound(seq, values);
|
|
* result.print(); // [1, 2, 5]
|
|
* ```
|
|
* @param sortedSequence: N-D. Sorted sequence.
|
|
* @param values: N-D. Search values.
|
|
* @return An N-D int32 tensor the size of values containing the result of
|
|
* applying upper bound to each value. The result is not a global index to
|
|
* the entire Tensor, but the index in the last dimension.
|
|
* @doc {heading: 'Operations', subheading: 'Evaluation'}
|
|
*/ parcelHelpers.export(exports, "upperBound", ()=>upperBound);
|
|
var _searchSorted = require("./search_sorted");
|
|
function upperBound(sortedSequence, values) {
|
|
return (0, _searchSorted.searchSorted)(sortedSequence, values, "right");
|
|
}
|
|
|
|
},{"./search_sorted":"4gaGh","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c3Bg5":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "variable", ()=>variable);
|
|
var _engine = require("../engine");
|
|
function variable(initialValue, trainable = true, name, dtype) {
|
|
return (0, _engine.ENGINE).makeVariable(initialValue, trainable, name, dtype);
|
|
}
|
|
|
|
},{"../engine":"1g2qo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2KVsP":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "whereAsync", ()=>whereAsync);
|
|
var _whereImpl = require("../backends/where_impl");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(condition, "condition", "whereAsync", "bool");
|
|
const vals = await $condition.data();
|
|
const res = (0, _whereImpl.whereImpl)($condition.shape, vals);
|
|
if (condition !== $condition) $condition.dispose();
|
|
return res;
|
|
}
|
|
const whereAsync = whereAsync_;
|
|
|
|
},{"../backends/where_impl":"lNCmF","../tensor_util_env":"6vfHI","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lNCmF":[function(require,module,exports) {
|
|
/**
|
|
* @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 */ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "whereImpl", ()=>whereImpl);
|
|
var _buffer = require("../ops/buffer");
|
|
function whereImpl(condShape, condVals) {
|
|
const indices = [];
|
|
for(let i = 0; i < condVals.length; i++)if (condVals[i]) indices.push(i);
|
|
const inBuffer = (0, _buffer.buffer)(condShape, "int32");
|
|
const out = (0, _buffer.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();
|
|
}
|
|
|
|
},{"../ops/buffer":"dYyY7","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jnpjK":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "booleanMaskAsync", ()=>booleanMaskAsync);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _gather = require("./gather");
|
|
var _reshape = require("./reshape");
|
|
var _squeeze = require("./squeeze");
|
|
var _whereAsync = require("./where_async");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(tensor, "tensor", "boolMask");
|
|
const $mask = (0, _tensorUtilEnv.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 = (0, _reshape.reshape)($tensor, targetTensorShape);
|
|
const reshapedMask = (0, _reshape.reshape)($mask, [
|
|
-1
|
|
]);
|
|
const positivePositions = await (0, _whereAsync.whereAsync)(reshapedMask);
|
|
const indices = (0, _squeeze.squeeze)(positivePositions, [
|
|
1
|
|
]);
|
|
const res = (0, _gather.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_;
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./gather":"5p5vK","./reshape":"ew3wZ","./squeeze":"VbY6Z","./where_async":"2KVsP","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2bqbS":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "transpose", ()=>transpose);
|
|
var _engine = require("../engine");
|
|
var _globals = require("../globals");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _complex = require("./complex");
|
|
var _imag = require("./imag");
|
|
var _neg = require("./neg");
|
|
var _operation = require("./operation");
|
|
var _real = require("./real");
|
|
/**
|
|
* 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.
|
|
* @param conjugate Will conjugate complex input if true.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Matrices'}
|
|
*/ function transpose_(x, perm, conjugate) {
|
|
const $x = (0, _tensorUtilEnv.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 inputs = {
|
|
x: $x
|
|
};
|
|
const attrs = {
|
|
perm
|
|
};
|
|
if ($x.dtype === "complex64") return (0, _globals.tidy)(()=>{
|
|
let $real = (0, _real.real)($x);
|
|
let $imag = (0, _imag.imag)($x);
|
|
$real = (0, _engine.ENGINE).runKernel((0, _kernelNames.Transpose), {
|
|
x: $real
|
|
}, attrs);
|
|
$imag = (0, _engine.ENGINE).runKernel((0, _kernelNames.Transpose), {
|
|
x: $imag
|
|
}, attrs);
|
|
if (conjugate) $imag = (0, _neg.neg)($imag);
|
|
return (0, _complex.complex)($real, $imag);
|
|
});
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Transpose), inputs, attrs);
|
|
}
|
|
const transpose = /* @__PURE__ */ (0, _operation.op)({
|
|
transpose_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../globals":"eO1Ja","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util":"ctavo","./complex":"bPDAx","./imag":"lDORm","./neg":"3jQfI","./operation":"ip64W","./real":"8i3Ch","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hLPKe":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "movingAverage", ()=>movingAverage);
|
|
var _tensorUtil = require("../tensor_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _add = require("./add");
|
|
var _div = require("./div");
|
|
var _mul = require("./mul");
|
|
var _operation = require("./operation");
|
|
var _pow = require("./pow");
|
|
var _scalar = require("./scalar");
|
|
var _sub = require("./sub");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(v, "v", "movingAverage");
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "movingAverage");
|
|
const $decay = (0, _tensorUtilEnv.convertToTensor)(decay, "decay", "movingAverage");
|
|
(0, _tensorUtil.assertTypesMatch)($v, $x);
|
|
_util.assert(_util.arraysEqual($v.shape, $x.shape), ()=>"Shape mismatch in v and x");
|
|
const one = (0, _scalar.scalar)(1);
|
|
const oneMinusDecay = (0, _sub.sub)(one, $decay);
|
|
let update = (0, _mul.mul)((0, _sub.sub)($x, $v), oneMinusDecay);
|
|
if (zeroDebias) {
|
|
_util.assert(step != null, ()=>"When using zeroDebias: true, step is required.");
|
|
const $step = (0, _tensorUtilEnv.convertToTensor)(step, "step", "movingAverage");
|
|
update = (0, _div.div)(update, (0, _sub.sub)(one, (0, _pow.pow)($decay, $step)));
|
|
}
|
|
return (0, _add.add)($v, update);
|
|
}
|
|
const movingAverage = /* @__PURE__ */ (0, _operation.op)({
|
|
movingAverage_
|
|
});
|
|
|
|
},{"../tensor_util":"8jzJG","../tensor_util_env":"6vfHI","../util":"ctavo","./add":"aynh7","./div":"5ZT1h","./mul":"fOWrC","./operation":"ip64W","./pow":"gezpC","./scalar":"7lhC8","./sub":"jBBQ2","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2xMWX":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "scatterND", ()=>scatterND);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _utilBase = require("../util_base");
|
|
var _operation = require("./operation");
|
|
var _scatterNdUtil = require("./scatter_nd_util");
|
|
/**
|
|
* 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) {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(shape);
|
|
const $indices = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "scatterND", "int32");
|
|
const $updates = (0, _tensorUtilEnv.convertToTensor)(updates, "updates", "scatterND");
|
|
_scatterNdUtil.validateInput($updates, $indices, shape);
|
|
const inputs = {
|
|
indices: $indices,
|
|
updates: $updates
|
|
};
|
|
const attrs = {
|
|
shape
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.ScatterNd), inputs, attrs);
|
|
}
|
|
const scatterND = /* @__PURE__ */ (0, _operation.op)({
|
|
scatterND_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","../util_base":"4Vo4a","./operation":"ip64W","./scatter_nd_util":"dDUQ5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gXN1p":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseToDense", ()=>sparseToDense);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _sparseToDenseUtil = require("../ops/sparse_to_dense_util");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _utilBase = require("../util_base");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* 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) {
|
|
(0, _utilBase.assertNonNegativeIntegerDimensions)(outputShape);
|
|
const $sparseIndices = (0, _tensorUtilEnv.convertToTensor)(sparseIndices, "sparseIndices", "sparseToDense", "int32");
|
|
const $sparseValues = (0, _tensorUtilEnv.convertToTensor)(sparseValues, "sparseValues", "sparseToDense", "string_or_numeric");
|
|
const $defaultValue = (0, _tensorUtilEnv.convertToTensor)(defaultValue, "defaultValue", "sparseToDense", $sparseValues.dtype);
|
|
_sparseToDenseUtil.validateInput($sparseIndices, $sparseValues, outputShape, $defaultValue);
|
|
const inputs = {
|
|
sparseIndices: $sparseIndices,
|
|
sparseValues: $sparseValues,
|
|
defaultValue: $defaultValue
|
|
};
|
|
const attrs = {
|
|
outputShape
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.SparseToDense), inputs, attrs);
|
|
}
|
|
const sparseToDense = /* @__PURE__ */ (0, _operation.op)({
|
|
sparseToDense_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../ops/sparse_to_dense_util":"7Tweu","../tensor_util_env":"6vfHI","../util_base":"4Vo4a","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7Tweu":[function(require,module,exports) {
|
|
/**
|
|
* 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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "validateInput", ()=>validateInput);
|
|
function 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");
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9KIwq":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gatherND", ()=>gatherND);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _operation = require("./operation");
|
|
/**
|
|
* Gather slices from input tensor into a Tensor with shape specified by
|
|
* `indices`.
|
|
*
|
|
* `indices` is a 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 = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "gatherND", "int32");
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "gatherND", "string_or_numeric");
|
|
const inputs = {
|
|
params: $x,
|
|
indices: $indices
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.GatherNd), inputs);
|
|
}
|
|
const gatherND = /* @__PURE__ */ (0, _operation.op)({
|
|
gatherND_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../tensor_util_env":"6vfHI","./operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6nVzD":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "dropout", ()=>dropout);
|
|
var _tensor = require("../tensor");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _add = require("./add");
|
|
var _div = require("./div");
|
|
var _dropoutUtil = require("./dropout_util");
|
|
var _floor = require("./floor");
|
|
var _mul = require("./mul");
|
|
var _operation = require("./operation");
|
|
var _randomUniform = require("./random_uniform");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.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 (0, _tensor.Tensor) ? $x.clone() : $x;
|
|
const $noiseShape = (0, _dropoutUtil.getNoiseShape)($x, noiseShape);
|
|
const keepProb = 1 - rate;
|
|
const multiplier = (0, _div.div)((0, _floor.floor)((0, _add.add)((0, _randomUniform.randomUniform)($noiseShape, 0, 1, "float32", seed), keepProb)), keepProb);
|
|
return (0, _mul.mul)($x, multiplier);
|
|
}
|
|
const dropout = /* @__PURE__ */ (0, _operation.op)({
|
|
dropout_
|
|
});
|
|
|
|
},{"../tensor":"cJNoh","../tensor_util_env":"6vfHI","../util":"ctavo","./add":"aynh7","./div":"5ZT1h","./dropout_util":"a55Hr","./floor":"35qCf","./mul":"fOWrC","./operation":"ip64W","./random_uniform":"8LDYI","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a55Hr":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getNoiseShape", ()=>getNoiseShape);
|
|
var _util = require("../util");
|
|
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;
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1EuF4":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "enclosingPowerOfTwo", ()=>enclosingPowerOfTwo);
|
|
parcelHelpers.export(exports, "cosineWindow", ()=>cosineWindow);
|
|
var _tensor1D = require("./tensor1d");
|
|
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 (0, _tensor1D.tensor1d)(newValues, "float32");
|
|
}
|
|
|
|
},{"./tensor1d":"aEL9e","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9rwSr":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "inTopKAsync", ()=>inTopKAsync);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _tensor = require("./tensor");
|
|
/**
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(predictions, "predictions", "inTopK");
|
|
const $targets = (0, _tensorUtilEnv.convertToTensor)(targets, "targets", "inTopK");
|
|
(0, _util.assert)($predictions.rank > 1, ()=>"inTopK() expects the predictions to be of rank 2 or higher, " + `but got ${$predictions.rank}`);
|
|
(0, _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}`);
|
|
(0, _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];
|
|
(0, _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 = (0, _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 (0, _tensor.tensor)(precision, $targets.shape, "bool");
|
|
}
|
|
const inTopKAsync = inTopKAsync_;
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./tensor":"jdbb1","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jqlvt":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2d", ()=>(0, _conv2D.conv2d));
|
|
parcelHelpers.export(exports, "depthwiseConv2d", ()=>(0, _depthwiseConv2D.depthwiseConv2d));
|
|
parcelHelpers.export(exports, "matMul", ()=>(0, _matMul.matMul));
|
|
var _conv2D = require("./fused/conv2d");
|
|
var _depthwiseConv2D = require("./fused/depthwise_conv2d");
|
|
var _matMul = require("./fused/mat_mul");
|
|
|
|
},{"./fused/conv2d":"i5FXc","./fused/depthwise_conv2d":"cEX74","./fused/mat_mul":"6BB2f","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"i5FXc":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2d", ()=>conv2d);
|
|
var _engine = require("../../engine");
|
|
var _gradients = require("../../gradients");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtil = require("../../tensor_util");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _add = require("../add");
|
|
var _broadcastUtil = require("../broadcast_util");
|
|
var _conv2D = require("../conv2d");
|
|
var _conv2DBackpropFilter = require("../conv2d_backprop_filter");
|
|
var _conv2DBackpropInput = require("../conv2d_backprop_input");
|
|
var _convUtil = require("../conv_util");
|
|
var _fusedUtil = require("../fused_util");
|
|
var _operation = require("../operation");
|
|
var _reshape = require("../reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/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 A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
* @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`.
|
|
* @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`
|
|
* activation.
|
|
*/ function fusedConv2d_({ x, filter, strides, pad, dataFormat = "NHWC", dilations = [
|
|
1,
|
|
1
|
|
], dimRoundingMode, bias, activation = "linear", preluActivationWeights, leakyreluAlpha }) {
|
|
activation = activation || "linear";
|
|
if ((0, _fusedUtil.shouldFuse)((0, _engine.ENGINE).state.gradientDepth, activation) === false) {
|
|
// TODO: Transpose bias and preluActivationWeights properly for NCHW
|
|
// format before computation.
|
|
_util.assert(dataFormat === "NHWC", ()=>`Error in fused conv2d: got dataFormat of ${dataFormat} but ` + `only NHWC is currently supported for the case of gradient depth ` + `is 0 and the activation is not linear.`);
|
|
let result = (0, _conv2D.conv2d)(x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
|
|
if (bias != null) result = (0, _add.add)(result, bias);
|
|
return (0, _fusedUtil.applyActivation)(result, activation, preluActivationWeights, leakyreluAlpha);
|
|
}
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "conv2d", "float32");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "conv2d", "float32");
|
|
let x4D = $x;
|
|
let reshapedTo4D = false;
|
|
if ($x.rank === 3) {
|
|
reshapedTo4D = true;
|
|
x4D = (0, _reshape.reshape)($x, [
|
|
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}.`);
|
|
_convUtil.checkPadOnDimRoundingMode("fused conv2d", pad, dimRoundingMode);
|
|
const inputChannels = dataFormat === "NHWC" ? x4D.shape[3] : x4D.shape[1];
|
|
_util.assert($filter.shape[2] === inputChannels, ()=>`Error in conv2d: depth of input (${inputChannels}) must match ` + `input depth for filter ${$filter.shape[2]}.`);
|
|
_util.assert(_convUtil.eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in conv2D: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
const convInfo = _convUtil.computeConv2DInfo(x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode);
|
|
let $bias;
|
|
if (bias != null) {
|
|
$bias = (0, _tensorUtilEnv.convertToTensor)(bias, "bias", "fused conv2d");
|
|
[$bias] = (0, _tensorUtil.makeTypesMatch)($bias, $x);
|
|
// According to TensorFlow, the bias is supposed be a 1-D tensor or a
|
|
// scalar.
|
|
//
|
|
// 3-D or 4-D bias is not disabled for NHWC format, because they are
|
|
// currently being used in some cases. For examplem in our code base,
|
|
// https://github.com/tensorflow/tfjs/blob/b53bd47e880367ae57493f0ea628abaf08db2d5d/tfjs-core/src/ops/fused/fused_conv2d_test.ts#L1972.
|
|
if (dataFormat === "NHWC") _broadcastUtil.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
|
|
else {
|
|
_util.assert($bias.shape.length <= 1, ()=>`Error in fused conv2d: only supports scalar or 1-D Tensor ` + `bias for NCHW format but got the bias of ` + `rank-${$bias.shape.length}.`);
|
|
_util.assert($bias.shape.length === 0 || $bias.shape[0] === convInfo.outChannels || $bias.shape[0] === 1, ()=>`Error in fused conv2d: bias shape (${$bias.shape}) is not ` + `compatible with the number of output channels ` + `(${convInfo.outChannels})`);
|
|
}
|
|
}
|
|
let $preluActivationWeights;
|
|
if (preluActivationWeights != null) {
|
|
// PReLU's activation weights could be a scalar, a 1-D tensor or a 3-D
|
|
// tensor.
|
|
const alphaShape = preluActivationWeights.shape;
|
|
_util.assert(alphaShape.length <= 1 || alphaShape.length === 3, ()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or ` + `3-D Tensor PReLU activation weights but got a tensor of ` + `rank-${alphaShape.length}.`);
|
|
if (alphaShape.length === 1) // Whether the data format is NCHW or NHWC, the 1-D PReLU activation
|
|
// weights tensor should be aligned with the output channels of conv2d
|
|
// result.
|
|
_util.assert(alphaShape[0] === 1 || alphaShape[0] === convInfo.outChannels, ()=>`Error in fused conv2d: PReLU activation weights ` + `(${alphaShape}) is not compatible with the number of output ` + `channels (${convInfo.outChannels}).`);
|
|
else if (alphaShape.length === 3) // Whether the data format is NCHW or NHWC, the PReLU activation weights
|
|
// tensor should has the compatible shape with the result of conv2d.
|
|
try {
|
|
_broadcastUtil.assertAndGetBroadcastShape(alphaShape, convInfo.outShape);
|
|
} catch (e) {
|
|
const errMsg = `Error in fused conv2d: PReLU activation weights (${alphaShape}) ` + `is not compatible with the output shape of the conv2d ` + `(${convInfo.outShape}).`;
|
|
throw Error(errMsg);
|
|
}
|
|
$preluActivationWeights = (0, _tensorUtilEnv.convertToTensor)(preluActivationWeights, "prelu weights", "fused conv2d");
|
|
}
|
|
const grad = (dy, saved)=>{
|
|
_util.assert(dataFormat === "NHWC", ()=>`Error in gradient of fused conv2D: got dataFormat of ${dataFormat} but only NHWC is currently supported.`);
|
|
const [$filter, x4D, y, $bias] = saved;
|
|
const dyActivation = (0, _fusedUtil.getFusedDyActivation)(dy, y, activation);
|
|
_util.assert(_convUtil.tupleValuesAreOne(dilations), ()=>"Error in gradient of fused conv2D: " + `dilation rates greater than 1 ` + `are not yet supported in gradients. Got dilations '${dilations}'`);
|
|
const xDer = (0, _conv2DBackpropInput.conv2DBackpropInput)(x4D.shape, dyActivation, $filter, strides, pad);
|
|
const filterDer = (0, _conv2DBackpropFilter.conv2DBackpropFilter)(x4D, dyActivation, $filter.shape, strides, pad);
|
|
const der = [
|
|
xDer,
|
|
filterDer
|
|
];
|
|
if ($bias != null) {
|
|
const biasDer = (0, _fusedUtil.getFusedBiasGradient)($bias, dyActivation);
|
|
der.push(biasDer);
|
|
}
|
|
return der;
|
|
};
|
|
const inputs = {
|
|
x: x4D,
|
|
filter: $filter,
|
|
bias: $bias,
|
|
preluActivationWeights: $preluActivationWeights
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dilations,
|
|
dimRoundingMode,
|
|
activation,
|
|
leakyreluAlpha
|
|
};
|
|
// Depending on the the params passed in we will have different number of
|
|
// inputs and thus a a different number of elements in the gradient.
|
|
if (bias == null) {
|
|
const customOp = (0, _gradients.customGrad)((x4D, filter, save)=>{
|
|
let res = // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
(0, _engine.ENGINE).runKernel((0, _kernelNames.FusedConv2D), inputs, attrs);
|
|
save([
|
|
filter,
|
|
x4D,
|
|
res
|
|
]);
|
|
if (reshapedTo4D) // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
res = (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return {
|
|
value: res,
|
|
gradFunc: grad
|
|
};
|
|
});
|
|
return customOp(x4D, $filter);
|
|
} else {
|
|
const customOpWithBias = (0, _gradients.customGrad)((x4D, filter, bias, save)=>{
|
|
let res = (0, _engine.ENGINE).runKernel((0, _kernelNames.FusedConv2D), inputs, attrs);
|
|
save([
|
|
filter,
|
|
x4D,
|
|
res,
|
|
bias
|
|
]);
|
|
if (reshapedTo4D) // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
res = (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return {
|
|
value: res,
|
|
gradFunc: grad
|
|
};
|
|
});
|
|
return customOpWithBias(x4D, $filter, $bias);
|
|
}
|
|
}
|
|
const conv2d = /* @__PURE__ */ (0, _operation.op)({
|
|
fusedConv2d_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../gradients":"dDHpg","../../kernel_names":"hniYO","../../tensor_util":"8jzJG","../../tensor_util_env":"6vfHI","../../util":"ctavo","../add":"aynh7","../broadcast_util":"eLo4J","../conv2d":"lmJyO","../conv2d_backprop_filter":"1UKq8","../conv2d_backprop_input":"l0Ec6","../conv_util":"bf4MH","../fused_util":"8847K","../operation":"ip64W","../reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1UKq8":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2DBackpropFilter", ()=>conv2DBackpropFilter);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _util = require("../util");
|
|
var _convUtil = require("./conv_util");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
/**
|
|
* 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'. If none is
|
|
* provided, it will default to truncate.
|
|
*/ function conv2DBackpropFilter_(x, dy, filterShape, strides, pad, dataFormat = "NHWC", dimRoundingMode) {
|
|
let x4D = x;
|
|
if (x.rank === 3) x4D = (0, _reshape.reshape)(x, [
|
|
1,
|
|
x.shape[0],
|
|
x.shape[1],
|
|
x.shape[2]
|
|
]);
|
|
let dy4D = dy;
|
|
if (dy4D.rank === 3) dy4D = (0, _reshape.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]}).`);
|
|
_convUtil.checkPadOnDimRoundingMode("conv2dDerFilter", pad, dimRoundingMode);
|
|
const inputs = {
|
|
x: x4D,
|
|
dy: dy4D
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dimRoundingMode,
|
|
filterShape
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Conv2DBackpropFilter), inputs, attrs);
|
|
}
|
|
const conv2DBackpropFilter = /* @__PURE__ */ (0, _operation.op)({
|
|
conv2DBackpropFilter_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","../util":"ctavo","./conv_util":"bf4MH","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8847K":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
// Returns gradient for fused activation.
|
|
parcelHelpers.export(exports, "getFusedDyActivation", ()=>getFusedDyActivation);
|
|
// Returns gradient for fused bias.
|
|
parcelHelpers.export(exports, "getFusedBiasGradient", ()=>getFusedBiasGradient);
|
|
parcelHelpers.export(exports, "applyActivation", ()=>applyActivation);
|
|
parcelHelpers.export(exports, "shouldFuse", ()=>shouldFuse);
|
|
var _broadcastUtil = require("./broadcast_util");
|
|
var _elu = require("./elu");
|
|
var _leakyRelu = require("./leaky_relu");
|
|
var _mul = require("./mul");
|
|
var _prelu = require("./prelu");
|
|
var _relu = require("./relu");
|
|
var _relu6 = require("./relu6");
|
|
var _reshape = require("./reshape");
|
|
var _sigmoid = require("./sigmoid");
|
|
var _step = require("./step");
|
|
var _sum = require("./sum");
|
|
function getFusedDyActivation(dy, y, activation) {
|
|
if (activation == null || activation === "linear") return dy;
|
|
if (activation === "relu") return (0, _mul.mul)(dy, (0, _step.step)(y));
|
|
throw new Error(`Cannot compute gradient for fused activation ${activation}.`);
|
|
}
|
|
function getFusedBiasGradient(bias, dyActivation) {
|
|
let res = dyActivation;
|
|
const reduceAxes = _broadcastUtil.getReductionAxes(bias.shape, dyActivation.shape);
|
|
if (reduceAxes.length > 0) res = (0, _sum.sum)(res, reduceAxes);
|
|
return (0, _reshape.reshape)(res, bias.shape);
|
|
}
|
|
function applyActivation(x, activation, preluActivationWeights, leakyreluAlpha) {
|
|
if (activation === "linear") return x;
|
|
else if (activation === "relu") return (0, _relu.relu)(x);
|
|
else if (activation === "elu") return (0, _elu.elu)(x);
|
|
else if (activation === "relu6") return (0, _relu6.relu6)(x);
|
|
else if (activation === "prelu") return (0, _prelu.prelu)(x, preluActivationWeights);
|
|
else if (activation === "leakyrelu") return (0, _leakyRelu.leakyRelu)(x, leakyreluAlpha);
|
|
else if (activation === "sigmoid") return (0, _sigmoid.sigmoid)(x);
|
|
throw new Error(`Unknown fused activation ${activation}.`);
|
|
}
|
|
const shouldFuse = (gradientDepth, activation)=>{
|
|
const gradientMode = gradientDepth > 0;
|
|
return !gradientMode || activation === "linear";
|
|
};
|
|
|
|
},{"./broadcast_util":"eLo4J","./elu":"dE197","./leaky_relu":"aRBcm","./mul":"fOWrC","./prelu":"azJEF","./relu":"lcv3E","./relu6":"cvYLK","./reshape":"ew3wZ","./sigmoid":"81E16","./step":"bBBT4","./sum":"5awd0","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cEX74":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2d", ()=>depthwiseConv2d);
|
|
var _engine = require("../../engine");
|
|
var _gradients = require("../../gradients");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtil = require("../../tensor_util");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _add = require("../add");
|
|
var _broadcastUtil = require("../broadcast_util");
|
|
var _convUtil = require("../conv_util");
|
|
var _depthwiseConv2D = require("../depthwise_conv2d");
|
|
var _depthwiseConv2DNativeBackpropFilter = require("../depthwise_conv2d_native_backprop_filter");
|
|
var _depthwiseConv2DNativeBackpropInput = require("../depthwise_conv2d_native_backprop_input");
|
|
var _fusedUtil = require("../fused_util");
|
|
var _operation = require("../operation");
|
|
var _reshape = require("../reshape");
|
|
/**
|
|
* 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_docs/python/tf/nn/convolution](
|
|
* https://www.tensorflow.org/api_docs/python/tf/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 A string from: 'ceil', 'round', 'floor'. If none is
|
|
* provided, it will default to truncate.
|
|
* @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`.
|
|
* @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`
|
|
* activation.
|
|
*/ function fusedDepthwiseConv2d_({ x, filter, strides, pad, dataFormat = "NHWC", dilations = [
|
|
1,
|
|
1
|
|
], dimRoundingMode, bias, activation = "linear", preluActivationWeights, leakyreluAlpha }) {
|
|
if ((0, _fusedUtil.shouldFuse)((0, _engine.ENGINE).state.gradientDepth, activation) === false) {
|
|
let result = (0, _depthwiseConv2D.depthwiseConv2d)(x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
|
|
if (bias != null) result = (0, _add.add)(result, bias);
|
|
return (0, _fusedUtil.applyActivation)(result, activation, preluActivationWeights, leakyreluAlpha);
|
|
}
|
|
const $x = (0, _tensorUtilEnv.convertToTensor)(x, "x", "depthwiseConv2d", "float32");
|
|
const $filter = (0, _tensorUtilEnv.convertToTensor)(filter, "filter", "depthwiseConv2d", "float32");
|
|
let x4D = $x;
|
|
let reshapedTo4D = false;
|
|
if ($x.rank === 3) {
|
|
reshapedTo4D = true;
|
|
x4D = (0, _reshape.reshape)($x, [
|
|
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(_convUtil.eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in fused depthwiseConv2d: Either strides or dilations must " + `be 1. Got strides ${strides} and dilations '${dilations}'`);
|
|
_convUtil.checkPadOnDimRoundingMode("fused depthwiseConv2d", pad, dimRoundingMode);
|
|
const convInfo = _convUtil.computeConv2DInfo(x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode, true);
|
|
let $bias;
|
|
if (bias != null) {
|
|
$bias = (0, _tensorUtilEnv.convertToTensor)(bias, "bias", "fused conv2d");
|
|
[$bias] = (0, _tensorUtil.makeTypesMatch)($bias, $x);
|
|
_broadcastUtil.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
|
|
}
|
|
let $preluActivationWeights;
|
|
if (preluActivationWeights != null) $preluActivationWeights = (0, _tensorUtilEnv.convertToTensor)(preluActivationWeights, "prelu weights", "fused depthwiseConv2d");
|
|
const grad = (dy, saved)=>{
|
|
_util.assert(_convUtil.tupleValuesAreOne(dilations), ()=>"Error in gradient of fused depthwiseConv2d: dilation rates " + `greater than 1 are not yet supported. Got dilations ` + `'${dilations}'`);
|
|
const [$filter, x4D, y, bias] = saved;
|
|
const dyActivation = (0, _fusedUtil.getFusedDyActivation)(dy, y, activation);
|
|
const xDer = (0, _depthwiseConv2DNativeBackpropInput.depthwiseConv2dNativeBackpropInput)(x4D.shape, dyActivation, $filter, strides, pad, dilations, dimRoundingMode);
|
|
const filterDer = (0, _depthwiseConv2DNativeBackpropFilter.depthwiseConv2dNativeBackpropFilter)(x4D, dyActivation, $filter.shape, strides, pad, dilations, dimRoundingMode);
|
|
if (bias != null) {
|
|
const biasDer = (0, _fusedUtil.getFusedBiasGradient)($bias, dyActivation);
|
|
return [
|
|
xDer,
|
|
filterDer,
|
|
biasDer
|
|
];
|
|
}
|
|
return [
|
|
xDer,
|
|
filterDer
|
|
];
|
|
};
|
|
const inputs = {
|
|
x: x4D,
|
|
filter: $filter,
|
|
bias: $bias,
|
|
preluActivationWeights: $preluActivationWeights
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dilations,
|
|
dimRoundingMode,
|
|
activation,
|
|
leakyreluAlpha
|
|
};
|
|
// Depending on the the params passed in we will have different number of
|
|
// inputs and thus a a different number of elements in the gradient.
|
|
if (bias == null) {
|
|
const customOp = (0, _gradients.customGrad)((x4D, filter, save)=>{
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
let res = (0, _engine.ENGINE).runKernel((0, _kernelNames.FusedDepthwiseConv2D), inputs, attrs);
|
|
save([
|
|
filter,
|
|
x4D,
|
|
res
|
|
]);
|
|
if (reshapedTo4D) // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
res = (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return {
|
|
value: res,
|
|
gradFunc: grad
|
|
};
|
|
});
|
|
return customOp(x4D, $filter);
|
|
} else {
|
|
const customOpWithBias = (0, _gradients.customGrad)((x4D, filter, bias, save)=>{
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
let res = (0, _engine.ENGINE).runKernel((0, _kernelNames.FusedDepthwiseConv2D), inputs, attrs);
|
|
save([
|
|
filter,
|
|
x4D,
|
|
res,
|
|
bias
|
|
]);
|
|
if (reshapedTo4D) // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
res = (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return {
|
|
value: res,
|
|
gradFunc: grad
|
|
};
|
|
});
|
|
return customOpWithBias(x4D, $filter, $bias);
|
|
}
|
|
}
|
|
const depthwiseConv2d = /* @__PURE__ */ (0, _operation.op)({
|
|
fusedDepthwiseConv2d_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../gradients":"dDHpg","../../kernel_names":"hniYO","../../tensor_util":"8jzJG","../../tensor_util_env":"6vfHI","../../util":"ctavo","../add":"aynh7","../broadcast_util":"eLo4J","../conv_util":"bf4MH","../depthwise_conv2d":"cZHpb","../depthwise_conv2d_native_backprop_filter":"c0q2C","../depthwise_conv2d_native_backprop_input":"b4Cpx","../fused_util":"8847K","../operation":"ip64W","../reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c0q2C":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropFilter", ()=>depthwiseConv2dNativeBackpropFilter);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad, dilations = [
|
|
1,
|
|
1
|
|
], dimRoundingMode) {
|
|
let x4D = x;
|
|
if (x.rank === 3) x4D = (0, _reshape.reshape)(x, [
|
|
1,
|
|
x.shape[0],
|
|
x.shape[1],
|
|
x.shape[2]
|
|
]);
|
|
let dy4D = dy;
|
|
if (dy4D.rank === 3) dy4D = (0, _reshape.reshape)(dy, [
|
|
1,
|
|
dy.shape[0],
|
|
dy.shape[1],
|
|
dy.shape[2]
|
|
]);
|
|
const inputs = {
|
|
x: x4D,
|
|
dy: dy4D
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dimRoundingMode,
|
|
dilations,
|
|
filterShape
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.DepthwiseConv2dNativeBackpropFilter), inputs, attrs);
|
|
}
|
|
const depthwiseConv2dNativeBackpropFilter = (0, _operation.op)({
|
|
depthwiseConv2dNativeBackpropFilter_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b4Cpx":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropInput", ()=>depthwiseConv2dNativeBackpropInput);
|
|
var _engine = require("../engine");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _operation = require("./operation");
|
|
var _reshape = require("./reshape");
|
|
function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, strides, pad, dilations = [
|
|
1,
|
|
1
|
|
], dimRoundingMode) {
|
|
let dy4D = dy;
|
|
let reshapedTo4D = false;
|
|
if (dy.rank === 3) {
|
|
reshapedTo4D = true;
|
|
dy4D = (0, _reshape.reshape)(dy, [
|
|
1,
|
|
dy.shape[0],
|
|
dy.shape[1],
|
|
dy.shape[2]
|
|
]);
|
|
}
|
|
const inputs = {
|
|
dy: dy4D,
|
|
filter
|
|
};
|
|
const attrs = {
|
|
strides,
|
|
pad,
|
|
dimRoundingMode,
|
|
dilations,
|
|
inputShape: xShape
|
|
};
|
|
const res = // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
(0, _engine.ENGINE).runKernel((0, _kernelNames.DepthwiseConv2dNativeBackpropInput), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const depthwiseConv2dNativeBackpropInput = (0, _operation.op)({
|
|
depthwiseConv2dNativeBackpropInput_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../kernel_names":"hniYO","./operation":"ip64W","./reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6BB2f":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "matMul", ()=>matMul);
|
|
var _engine = require("../../engine");
|
|
var _gradients = require("../../gradients");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtil = require("../../tensor_util");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _add = require("../add");
|
|
var _broadcastUtil = require("../broadcast_util");
|
|
var _fusedUtil = require("../fused_util");
|
|
var _matMul = require("../mat_mul");
|
|
var _operation = require("../operation");
|
|
var _reshape = require("../reshape");
|
|
/**
|
|
* 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.
|
|
* - `leakyreluAlpha` Alpha of leakyrelu.
|
|
*/ function fusedMatMul_({ a, b, transposeA = false, transposeB = false, bias, activation = "linear", preluActivationWeights, leakyreluAlpha = 0.2 }) {
|
|
if ((0, _fusedUtil.shouldFuse)((0, _engine.ENGINE).state.gradientDepth, activation) === false) {
|
|
let result = (0, _matMul.matMul)(a, b, transposeA, transposeB);
|
|
if (bias != null) result = (0, _add.add)(result, bias);
|
|
return (0, _fusedUtil.applyActivation)(result, activation, preluActivationWeights, leakyreluAlpha);
|
|
}
|
|
let $a = (0, _tensorUtilEnv.convertToTensor)(a, "a", "fused matMul");
|
|
let $b = (0, _tensorUtilEnv.convertToTensor)(b, "b", "fused matMul");
|
|
[$a, $b] = (0, _tensorUtil.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(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 outShapeOuterDims = _broadcastUtil.assertAndGetBroadcastShape($a.shape.slice(0, -2), $b.shape.slice(0, -2));
|
|
const outShape = outShapeOuterDims.concat([
|
|
outerShapeA,
|
|
outerShapeB
|
|
]);
|
|
const a3D = transposeA ? (0, _reshape.reshape)($a, [
|
|
batchDimA,
|
|
innerShapeA,
|
|
outerShapeA
|
|
]) : (0, _reshape.reshape)($a, [
|
|
batchDimA,
|
|
outerShapeA,
|
|
innerShapeA
|
|
]);
|
|
const b3D = transposeB ? (0, _reshape.reshape)($b, [
|
|
batchDimB,
|
|
outerShapeB,
|
|
innerShapeB
|
|
]) : (0, _reshape.reshape)($b, [
|
|
batchDimB,
|
|
innerShapeB,
|
|
outerShapeB
|
|
]);
|
|
let $bias;
|
|
if (bias != null) {
|
|
$bias = (0, _tensorUtilEnv.convertToTensor)(bias, "bias", "fused matMul");
|
|
[$bias] = (0, _tensorUtil.makeTypesMatch)($bias, $a);
|
|
_broadcastUtil.assertAndGetBroadcastShape(outShape, $bias.shape);
|
|
}
|
|
let $preluActivationWeights;
|
|
if (preluActivationWeights != null) $preluActivationWeights = (0, _tensorUtilEnv.convertToTensor)(preluActivationWeights, "prelu weights", "fused matMul");
|
|
const grad = (dy, saved)=>{
|
|
const [a3D, b3D, y, $bias] = saved;
|
|
// we reshape dy because the result of the forward is not
|
|
// necessarily going to be a 3d tensor due to a reshape done at the end of
|
|
// the customOp.
|
|
const dyActivation = (0, _fusedUtil.getFusedDyActivation)((0, _reshape.reshape)(dy, y.shape), y, activation);
|
|
let aDer;
|
|
let bDer;
|
|
if (!transposeA && !transposeB) {
|
|
aDer = (0, _matMul.matMul)(dyActivation, b3D, false, true);
|
|
bDer = (0, _matMul.matMul)(a3D, dyActivation, true, false);
|
|
} else if (!transposeA && transposeB) {
|
|
aDer = (0, _matMul.matMul)(dyActivation, b3D, false, false);
|
|
bDer = (0, _matMul.matMul)(dyActivation, a3D, true, false);
|
|
} else if (transposeA && !transposeB) {
|
|
aDer = (0, _matMul.matMul)(b3D, dyActivation, false, true);
|
|
bDer = (0, _matMul.matMul)(a3D, dyActivation, false, false);
|
|
} else {
|
|
aDer = (0, _matMul.matMul)(b3D, dyActivation, true, true);
|
|
bDer = (0, _matMul.matMul)(dyActivation, a3D, true, true);
|
|
}
|
|
if (bias != null) {
|
|
const biasDer = (0, _fusedUtil.getFusedBiasGradient)($bias, dyActivation);
|
|
return [
|
|
aDer,
|
|
bDer,
|
|
biasDer
|
|
];
|
|
} else return [
|
|
aDer,
|
|
bDer
|
|
];
|
|
};
|
|
const inputs = {
|
|
a: a3D,
|
|
b: b3D,
|
|
bias: $bias,
|
|
preluActivationWeights: $preluActivationWeights
|
|
};
|
|
const attrs = {
|
|
transposeA,
|
|
transposeB,
|
|
activation,
|
|
leakyreluAlpha
|
|
};
|
|
// Depending on the the params passed in we will have different number of
|
|
// inputs and thus a a different number of elements in the gradient.
|
|
if (bias == null) {
|
|
const customOp = (0, _gradients.customGrad)((a3D, b3D, save)=>{
|
|
const res = // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
(0, _engine.ENGINE).runKernel((0, _kernelNames._FusedMatMul), inputs, attrs);
|
|
save([
|
|
a3D,
|
|
b3D,
|
|
res
|
|
]);
|
|
return {
|
|
value: (0, _reshape.reshape)(res, outShape),
|
|
gradFunc: grad
|
|
};
|
|
});
|
|
return customOp(a3D, b3D);
|
|
} else {
|
|
const customOpWithBias = (0, _gradients.customGrad)((a3D, b3D, $bias, save)=>{
|
|
const res = // tslint:disable-next-line: no-unnecessary-type-assertion
|
|
(0, _engine.ENGINE).runKernel((0, _kernelNames._FusedMatMul), inputs, attrs);
|
|
save([
|
|
a3D,
|
|
b3D,
|
|
res,
|
|
$bias
|
|
]);
|
|
return {
|
|
value: (0, _reshape.reshape)(res, outShape),
|
|
gradFunc: grad
|
|
};
|
|
});
|
|
return customOpWithBias(a3D, b3D, $bias);
|
|
}
|
|
}
|
|
const matMul = /* @__PURE__ */ (0, _operation.op)({
|
|
fusedMatMul_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../gradients":"dDHpg","../../kernel_names":"hniYO","../../tensor_util":"8jzJG","../../tensor_util_env":"6vfHI","../../util":"ctavo","../add":"aynh7","../broadcast_util":"eLo4J","../fused_util":"8847K","../mat_mul":"fiMp4","../operation":"ip64W","../reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"crMwx":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "hammingWindow", ()=>hammingWindow);
|
|
var _operation = require("../operation");
|
|
var _signalOpsUtil = require("../signal_ops_util");
|
|
/**
|
|
* 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 (0, _signalOpsUtil.cosineWindow)(windowLength, 0.54, 0.46);
|
|
}
|
|
const hammingWindow = /* @__PURE__ */ (0, _operation.op)({
|
|
hammingWindow_
|
|
});
|
|
|
|
},{"../operation":"ip64W","../signal_ops_util":"1EuF4","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lwQEl":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "hannWindow", ()=>hannWindow);
|
|
var _operation = require("../operation");
|
|
var _signalOpsUtil = require("../signal_ops_util");
|
|
/**
|
|
* 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 (0, _signalOpsUtil.cosineWindow)(windowLength, 0.5, 0.5);
|
|
}
|
|
const hannWindow = /* @__PURE__ */ (0, _operation.op)({
|
|
hannWindow_
|
|
});
|
|
|
|
},{"../operation":"ip64W","../signal_ops_util":"1EuF4","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3ntgK":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "frame", ()=>frame);
|
|
var _concat = require("../concat");
|
|
var _fill = require("../fill");
|
|
var _operation = require("../operation");
|
|
var _reshape = require("../reshape");
|
|
var _slice = require("../slice");
|
|
var _tensor2D = require("../tensor2d");
|
|
/**
|
|
* 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 A 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((0, _slice.slice)(signal, start, frameLength));
|
|
start += frameStep;
|
|
}
|
|
if (padEnd) while(start < signal.size){
|
|
const padLen = start + frameLength - signal.size;
|
|
const pad = (0, _concat.concat)([
|
|
(0, _slice.slice)(signal, start, frameLength - padLen),
|
|
(0, _fill.fill)([
|
|
padLen
|
|
], padValue)
|
|
]);
|
|
output.push(pad);
|
|
start += frameStep;
|
|
}
|
|
if (output.length === 0) return (0, _tensor2D.tensor2d)([], [
|
|
0,
|
|
frameLength
|
|
]);
|
|
return (0, _reshape.reshape)((0, _concat.concat)(output), [
|
|
output.length,
|
|
frameLength
|
|
]);
|
|
}
|
|
const frame = /* @__PURE__ */ (0, _operation.op)({
|
|
frame_
|
|
});
|
|
|
|
},{"../concat":"1NOyL","../fill":"i7goe","../operation":"ip64W","../reshape":"ew3wZ","../slice":"dr7Gq","../tensor2d":"faX5H","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gUBf5":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stft", ()=>stft);
|
|
var _mul = require("../mul");
|
|
var _operation = require("../operation");
|
|
var _signalOpsUtil = require("../signal_ops_util");
|
|
var _rfft = require("../spectral/rfft");
|
|
var _frame = require("./frame");
|
|
var _hannWindow = require("./hann_window");
|
|
/**
|
|
* 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 = (0, _hannWindow.hannWindow)) {
|
|
if (fftLength == null) fftLength = (0, _signalOpsUtil.enclosingPowerOfTwo)(frameLength);
|
|
const framedSignal = (0, _frame.frame)(signal, frameLength, frameStep);
|
|
const windowedSignal = (0, _mul.mul)(framedSignal, windowFn(frameLength));
|
|
return (0, _rfft.rfft)(windowedSignal, fftLength);
|
|
}
|
|
const stft = /* @__PURE__ */ (0, _operation.op)({
|
|
stft_
|
|
});
|
|
|
|
},{"../mul":"fOWrC","../operation":"ip64W","../signal_ops_util":"1EuF4","../spectral/rfft":"hnd5A","./frame":"3ntgK","./hann_window":"lwQEl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kQOfI":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cropAndResize", ()=>cropAndResize);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* 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 cropSize.
|
|
*
|
|
* @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 = "bilinear", extrapolationValue = 0) {
|
|
const $image = (0, _tensorUtilEnv.convertToTensor)(image, "image", "cropAndResize");
|
|
const $boxes = (0, _tensorUtilEnv.convertToTensor)(boxes, "boxes", "cropAndResize", "float32");
|
|
const $boxInd = (0, _tensorUtilEnv.convertToTensor)(boxInd, "boxInd", "cropAndResize", "int32");
|
|
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 inputs = {
|
|
image: $image,
|
|
boxes: $boxes,
|
|
boxInd: $boxInd
|
|
};
|
|
const attrs = {
|
|
method,
|
|
extrapolationValue,
|
|
cropSize
|
|
};
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.CropAndResize), inputs, attrs);
|
|
return res;
|
|
}
|
|
const cropAndResize = /* @__PURE__ */ (0, _operation.op)({
|
|
cropAndResize_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../../util":"ctavo","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7xdFd":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "flipLeftRight", ()=>flipLeftRight);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Flips the image left to right. Currently available in the CPU, WebGL, and
|
|
* WASM backends.
|
|
*
|
|
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
|
|
*/ /** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */ function flipLeftRight_(image) {
|
|
const $image = (0, _tensorUtilEnv.convertToTensor)(image, "image", "flipLeftRight", "float32");
|
|
_util.assert($image.rank === 4, ()=>"Error in flipLeftRight: image must be rank 4," + `but got rank ${$image.rank}.`);
|
|
const inputs = {
|
|
image: $image
|
|
};
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.FlipLeftRight), inputs, {});
|
|
return res;
|
|
}
|
|
const flipLeftRight = /* @__PURE__ */ (0, _operation.op)({
|
|
flipLeftRight_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../../util":"ctavo","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hbmqN":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "grayscaleToRGB", ()=>grayscaleToRGB);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
var _tile = require("../tile");
|
|
/**
|
|
* Converts images from grayscale to RGB format.
|
|
*
|
|
* @param image A grayscale tensor to convert. The `image`'s last dimension must
|
|
* be size 1 with at least a two-dimensional shape.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
|
|
*/ function grayscaleToRGB_(image) {
|
|
const $image = (0, _tensorUtilEnv.convertToTensor)(image, "image", "grayscaleToRGB");
|
|
const lastDimsIdx = $image.rank - 1;
|
|
const lastDims = $image.shape[lastDimsIdx];
|
|
_util.assert($image.rank >= 2, ()=>"Error in grayscaleToRGB: images must be at least rank 2, " + `but got rank ${$image.rank}.`);
|
|
_util.assert(lastDims === 1, ()=>"Error in grayscaleToRGB: last dimension of a grayscale image " + `should be size 1, but got size ${lastDims}.`);
|
|
const reps = new Array($image.rank);
|
|
reps.fill(1, 0, lastDimsIdx);
|
|
reps[lastDimsIdx] = 3;
|
|
return (0, _tile.tile)($image, reps);
|
|
}
|
|
const grayscaleToRGB = /* @__PURE__ */ (0, _operation.op)({
|
|
grayscaleToRGB_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../operation":"ip64W","../tile":"gzqG2","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hrZfi":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rgbToGrayscale", ()=>rgbToGrayscale);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _cast = require("../cast");
|
|
var _einsum = require("../einsum");
|
|
var _expandDims = require("../expand_dims");
|
|
var _operation = require("../operation");
|
|
var _tensor1D = require("../tensor1d");
|
|
/**
|
|
* Converts images from RGB format to grayscale.
|
|
*
|
|
* @param image A RGB tensor to convert. The `image`'s last dimension must
|
|
* be size 3 with at least a two-dimensional shape.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
|
|
*/ function rgbToGrayscale_(image) {
|
|
const $image = (0, _tensorUtilEnv.convertToTensor)(image, "image", "RGBToGrayscale");
|
|
const lastDimsIdx = $image.rank - 1;
|
|
const lastDims = $image.shape[lastDimsIdx];
|
|
_util.assert($image.rank >= 2, ()=>"Error in RGBToGrayscale: images must be at least rank 2, " + `but got rank ${$image.rank}.`);
|
|
_util.assert(lastDims === 3, ()=>"Error in RGBToGrayscale: last dimension of an RGB image " + `should be size 3, but got size ${lastDims}.`);
|
|
// Remember original dtype so we can convert back if needed
|
|
const origDtype = $image.dtype;
|
|
const fltImage = (0, _cast.cast)($image, "float32");
|
|
const rgbWeights = (0, _tensor1D.tensor1d)([
|
|
0.2989,
|
|
0.5870,
|
|
0.1140
|
|
]);
|
|
let grayFloat;
|
|
switch($image.rank){
|
|
case 2:
|
|
grayFloat = (0, _einsum.einsum)("ij,j->i", fltImage, rgbWeights);
|
|
break;
|
|
case 3:
|
|
grayFloat = (0, _einsum.einsum)("ijk,k->ij", fltImage, rgbWeights);
|
|
break;
|
|
case 4:
|
|
grayFloat = (0, _einsum.einsum)("ijkl,l->ijk", fltImage, rgbWeights);
|
|
break;
|
|
case 5:
|
|
grayFloat = (0, _einsum.einsum)("ijklm,m->ijkl", fltImage, rgbWeights);
|
|
break;
|
|
case 6:
|
|
grayFloat = (0, _einsum.einsum)("ijklmn,n->ijklm", fltImage, rgbWeights);
|
|
break;
|
|
default:
|
|
throw new Error("Not a valid tensor rank.");
|
|
}
|
|
grayFloat = (0, _expandDims.expandDims)(grayFloat, -1);
|
|
return (0, _cast.cast)(grayFloat, origDtype);
|
|
}
|
|
const rgbToGrayscale = /* @__PURE__ */ (0, _operation.op)({
|
|
rgbToGrayscale_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../cast":"b4VDA","../einsum":"adKPG","../expand_dims":"lc7t7","../operation":"ip64W","../tensor1d":"aEL9e","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"df6QK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rotateWithOffset", ()=>rotateWithOffset);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Rotates the input image tensor counter-clockwise with an optional offset
|
|
* center of rotation. Currently available in the CPU, WebGL, and WASM backends.
|
|
*
|
|
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
|
|
* @param radians The amount of rotation.
|
|
* @param fillValue The value to fill in the empty space leftover
|
|
* after rotation. Can be either a single grayscale value (0-255), or an
|
|
* array of three numbers `[red, green, blue]` specifying the red, green,
|
|
* and blue channels. Defaults to `0` (black).
|
|
* @param center The center of rotation. Can be either a single value (0-1), or
|
|
* an array of two numbers `[centerX, centerY]`. Defaults to `0.5` (rotates
|
|
* the image around its center).
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
|
|
*/ function rotateWithOffset_(image, radians, fillValue = 0, center = 0.5) {
|
|
const $image = (0, _tensorUtilEnv.convertToTensor)(image, "image", "rotateWithOffset", "float32");
|
|
_util.assert($image.rank === 4, ()=>"Error in rotateWithOffset: image must be rank 4," + `but got rank ${$image.rank}.`);
|
|
const inputs = {
|
|
image: $image
|
|
};
|
|
const attrs = {
|
|
radians,
|
|
fillValue,
|
|
center
|
|
};
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.RotateWithOffset), inputs, attrs);
|
|
return res;
|
|
}
|
|
const rotateWithOffset = /* @__PURE__ */ (0, _operation.op)({
|
|
rotateWithOffset_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../../util":"ctavo","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bQBrw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppression", ()=>nonMaxSuppression);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _nonmaxUtil = require("../nonmax_util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* 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'}
|
|
*/ function nonMaxSuppression_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY) {
|
|
const $boxes = (0, _tensorUtilEnv.convertToTensor)(boxes, "boxes", "nonMaxSuppression", "float32");
|
|
const $scores = (0, _tensorUtilEnv.convertToTensor)(scores, "scores", "nonMaxSuppression", "float32");
|
|
const inputs = (0, _nonmaxUtil.nonMaxSuppSanityCheck)($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
|
|
maxOutputSize = inputs.maxOutputSize;
|
|
iouThreshold = inputs.iouThreshold;
|
|
scoreThreshold = inputs.scoreThreshold;
|
|
const attrs = {
|
|
maxOutputSize,
|
|
iouThreshold,
|
|
scoreThreshold
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.NonMaxSuppressionV3), {
|
|
boxes: $boxes,
|
|
scores: $scores
|
|
}, attrs);
|
|
}
|
|
const nonMaxSuppression = /* @__PURE__ */ (0, _operation.op)({
|
|
nonMaxSuppression_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../nonmax_util":"g968U","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g968U":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppSanityCheck", ()=>nonMaxSuppSanityCheck);
|
|
var _util = require("../util");
|
|
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
|
|
};
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8ps8b":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionAsync", ()=>nonMaxSuppressionAsync);
|
|
var _nonMaxSuppressionImpl = require("../../backends/non_max_suppression_impl");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _nonmaxUtil = require("../nonmax_util");
|
|
var _tensor1D = require("../tensor1d");
|
|
/**
|
|
* Performs non maximum suppression of bounding boxes based on
|
|
* iou (intersection over union).
|
|
*
|
|
* This is the async version of `nonMaxSuppression`
|
|
*
|
|
* @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'}
|
|
*/ async function nonMaxSuppressionAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY) {
|
|
const $boxes = (0, _tensorUtilEnv.convertToTensor)(boxes, "boxes", "nonMaxSuppressionAsync");
|
|
const $scores = (0, _tensorUtilEnv.convertToTensor)(scores, "scores", "nonMaxSuppressionAsync");
|
|
const inputs = (0, _nonmaxUtil.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];
|
|
// We call a cpu based impl directly with the typedarray data here rather
|
|
// than a kernel because all kernels are synchronous (and thus cannot await
|
|
// .data()).
|
|
const { selectedIndices } = (0, _nonMaxSuppressionImpl.nonMaxSuppressionV3Impl)(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);
|
|
if ($boxes !== boxes) $boxes.dispose();
|
|
if ($scores !== scores) $scores.dispose();
|
|
return (0, _tensor1D.tensor1d)(selectedIndices, "int32");
|
|
}
|
|
const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
|
|
|
|
},{"../../backends/non_max_suppression_impl":"e0x4w","../../tensor_util_env":"6vfHI","../nonmax_util":"g968U","../tensor1d":"aEL9e","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"e0x4w":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV3Impl", ()=>nonMaxSuppressionV3Impl);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV4Impl", ()=>nonMaxSuppressionV4Impl);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV5Impl", ()=>nonMaxSuppressionV5Impl);
|
|
var _nonMaxSuppressionUtil = require("./non_max_suppression_util");
|
|
function nonMaxSuppressionV3Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
|
|
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, 0 /* softNmsSigma */ );
|
|
}
|
|
function nonMaxSuppressionV4Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
|
|
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, 0 /* softNmsSigma */ , false, padToMaxOutputSize /* padToMaxOutputSize */ , true);
|
|
}
|
|
function nonMaxSuppressionV5Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
|
|
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, true);
|
|
}
|
|
function nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, returnScoresTensor = false, padToMaxOutputSize = false, returnValidOutputs = 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.
|
|
(0, _nonMaxSuppressionUtil.binaryInsert)(candidates, candidate, ascendingComparator);
|
|
}
|
|
}
|
|
// NonMaxSuppressionV4 feature: padding output to maxOutputSize.
|
|
const validOutputs = selectedIndices.length;
|
|
const elemsToPad = maxOutputSize - validOutputs;
|
|
if (padToMaxOutputSize && elemsToPad > 0) {
|
|
selectedIndices.push(...new Array(elemsToPad).fill(0));
|
|
selectedScores.push(...new Array(elemsToPad).fill(0.0));
|
|
}
|
|
const result = {
|
|
selectedIndices
|
|
};
|
|
if (returnScoresTensor) result["selectedScores"] = selectedScores;
|
|
if (returnValidOutputs) result["validOutputs"] = validOutputs;
|
|
return result;
|
|
}
|
|
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;
|
|
}
|
|
|
|
},{"./non_max_suppression_util":"i4jUO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"i4jUO":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "binaryInsert", ()=>binaryInsert);
|
|
/**
|
|
* 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).
|
|
*/ parcelHelpers.export(exports, "binarySearch", ()=>binarySearch);
|
|
function binaryInsert(arr, element, comparator) {
|
|
const index = binarySearch(arr, element, comparator);
|
|
const insertionPoint = index < 0 ? -(index + 1) : index;
|
|
arr.splice(insertionPoint, 0, element);
|
|
}
|
|
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;
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"khN9i":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionWithScore", ()=>nonMaxSuppressionWithScore);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _nonmaxUtil = require("../nonmax_util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Performs non maximum suppression of bounding boxes based on
|
|
* iou (intersection over union).
|
|
*
|
|
* This op also supports a Soft-NMS mode (cf.
|
|
* 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 = (0, _tensorUtilEnv.convertToTensor)(boxes, "boxes", "nonMaxSuppression");
|
|
const $scores = (0, _tensorUtilEnv.convertToTensor)(scores, "scores", "nonMaxSuppression");
|
|
const params = (0, _nonmaxUtil.nonMaxSuppSanityCheck)($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
|
|
maxOutputSize = params.maxOutputSize;
|
|
iouThreshold = params.iouThreshold;
|
|
scoreThreshold = params.scoreThreshold;
|
|
softNmsSigma = params.softNmsSigma;
|
|
const inputs = {
|
|
boxes: $boxes,
|
|
scores: $scores
|
|
};
|
|
const attrs = {
|
|
maxOutputSize,
|
|
iouThreshold,
|
|
scoreThreshold,
|
|
softNmsSigma
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.NonMaxSuppressionV5), inputs, attrs);
|
|
return {
|
|
selectedIndices: result[0],
|
|
selectedScores: result[1]
|
|
};
|
|
}
|
|
const nonMaxSuppressionWithScore = /* @__PURE__ */ (0, _operation.op)({
|
|
nonMaxSuppressionWithScore_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../nonmax_util":"g968U","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bH9TE":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionWithScoreAsync", ()=>nonMaxSuppressionWithScoreAsync);
|
|
var _nonMaxSuppressionImpl = require("../../backends/non_max_suppression_impl");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _nonmaxUtil = require("../nonmax_util");
|
|
var _tensor1D = require("../tensor1d");
|
|
/**
|
|
* Asynchronously performs non maximum suppression of bounding boxes based on
|
|
* iou (intersection over union).
|
|
*
|
|
* This op also supports a Soft-NMS mode (cf.
|
|
* 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'}
|
|
*/ async function nonMaxSuppressionWithScoreAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, softNmsSigma = 0.0) {
|
|
const $boxes = (0, _tensorUtilEnv.convertToTensor)(boxes, "boxes", "nonMaxSuppressionAsync");
|
|
const $scores = (0, _tensorUtilEnv.convertToTensor)(scores, "scores", "nonMaxSuppressionAsync");
|
|
const params = (0, _nonmaxUtil.nonMaxSuppSanityCheck)($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
|
|
maxOutputSize = params.maxOutputSize;
|
|
iouThreshold = params.iouThreshold;
|
|
scoreThreshold = params.scoreThreshold;
|
|
softNmsSigma = params.softNmsSigma;
|
|
const boxesAndScores = await Promise.all([
|
|
$boxes.data(),
|
|
$scores.data()
|
|
]);
|
|
const boxesVals = boxesAndScores[0];
|
|
const scoresVals = boxesAndScores[1];
|
|
// We call a cpu based impl directly with the typedarray data here rather
|
|
// than a kernel because all kernels are synchronous (and thus cannot await
|
|
// .data()).
|
|
const { selectedIndices, selectedScores } = (0, _nonMaxSuppressionImpl.nonMaxSuppressionV5Impl)(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
|
|
if ($boxes !== boxes) $boxes.dispose();
|
|
if ($scores !== scores) $scores.dispose();
|
|
return {
|
|
selectedIndices: (0, _tensor1D.tensor1d)(selectedIndices, "int32"),
|
|
selectedScores: (0, _tensor1D.tensor1d)(selectedScores)
|
|
};
|
|
}
|
|
const nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;
|
|
|
|
},{"../../backends/non_max_suppression_impl":"e0x4w","../../tensor_util_env":"6vfHI","../nonmax_util":"g968U","../tensor1d":"aEL9e","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3Hdah":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionPadded", ()=>nonMaxSuppressionPadded);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _nonmaxUtil = require("../nonmax_util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Asynchronously performs non maximum suppression of bounding boxes based on
|
|
* iou (intersection over union), with an option to pad results.
|
|
*
|
|
* @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 padToMaxOutputSize Defaults to false. If true, size of output
|
|
* `selectedIndices` is padded to maxOutputSize.
|
|
* @return A map with the following properties:
|
|
* - selectedIndices: A 1D tensor with the selected box indices.
|
|
* - validOutputs: A scalar denoting how many elements in `selectedIndices`
|
|
* are valid. Valid elements occur first, then padding.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
|
|
*/ function nonMaxSuppressionPadded_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, padToMaxOutputSize = false) {
|
|
const $boxes = (0, _tensorUtilEnv.convertToTensor)(boxes, "boxes", "nonMaxSuppression");
|
|
const $scores = (0, _tensorUtilEnv.convertToTensor)(scores, "scores", "nonMaxSuppression");
|
|
const params = (0, _nonmaxUtil.nonMaxSuppSanityCheck)($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, null);
|
|
const $maxOutputSize = params.maxOutputSize;
|
|
const $iouThreshold = params.iouThreshold;
|
|
const $scoreThreshold = params.scoreThreshold;
|
|
const inputs = {
|
|
boxes: $boxes,
|
|
scores: $scores
|
|
};
|
|
const attrs = {
|
|
maxOutputSize: $maxOutputSize,
|
|
iouThreshold: $iouThreshold,
|
|
scoreThreshold: $scoreThreshold,
|
|
padToMaxOutputSize
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.NonMaxSuppressionV4), inputs, attrs);
|
|
return {
|
|
selectedIndices: result[0],
|
|
validOutputs: result[1]
|
|
};
|
|
}
|
|
const nonMaxSuppressionPadded = /* @__PURE__ */ (0, _operation.op)({
|
|
nonMaxSuppressionPadded_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../nonmax_util":"g968U","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dJg2S":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionPaddedAsync", ()=>nonMaxSuppressionPaddedAsync);
|
|
var _nonMaxSuppressionImpl = require("../../backends/non_max_suppression_impl");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _nonmaxUtil = require("../nonmax_util");
|
|
var _scalar = require("../scalar");
|
|
var _tensor1D = require("../tensor1d");
|
|
/**
|
|
* Asynchronously performs non maximum suppression of bounding boxes based on
|
|
* iou (intersection over union), with an option to pad results.
|
|
*
|
|
* @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 padToMaxOutputSize Defaults to false. If true, size of output
|
|
* `selectedIndices` is padded to maxOutputSize.
|
|
* @return A map with the following properties:
|
|
* - selectedIndices: A 1D tensor with the selected box indices.
|
|
* - validOutputs: A scalar denoting how many elements in `selectedIndices`
|
|
* are valid. Valid elements occur first, then padding.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
|
|
*/ async function nonMaxSuppressionPaddedAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, padToMaxOutputSize = false) {
|
|
const $boxes = (0, _tensorUtilEnv.convertToTensor)(boxes, "boxes", "nonMaxSuppressionAsync");
|
|
const $scores = (0, _tensorUtilEnv.convertToTensor)(scores, "scores", "nonMaxSuppressionAsync");
|
|
const params = (0, _nonmaxUtil.nonMaxSuppSanityCheck)($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, null);
|
|
const $maxOutputSize = params.maxOutputSize;
|
|
const $iouThreshold = params.iouThreshold;
|
|
const $scoreThreshold = params.scoreThreshold;
|
|
const [boxesVals, scoresVals] = await Promise.all([
|
|
$boxes.data(),
|
|
$scores.data()
|
|
]);
|
|
// We call a cpu based impl directly with the typedarray data here rather
|
|
// than a kernel because all kernels are synchronous (and thus cannot await
|
|
// .data()).
|
|
const { selectedIndices, validOutputs } = (0, _nonMaxSuppressionImpl.nonMaxSuppressionV4Impl)(boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold, padToMaxOutputSize);
|
|
if ($boxes !== boxes) $boxes.dispose();
|
|
if ($scores !== scores) $scores.dispose();
|
|
return {
|
|
selectedIndices: (0, _tensor1D.tensor1d)(selectedIndices, "int32"),
|
|
validOutputs: (0, _scalar.scalar)(validOutputs, "int32")
|
|
};
|
|
}
|
|
const nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;
|
|
|
|
},{"../../backends/non_max_suppression_impl":"e0x4w","../../tensor_util_env":"6vfHI","../nonmax_util":"g968U","../scalar":"7lhC8","../tensor1d":"aEL9e","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"h5fgY":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeBilinear", ()=>resizeBilinear);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
var _reshape = require("../reshape");
|
|
/**
|
|
* Bilinear resize a single 3D image or 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.
|
|
* @param halfPixelCenters Defaults to `false`. Whether to assume pixel centers
|
|
* are at 0.5, which would make the floating point coordinates of the top
|
|
* left pixel 0.5, 0.5.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
|
|
*/ function resizeBilinear_(images, size, alignCorners = false, halfPixelCenters = false) {
|
|
const $images = (0, _tensorUtilEnv.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}.`);
|
|
_util.assert(halfPixelCenters === false || alignCorners === false, ()=>`Error in resizeBilinear: If halfPixelCenters is true, ` + `alignCorners must be false.`);
|
|
let batchImages = $images;
|
|
let reshapedTo4D = false;
|
|
if ($images.rank === 3) {
|
|
reshapedTo4D = true;
|
|
batchImages = (0, _reshape.reshape)($images, [
|
|
1,
|
|
$images.shape[0],
|
|
$images.shape[1],
|
|
$images.shape[2]
|
|
]);
|
|
}
|
|
const [] = size;
|
|
const inputs = {
|
|
images: batchImages
|
|
};
|
|
const attrs = {
|
|
alignCorners,
|
|
halfPixelCenters,
|
|
size
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.ResizeBilinear), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const resizeBilinear = /* @__PURE__ */ (0, _operation.op)({
|
|
resizeBilinear_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../../util":"ctavo","../operation":"ip64W","../reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6vytD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeNearestNeighbor", ()=>resizeNearestNeighbor);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
var _reshape = require("../reshape");
|
|
/**
|
|
* 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.
|
|
* @param halfPixelCenters Defaults to `false`. Whether to assume pixels are of
|
|
* half the actual dimensions, and yield more accurate resizes. This flag
|
|
* would also make the floating point coordinates of the top left pixel
|
|
* 0.5, 0.5.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
|
|
*/ function resizeNearestNeighbor_(images, size, alignCorners = false, halfPixelCenters = false) {
|
|
const $images = (0, _tensorUtilEnv.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");
|
|
_util.assert(halfPixelCenters === false || alignCorners === false, ()=>`Error in resizeNearestNeighbor: If halfPixelCenters is true, ` + `alignCorners must be false.`);
|
|
let batchImages = $images;
|
|
let reshapedTo4D = false;
|
|
if ($images.rank === 3) {
|
|
reshapedTo4D = true;
|
|
batchImages = (0, _reshape.reshape)($images, [
|
|
1,
|
|
$images.shape[0],
|
|
$images.shape[1],
|
|
$images.shape[2]
|
|
]);
|
|
}
|
|
const [] = size;
|
|
const inputs = {
|
|
images: batchImages
|
|
};
|
|
const attrs = {
|
|
alignCorners,
|
|
halfPixelCenters,
|
|
size
|
|
};
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const res = (0, _engine.ENGINE).runKernel((0, _kernelNames.ResizeNearestNeighbor), inputs, attrs);
|
|
if (reshapedTo4D) return (0, _reshape.reshape)(res, [
|
|
res.shape[1],
|
|
res.shape[2],
|
|
res.shape[3]
|
|
]);
|
|
return res;
|
|
}
|
|
const resizeNearestNeighbor = /* @__PURE__ */ (0, _operation.op)({
|
|
resizeNearestNeighbor_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../../util":"ctavo","../operation":"ip64W","../reshape":"ew3wZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"d58R4":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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
|
|
*
|
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "threshold", ()=>threshold);
|
|
var _tensor1D = require("../tensor1d");
|
|
var _operation = require("../operation");
|
|
var _cast = require("../cast");
|
|
var _split = require("../split");
|
|
var _bincount = require("../bincount");
|
|
var _lessEqual = require("../less_equal");
|
|
var _greater = require("../greater");
|
|
var _sum = require("../sum");
|
|
var _add = require("../add");
|
|
var _mul = require("../mul");
|
|
var _div = require("../div");
|
|
var _sub = require("../sub");
|
|
var _round = require("../round");
|
|
var _where = require("../where");
|
|
var _fill = require("../fill");
|
|
var _slice = require("../slice");
|
|
var _range = require("../range");
|
|
var _tensor = require("../tensor");
|
|
var _util = require("../../util");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
/**
|
|
* Performs image binarization with corresponding threshold
|
|
* (depends on the method)value, which creates a binary image from a grayscale.
|
|
* @param image 3d tensor of shape [imageHeight,imageWidth, depth],
|
|
* where imageHeight and imageWidth must be positive.The image color
|
|
* range should be [0, 255].
|
|
* @param method Optional string from `'binary' | 'otsu'`
|
|
* which specifies the method for thresholding. Defaults to 'binary'.
|
|
* @param inverted Optional boolean whichspecifies
|
|
* if colours should be inverted. Defaults to false.
|
|
* @param threshValue Optional number which defines threshold value from 0 to 1.
|
|
* Defaults to 0.5.
|
|
* @return A 3d tensor of shape [imageHeight,imageWidth, depth], which
|
|
* contains binarized image.
|
|
*/ function threshold_(image, method = "binary", inverted = false, threshValue = 0.5) {
|
|
const $image = (0, _tensorUtilEnv.convertToTensor)(image, "image", "threshold");
|
|
/* 0.2989, 0.5870, 0.1140 are represent luma coefficients in CCIR601.
|
|
Reference for converting between RGB and grayscale: https://en.wikipedia.org/wiki/Luma_%28video%29 */ const RED_INTENCITY_COEF = 0.2989;
|
|
const GREEN_INTENCITY_COEF = 0.5870;
|
|
const BLUE_INTENCITY_COEF = 0.1140;
|
|
const totalPixelsInImage = $image.shape[0] * $image.shape[1];
|
|
let $threshold = (0, _mul.mul)((0, _tensor1D.tensor1d)([
|
|
threshValue
|
|
]), 255);
|
|
let r, g, b, grayscale;
|
|
_util.assert($image.rank === 3, ()=>"Error in threshold: image must be rank 3," + `but got rank ${$image.rank}.`);
|
|
_util.assert($image.shape[2] === 3 || $image.shape[2] === 1, ()=>"Error in threshold: image color channel must be equal to 3 or 1" + `but got ${$image.shape[2]}.`);
|
|
_util.assert($image.dtype === "int32" || $image.dtype === "float32", ()=>"Error in dtype: image dtype must be int32 or float32," + `but got dtype ${$image.dtype}.`);
|
|
_util.assert(method === "otsu" || method === "binary", ()=>`Method must be binary or otsu, but was ${method}`);
|
|
if ($image.shape[2] === 3) {
|
|
[r, g, b] = (0, _split.split)($image, [
|
|
1,
|
|
1,
|
|
1
|
|
], -1);
|
|
const $r = (0, _mul.mul)(r, RED_INTENCITY_COEF);
|
|
const $g = (0, _mul.mul)(g, GREEN_INTENCITY_COEF);
|
|
const $b = (0, _mul.mul)(b, BLUE_INTENCITY_COEF);
|
|
grayscale = (0, _add.add)((0, _add.add)($r, $g), $b);
|
|
} else grayscale = image;
|
|
if (method === "otsu") {
|
|
const $histogram = (0, _bincount.bincount)((0, _cast.cast)((0, _round.round)(grayscale), "int32"), (0, _tensor.tensor)([]), 256);
|
|
$threshold = otsu($histogram, totalPixelsInImage);
|
|
}
|
|
const invCondition = inverted ? (0, _lessEqual.lessEqual)(grayscale, $threshold) : (0, _greater.greater)(grayscale, $threshold);
|
|
const result = (0, _cast.cast)((0, _mul.mul)(invCondition, 255), "int32");
|
|
return result;
|
|
}
|
|
function otsu(histogram, total) {
|
|
let bestThresh = (0, _tensor1D.tensor1d)([
|
|
-1
|
|
]);
|
|
let bestInBetVar = (0, _tensor1D.tensor1d)([
|
|
0
|
|
]);
|
|
let cInBetVar = (0, _tensor1D.tensor1d)([
|
|
0
|
|
]);
|
|
let classFirst, classSecond, meanFirst, meanSec, weightForeground, weightBack;
|
|
for(let index = 0; index < histogram.size - 1; index++){
|
|
classFirst = (0, _slice.slice)(histogram, 0, index + 1);
|
|
classSecond = (0, _slice.slice)(histogram, index + 1);
|
|
weightForeground = (0, _div.div)((0, _sum.sum)(classFirst), total);
|
|
weightBack = (0, _div.div)((0, _sum.sum)(classSecond), total);
|
|
const meanFirstDivA = (0, _sum.sum)((0, _mul.mul)(classFirst, (0, _range.range)(0, classFirst.size)));
|
|
meanFirst = (0, _div.div)(meanFirstDivA, (0, _sum.sum)(classFirst));
|
|
const meanSecFill = (0, _fill.fill)(classSecond.shape, classFirst.size);
|
|
const meanSecAdd = (0, _add.add)((0, _range.range)(0, classSecond.size), meanSecFill);
|
|
const meanSecMul = (0, _mul.mul)(classSecond, meanSecAdd);
|
|
meanSec = (0, _div.div)((0, _sum.sum)(meanSecMul), (0, _sum.sum)(classSecond));
|
|
const cInBetVarSubA = (0, _sub.sub)(meanFirst, meanSec);
|
|
const cInBetVarSubB = (0, _sub.sub)(meanFirst, meanSec);
|
|
const cInBetVarMul = (0, _mul.mul)(weightForeground, weightBack);
|
|
cInBetVar = (0, _mul.mul)((0, _mul.mul)(cInBetVarMul, cInBetVarSubA), cInBetVarSubB);
|
|
const condition = (0, _greater.greater)(cInBetVar, bestInBetVar);
|
|
bestInBetVar = (0, _where.where)(condition, cInBetVar, bestInBetVar);
|
|
bestThresh = (0, _where.where)(condition, (0, _tensor1D.tensor1d)([
|
|
index
|
|
]), bestThresh);
|
|
}
|
|
return bestThresh;
|
|
}
|
|
const threshold = /* @__PURE__ */ (0, _operation.op)({
|
|
threshold_
|
|
});
|
|
|
|
},{"../tensor1d":"aEL9e","../operation":"ip64W","../cast":"b4VDA","../split":"l0HF2","../bincount":"gW00L","../less_equal":"j9Jhy","../greater":"3Nh8O","../sum":"5awd0","../add":"aynh7","../mul":"fOWrC","../div":"5ZT1h","../sub":"jBBQ2","../round":"4aCvQ","../where":"47cKc","../fill":"i7goe","../slice":"dr7Gq","../range":"3seHd","../tensor":"jdbb1","../../util":"ctavo","../../tensor_util_env":"6vfHI","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"sijU0":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "transform", ()=>transform);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Applies the given transform(s) to the image(s).
|
|
*
|
|
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
|
|
* @param transforms Projective transform matrix/matrices. A tensor1d of length
|
|
* 8 or tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0,
|
|
* b1, b2, c0, c1], then it maps the output point (x, y) to a transformed
|
|
* input point (x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k),
|
|
* where k = c0 x + c1 y + 1. The transforms are inverted compared to the
|
|
* transform mapping input points to output points.
|
|
* @param interpolation Interpolation mode.
|
|
* Supported values: 'nearest', 'bilinear'. Default to 'nearest'.
|
|
* @param fillMode Points outside the boundaries of the input are filled
|
|
* according to the given mode, one of 'constant', 'reflect', 'wrap',
|
|
* 'nearest'. Default to 'constant'.
|
|
* 'reflect': (d c b a | a b c d | d c b a ) The input is extended by
|
|
* reflecting about the edge of the last pixel.
|
|
* 'constant': (k k k k | a b c d | k k k k) The input is extended by
|
|
* filling all values beyond the edge with the same constant value k.
|
|
* 'wrap': (a b c d | a b c d | a b c d) The input is extended by
|
|
* wrapping around to the opposite edge.
|
|
* 'nearest': (a a a a | a b c d | d d d d) The input is extended by
|
|
* the nearest pixel.
|
|
* @param fillValue A float represents the value to be filled outside the
|
|
* boundaries when fillMode is 'constant'.
|
|
* @param Output dimension after the transform, [height, width]. If undefined,
|
|
* output is the same size as input image.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
|
|
*/ function transform_(image, transforms, interpolation = "nearest", fillMode = "constant", fillValue = 0, outputShape) {
|
|
const $image = (0, _tensorUtilEnv.convertToTensor)(image, "image", "transform", "float32");
|
|
const $transforms = (0, _tensorUtilEnv.convertToTensor)(transforms, "transforms", "transform", "float32");
|
|
_util.assert($image.rank === 4, ()=>"Error in transform: image must be rank 4," + `but got rank ${$image.rank}.`);
|
|
_util.assert($transforms.rank === 2 && ($transforms.shape[0] === $image.shape[0] || $transforms.shape[0] === 1) && $transforms.shape[1] === 8, ()=>`Error in transform: Input transform should be batch x 8 or 1 x 8`);
|
|
_util.assert(outputShape == null || outputShape.length === 2, ()=>"Error in transform: outputShape must be [height, width] or null, " + `but got ${outputShape}.`);
|
|
const inputs = {
|
|
image: $image,
|
|
transforms: $transforms
|
|
};
|
|
const attrs = {
|
|
interpolation,
|
|
fillMode,
|
|
fillValue,
|
|
outputShape
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.Transform), inputs, attrs);
|
|
}
|
|
const transform = /* @__PURE__ */ (0, _operation.op)({
|
|
transform_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../../util":"ctavo","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cLsM5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "bandPart", ()=>bandPart);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _greaterEqual = require("../greater_equal");
|
|
var _less = require("../less");
|
|
var _lessEqual = require("../less_equal");
|
|
var _logicalAnd = require("../logical_and");
|
|
var _minimum = require("../minimum");
|
|
var _neg = require("../neg");
|
|
var _operation = require("../operation");
|
|
var _range = require("../range");
|
|
var _reshape = require("../reshape");
|
|
var _stack = require("../stack");
|
|
var _sub = require("../sub");
|
|
var _unstack = require("../unstack");
|
|
var _where = require("../where");
|
|
var _zeros = require("../zeros");
|
|
/**
|
|
* 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) {
|
|
const $a = (0, _tensorUtilEnv.convertToTensor)(a, "a", "bandPart");
|
|
(0, _util.assert)($a.rank >= 2, ()=>`bandPart(): Rank must be at least 2, got ${$a.rank}.`);
|
|
const shape = $a.shape;
|
|
const [M, N] = $a.shape.slice(-2);
|
|
let $numLower;
|
|
let $numUpper;
|
|
if (typeof numLower === "number") {
|
|
(0, _util.assert)(numLower % 1 === 0, ()=>`bandPart(): numLower must be an integer, got ${numLower}.`);
|
|
(0, _util.assert)(numLower <= M, ()=>`bandPart(): numLower (${numLower})` + ` must not be greater than the number of rows (${M}).`);
|
|
$numLower = (0, _tensorUtilEnv.convertToTensor)(numLower < 0 ? M : numLower, "numLower", "bandPart");
|
|
} else {
|
|
(0, _util.assert)(numLower.dtype === "int32", ()=>`bandPart(): numLower's dtype must be an int32.`);
|
|
// If numLower is a Scalar, checking `numLower <= M` could hurt performance,
|
|
// but minimum(numLower, M) could avoid unexpected results.
|
|
$numLower = (0, _where.where)((0, _less.less)(numLower, 0), M, (0, _minimum.minimum)(numLower, M));
|
|
}
|
|
if (typeof numUpper === "number") {
|
|
(0, _util.assert)(numUpper % 1 === 0, ()=>`bandPart(): numUpper must be an integer, got ${numUpper}.`);
|
|
(0, _util.assert)(numUpper <= N, ()=>`bandPart(): numUpper (${numUpper})` + ` must not be greater than the number of columns (${N}).`);
|
|
$numUpper = (0, _tensorUtilEnv.convertToTensor)(numUpper < 0 ? N : numUpper, "numUpper", "bandPart");
|
|
} else {
|
|
(0, _util.assert)(numUpper.dtype === "int32", ()=>`bandPart(): numUpper's dtype must be an int32.`);
|
|
$numUpper = (0, _where.where)((0, _less.less)(numUpper, 0), N, (0, _minimum.minimum)(numUpper, N));
|
|
}
|
|
const i = (0, _reshape.reshape)((0, _range.range)(0, M, 1, "int32"), [
|
|
-1,
|
|
1
|
|
]);
|
|
const j = (0, _range.range)(0, N, 1, "int32");
|
|
const ij = (0, _sub.sub)(i, j);
|
|
const inBand = (0, _logicalAnd.logicalAnd)((0, _lessEqual.lessEqual)(ij, $numLower), (0, _greaterEqual.greaterEqual)(ij, (0, _neg.neg)($numUpper)));
|
|
const zero = (0, _zeros.zeros)([
|
|
M,
|
|
N
|
|
], $a.dtype);
|
|
return (0, _reshape.reshape)((0, _stack.stack)((0, _unstack.unstack)((0, _reshape.reshape)($a, [
|
|
-1,
|
|
M,
|
|
N
|
|
])).map((mat)=>(0, _where.where)(inBand, mat, zero))), shape);
|
|
}
|
|
const bandPart = /* @__PURE__ */ (0, _operation.op)({
|
|
bandPart_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../greater_equal":"f7S2c","../less":"hCGN5","../less_equal":"j9Jhy","../logical_and":"6zYjJ","../minimum":"guwat","../neg":"3jQfI","../operation":"ip64W","../range":"3seHd","../reshape":"ew3wZ","../stack":"jeh7M","../sub":"jBBQ2","../unstack":"90Kbb","../where":"47cKc","../zeros":"fcPHR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dmmpK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gramSchmidt", ()=>gramSchmidt);
|
|
var _engine = require("../../engine");
|
|
var _util = require("../../util");
|
|
var _div = require("../div");
|
|
var _mul = require("../mul");
|
|
var _norm = require("../norm");
|
|
var _operation = require("../operation");
|
|
var _split = require("../split");
|
|
var _squeeze = require("../squeeze");
|
|
var _stack = require("../stack");
|
|
var _sub = require("../sub");
|
|
var _sum = require("../sum");
|
|
/**
|
|
* Gram-Schmidt orthogonalization.
|
|
*
|
|
* ```js
|
|
* const x = tf.tensor2d([[1, 2], [3, 4]]);
|
|
* let y = tf.linalg.gramSchmidt(x);
|
|
* y.print();
|
|
* console.log('Orthogonalized:');
|
|
* 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;
|
|
(0, _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)(0, _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 = (0, _split.split)(xs, xs.shape[0], 0).map((x)=>(0, _squeeze.squeeze)(x, [
|
|
0
|
|
]));
|
|
}
|
|
(0, _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((0, _engine.ENGINE).tidy(()=>{
|
|
let x = xs1d[i];
|
|
if (i > 0) for(let j = 0; j < i; ++j){
|
|
const proj = (0, _mul.mul)((0, _sum.sum)((0, _mul.mul)(ys[j], x)), ys[j]);
|
|
x = (0, _sub.sub)(x, proj);
|
|
}
|
|
return (0, _div.div)(x, (0, _norm.norm)(x, "euclidean"));
|
|
}));
|
|
if (inputIsTensor2D) return (0, _stack.stack)(ys, 0);
|
|
else return ys;
|
|
}
|
|
const gramSchmidt = /* @__PURE__ */ (0, _operation.op)({
|
|
gramSchmidt_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../util":"ctavo","../div":"5ZT1h","../mul":"fOWrC","../norm":"eOnCA","../operation":"ip64W","../split":"l0HF2","../squeeze":"VbY6Z","../stack":"jeh7M","../sub":"jBBQ2","../sum":"5awd0","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dhxAc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "qr", ()=>qr);
|
|
var _engine = require("../../engine");
|
|
var _globals = require("../../globals");
|
|
var _util = require("../../util");
|
|
var _clone = require("../clone");
|
|
var _concat = require("../concat");
|
|
var _div = require("../div");
|
|
var _eye = require("../eye");
|
|
var _greater = require("../greater");
|
|
var _matMul = require("../mat_mul");
|
|
var _mul = require("../mul");
|
|
var _neg = require("../neg");
|
|
var _norm = require("../norm");
|
|
var _operation = require("../operation");
|
|
var _reshape = require("../reshape");
|
|
var _slice = require("../slice");
|
|
var _stack = require("../stack");
|
|
var _sub = require("../sub");
|
|
var _tensor2D = require("../tensor2d");
|
|
var _transpose = require("../transpose");
|
|
var _unstack = require("../unstack");
|
|
var _where = require("../where");
|
|
/**
|
|
* 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) {
|
|
(0, _util.assert)(x.rank >= 2, ()=>`qr() requires input tensor to have a rank >= 2, but got rank ${x.rank}`);
|
|
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 = (0, _unstack.unstack)((0, _reshape.reshape)(x, [
|
|
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 = (0, _reshape.reshape)((0, _stack.stack)(q2ds, 0), x.shape);
|
|
const r = (0, _reshape.reshape)((0, _stack.stack)(r2ds, 0), x.shape);
|
|
return [
|
|
q,
|
|
r
|
|
];
|
|
}
|
|
}
|
|
function qr2d(x, fullMatrices = false) {
|
|
return (0, _engine.ENGINE).tidy(()=>{
|
|
(0, _util.assert)(x.shape.length === 2, ()=>`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 = (0, _eye.eye)(m); // Orthogonal transform so far.
|
|
let r = (0, _clone.clone)(x); // Transformed matrix so far.
|
|
const one2D = (0, _tensor2D.tensor2d)([
|
|
[
|
|
1
|
|
]
|
|
], [
|
|
1,
|
|
1
|
|
]);
|
|
let w = (0, _clone.clone)(one2D);
|
|
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] = (0, _engine.ENGINE).tidy(()=>{
|
|
// Find H = I - tau * w * w', to put zeros below R(j, j).
|
|
const rjEnd1 = (0, _slice.slice)(r, [
|
|
j,
|
|
j
|
|
], [
|
|
m - j,
|
|
1
|
|
]);
|
|
const normX = (0, _norm.norm)(rjEnd1);
|
|
const rjj = (0, _slice.slice)(r, [
|
|
j,
|
|
j
|
|
], [
|
|
1,
|
|
1
|
|
]);
|
|
// The sign() function returns 0 on 0, which causes division by zero.
|
|
const s = (0, _where.where)((0, _greater.greater)(rjj, 0), (0, _tensor2D.tensor2d)([
|
|
[
|
|
-1
|
|
]
|
|
]), (0, _tensor2D.tensor2d)([
|
|
[
|
|
1
|
|
]
|
|
]));
|
|
const u1 = (0, _sub.sub)(rjj, (0, _mul.mul)(s, normX));
|
|
const wPre = (0, _div.div)(rjEnd1, u1);
|
|
if (wPre.shape[0] === 1) w = (0, _clone.clone)(one2D);
|
|
else w = (0, _concat.concat)([
|
|
one2D,
|
|
(0, _slice.slice)(wPre, [
|
|
1,
|
|
0
|
|
], [
|
|
wPre.shape[0] - 1,
|
|
wPre.shape[1]
|
|
])
|
|
], 0);
|
|
const tau = (0, _neg.neg)((0, _div.div)((0, _matMul.matMul)(s, u1), normX));
|
|
// -- R := HR, Q := QH.
|
|
const rjEndAll = (0, _slice.slice)(r, [
|
|
j,
|
|
0
|
|
], [
|
|
m - j,
|
|
n
|
|
]);
|
|
const tauTimesW = (0, _mul.mul)(tau, w);
|
|
const wT = (0, _transpose.transpose)(w);
|
|
if (j === 0) r = (0, _sub.sub)(rjEndAll, (0, _matMul.matMul)(tauTimesW, (0, _matMul.matMul)(wT, rjEndAll)));
|
|
else {
|
|
const rTimesTau = (0, _sub.sub)(rjEndAll, (0, _matMul.matMul)(tauTimesW, (0, _matMul.matMul)(wT, rjEndAll)));
|
|
r = (0, _concat.concat)([
|
|
(0, _slice.slice)(r, [
|
|
0,
|
|
0
|
|
], [
|
|
j,
|
|
n
|
|
]),
|
|
rTimesTau
|
|
], 0);
|
|
}
|
|
const tawTimesWT = (0, _transpose.transpose)(tauTimesW);
|
|
const qAllJEnd = (0, _slice.slice)(q, [
|
|
0,
|
|
j
|
|
], [
|
|
m,
|
|
q.shape[1] - j
|
|
]);
|
|
if (j === 0) q = (0, _sub.sub)(qAllJEnd, (0, _matMul.matMul)((0, _matMul.matMul)(qAllJEnd, w), tawTimesWT));
|
|
else {
|
|
const qTimesTau = (0, _sub.sub)(qAllJEnd, (0, _matMul.matMul)((0, _matMul.matMul)(qAllJEnd, w), tawTimesWT));
|
|
q = (0, _concat.concat)([
|
|
(0, _slice.slice)(q, [
|
|
0,
|
|
0
|
|
], [
|
|
m,
|
|
j
|
|
]),
|
|
qTimesTau
|
|
], 1);
|
|
}
|
|
return [
|
|
w,
|
|
r,
|
|
q
|
|
];
|
|
});
|
|
(0, _globals.dispose)([
|
|
rTemp,
|
|
wTemp,
|
|
qTemp
|
|
]);
|
|
}
|
|
if (!fullMatrices && m > n) {
|
|
q = (0, _slice.slice)(q, [
|
|
0,
|
|
0
|
|
], [
|
|
m,
|
|
n
|
|
]);
|
|
r = (0, _slice.slice)(r, [
|
|
0,
|
|
0
|
|
], [
|
|
n,
|
|
n
|
|
]);
|
|
}
|
|
return [
|
|
q,
|
|
r
|
|
];
|
|
});
|
|
}
|
|
const qr = /* @__PURE__ */ (0, _operation.op)({
|
|
qr_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../globals":"eO1Ja","../../util":"ctavo","../clone":"jmQ7S","../concat":"1NOyL","../div":"5ZT1h","../eye":"hDQ1U","../greater":"3Nh8O","../mat_mul":"fiMp4","../mul":"fOWrC","../neg":"3jQfI","../norm":"eOnCA","../operation":"ip64W","../reshape":"ew3wZ","../slice":"dr7Gq","../stack":"jeh7M","../sub":"jBBQ2","../tensor2d":"faX5H","../transpose":"2bqbS","../unstack":"90Kbb","../where":"47cKc","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5sJon":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "absoluteDifference", ()=>absoluteDifference);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _abs = require("../abs");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _operation = require("../operation");
|
|
var _sub = require("../sub");
|
|
var _computeWeightedLoss = require("./compute_weighted_loss");
|
|
/**
|
|
* 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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
const $labels = (0, _tensorUtilEnv.convertToTensor)(labels, "labels", "absoluteDifference");
|
|
const $predictions = (0, _tensorUtilEnv.convertToTensor)(predictions, "predictions", "absoluteDifference");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "absoluteDifference");
|
|
(0, _util.assertShapesMatch)($labels.shape, $predictions.shape, "Error in absoluteDifference: ");
|
|
const losses = (0, _abs.abs)((0, _sub.sub)($labels, $predictions));
|
|
return (0, _computeWeightedLoss.computeWeightedLoss)(losses, $weights, reduction);
|
|
}
|
|
const absoluteDifference = /* @__PURE__ */ (0, _operation.op)({
|
|
absoluteDifference_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../abs":"iZQ4e","../loss_ops_utils":"6wY9M","../operation":"ip64W","../sub":"jBBQ2","./compute_weighted_loss":"1agzr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6wY9M":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Reduction", ()=>Reduction);
|
|
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 = {}));
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1agzr":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "computeWeightedLoss", ()=>computeWeightedLoss);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _cast = require("../cast");
|
|
var _div = require("../div");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _mean = require("../mean");
|
|
var _mul = require("../mul");
|
|
var _notEqual = require("../not_equal");
|
|
var _ones = require("../ones");
|
|
var _operation = require("../operation");
|
|
var _scalar = require("../scalar");
|
|
var _sum = require("../sum");
|
|
/**
|
|
* 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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
const $losses = (0, _tensorUtilEnv.convertToTensor)(losses, "losses", "computeWeightedLoss");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "computeWeightedLoss");
|
|
const weightedLoss = $weights == null ? $losses : (0, _mul.mul)($losses, $weights);
|
|
if (reduction === (0, _lossOpsUtils.Reduction).NONE) return weightedLoss;
|
|
if (reduction === (0, _lossOpsUtils.Reduction).SUM) return (0, _sum.sum)(weightedLoss);
|
|
if (reduction === (0, _lossOpsUtils.Reduction).MEAN) {
|
|
if ($weights == null) return (0, _mean.mean)(weightedLoss);
|
|
else {
|
|
const broadcastFactor = $losses.size / $weights.size;
|
|
const result = (0, _div.div)((0, _sum.sum)(weightedLoss), (0, _sum.sum)($weights));
|
|
return broadcastFactor > 1 ? (0, _div.div)(result, (0, _scalar.scalar)(broadcastFactor)) : result;
|
|
}
|
|
}
|
|
if (reduction === (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
if ($weights == null) return (0, _div.div)((0, _sum.sum)(weightedLoss), (0, _scalar.scalar)($losses.size));
|
|
else {
|
|
const broadcastedWeights = (0, _mul.mul)($weights, (0, _ones.ones)($losses.shape));
|
|
const numNonZeros = (0, _cast.cast)((0, _sum.sum)((0, _notEqual.notEqual)(broadcastedWeights, (0, _scalar.scalar)(0))), "float32");
|
|
return (0, _div.div)((0, _sum.sum)(weightedLoss), numNonZeros);
|
|
}
|
|
}
|
|
throw Error(`Unknown reduction: ${reduction}`);
|
|
}
|
|
const computeWeightedLoss = /* @__PURE__ */ (0, _operation.op)({
|
|
computeWeightedLoss_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../cast":"b4VDA","../div":"5ZT1h","../loss_ops_utils":"6wY9M","../mean":"hzzLs","../mul":"fOWrC","../not_equal":"gUKb0","../ones":"2gdnE","../operation":"ip64W","../scalar":"7lhC8","../sum":"5awd0","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"enn6x":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cosineDistance", ()=>cosineDistance);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _mul = require("../mul");
|
|
var _operation = require("../operation");
|
|
var _scalar = require("../scalar");
|
|
var _sub = require("../sub");
|
|
var _sum = require("../sum");
|
|
var _computeWeightedLoss = require("./compute_weighted_loss");
|
|
/**
|
|
* 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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
const $labels = (0, _tensorUtilEnv.convertToTensor)(labels, "labels", "cosineDistance");
|
|
const $predictions = (0, _tensorUtilEnv.convertToTensor)(predictions, "predictions", "cosineDistance");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "cosineDistance");
|
|
(0, _util.assertShapesMatch)($labels.shape, $predictions.shape, "Error in cosineDistance: ");
|
|
const one = (0, _scalar.scalar)(1);
|
|
const losses = (0, _sub.sub)(one, (0, _sum.sum)((0, _mul.mul)($labels, $predictions), axis, true));
|
|
return (0, _computeWeightedLoss.computeWeightedLoss)(losses, $weights, reduction);
|
|
}
|
|
const cosineDistance = /* @__PURE__ */ (0, _operation.op)({
|
|
cosineDistance_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../loss_ops_utils":"6wY9M","../mul":"fOWrC","../operation":"ip64W","../scalar":"7lhC8","../sub":"jBBQ2","../sum":"5awd0","./compute_weighted_loss":"1agzr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1aaXc":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "hingeLoss", ()=>hingeLoss);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _mul = require("../mul");
|
|
var _operation = require("../operation");
|
|
var _relu = require("../relu");
|
|
var _scalar = require("../scalar");
|
|
var _sub = require("../sub");
|
|
var _computeWeightedLoss = require("./compute_weighted_loss");
|
|
/**
|
|
* 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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
let $labels = (0, _tensorUtilEnv.convertToTensor)(labels, "labels", "hingeLoss");
|
|
const $predictions = (0, _tensorUtilEnv.convertToTensor)(predictions, "predictions", "hingeLoss");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "hingeLoss");
|
|
(0, _util.assertShapesMatch)($labels.shape, $predictions.shape, "Error in hingeLoss: ");
|
|
const one = (0, _scalar.scalar)(1);
|
|
// Convert binary labels to (-1, 1)
|
|
$labels = (0, _sub.sub)((0, _mul.mul)((0, _scalar.scalar)(2), $labels), one);
|
|
const losses = (0, _relu.relu)((0, _sub.sub)(one, (0, _mul.mul)($labels, $predictions)));
|
|
return (0, _computeWeightedLoss.computeWeightedLoss)(losses, $weights, reduction);
|
|
}
|
|
const hingeLoss = /* @__PURE__ */ (0, _operation.op)({
|
|
hingeLoss_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../loss_ops_utils":"6wY9M","../mul":"fOWrC","../operation":"ip64W","../relu":"lcv3E","../scalar":"7lhC8","../sub":"jBBQ2","./compute_weighted_loss":"1agzr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1c06w":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "huberLoss", ()=>huberLoss);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _abs = require("../abs");
|
|
var _add = require("../add");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _minimum = require("../minimum");
|
|
var _mul = require("../mul");
|
|
var _operation = require("../operation");
|
|
var _scalar = require("../scalar");
|
|
var _square = require("../square");
|
|
var _sub = require("../sub");
|
|
var _computeWeightedLoss = require("./compute_weighted_loss");
|
|
/**
|
|
* 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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
const $labels = (0, _tensorUtilEnv.convertToTensor)(labels, "labels", "huberLoss");
|
|
const $predictions = (0, _tensorUtilEnv.convertToTensor)(predictions, "predictions", "huberLoss");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "huberLoss");
|
|
(0, _util.assertShapesMatch)($labels.shape, $predictions.shape, "Error in huberLoss: ");
|
|
const deltaScalar = (0, _scalar.scalar)(delta);
|
|
const error = (0, _abs.abs)((0, _sub.sub)($predictions, $labels));
|
|
const quadratic = (0, _minimum.minimum)(error, deltaScalar);
|
|
const linear = (0, _sub.sub)(error, quadratic);
|
|
const losses = (0, _add.add)((0, _mul.mul)((0, _scalar.scalar)(0.5), (0, _square.square)(quadratic)), (0, _mul.mul)(deltaScalar, linear));
|
|
return (0, _computeWeightedLoss.computeWeightedLoss)(losses, $weights, reduction);
|
|
}
|
|
const huberLoss = /* @__PURE__ */ (0, _operation.op)({
|
|
huberLoss_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../abs":"iZQ4e","../add":"aynh7","../loss_ops_utils":"6wY9M","../minimum":"guwat","../mul":"fOWrC","../operation":"ip64W","../scalar":"7lhC8","../square":"cOosW","../sub":"jBBQ2","./compute_weighted_loss":"1agzr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"UdKNC":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logLoss", ()=>logLoss);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _add = require("../add");
|
|
var _log = require("../log");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _mul = require("../mul");
|
|
var _neg = require("../neg");
|
|
var _operation = require("../operation");
|
|
var _scalar = require("../scalar");
|
|
var _sub = require("../sub");
|
|
var _computeWeightedLoss = require("./compute_weighted_loss");
|
|
/**
|
|
* 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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
const $labels = (0, _tensorUtilEnv.convertToTensor)(labels, "labels", "logLoss");
|
|
const $predictions = (0, _tensorUtilEnv.convertToTensor)(predictions, "predictions", "logLoss");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "logLoss");
|
|
(0, _util.assertShapesMatch)($labels.shape, $predictions.shape, "Error in logLoss: ");
|
|
const one = (0, _scalar.scalar)(1);
|
|
const epsilonScalar = (0, _scalar.scalar)(epsilon);
|
|
const l1 = (0, _neg.neg)((0, _mul.mul)($labels, (0, _log.log)((0, _add.add)($predictions, epsilonScalar))));
|
|
const l2 = (0, _mul.mul)((0, _sub.sub)(one, $labels), (0, _log.log)((0, _add.add)((0, _sub.sub)(one, $predictions), epsilonScalar)));
|
|
const losses = (0, _sub.sub)(l1, l2);
|
|
return (0, _computeWeightedLoss.computeWeightedLoss)(losses, $weights, reduction);
|
|
}
|
|
const logLoss = /* @__PURE__ */ (0, _operation.op)({
|
|
logLoss_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../add":"aynh7","../log":"iex5O","../loss_ops_utils":"6wY9M","../mul":"fOWrC","../neg":"3jQfI","../operation":"ip64W","../scalar":"7lhC8","../sub":"jBBQ2","./compute_weighted_loss":"1agzr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8Mugj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "meanSquaredError", ()=>meanSquaredError);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _operation = require("../operation");
|
|
var _squaredDifference = require("../squared_difference");
|
|
var _computeWeightedLoss = require("./compute_weighted_loss");
|
|
/**
|
|
* 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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
const $labels = (0, _tensorUtilEnv.convertToTensor)(labels, "labels", "meanSquaredError");
|
|
const $predictions = (0, _tensorUtilEnv.convertToTensor)(predictions, "predictions", "meanSquaredError");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "meanSquaredError");
|
|
(0, _util.assertShapesMatch)($labels.shape, $predictions.shape, "Error in meanSquaredError: ");
|
|
const losses = (0, _squaredDifference.squaredDifference)($labels, $predictions);
|
|
return (0, _computeWeightedLoss.computeWeightedLoss)(losses, $weights, reduction);
|
|
}
|
|
const meanSquaredError = /* @__PURE__ */ (0, _operation.op)({
|
|
meanSquaredError_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../loss_ops_utils":"6wY9M","../operation":"ip64W","../squared_difference":"iHBgt","./compute_weighted_loss":"1agzr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"77Q3C":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sigmoidCrossEntropy", ()=>sigmoidCrossEntropy);
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _abs = require("../abs");
|
|
var _add = require("../add");
|
|
var _exp = require("../exp");
|
|
var _log1P = require("../log1p");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _mul = require("../mul");
|
|
var _neg = require("../neg");
|
|
var _operation = require("../operation");
|
|
var _relu = require("../relu");
|
|
var _scalar = require("../scalar");
|
|
var _sub = require("../sub");
|
|
var _computeWeightedLoss = require("./compute_weighted_loss");
|
|
function sigmoidCrossEntropyWithLogits_(labels, logits) {
|
|
const $labels = (0, _tensorUtilEnv.convertToTensor)(labels, "labels", "sigmoidCrossEntropyWithLogits");
|
|
const $logits = (0, _tensorUtilEnv.convertToTensor)(logits, "logits", "sigmoidCrossEntropyWithLogits");
|
|
(0, _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 = (0, _relu.relu)($logits);
|
|
const outputXTarget = (0, _mul.mul)($logits, $labels);
|
|
const sigmoidOutput = (0, _log1P.log1p)((0, _exp.exp)((0, _neg.neg)((0, _abs.abs)($logits))));
|
|
return (0, _add.add)((0, _sub.sub)(maxOutput, outputXTarget), 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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
let $multiClassLabels = (0, _tensorUtilEnv.convertToTensor)(multiClassLabels, "multiClassLabels", "sigmoidCrossEntropy");
|
|
const $logits = (0, _tensorUtilEnv.convertToTensor)(logits, "logits", "sigmoidCrossEntropy");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "sigmoidCrossEntropy");
|
|
(0, _util.assertShapesMatch)($multiClassLabels.shape, $logits.shape, "Error in sigmoidCrossEntropy: ");
|
|
if (labelSmoothing > 0) {
|
|
const labelSmoothingScalar = (0, _scalar.scalar)(labelSmoothing);
|
|
const one = (0, _scalar.scalar)(1);
|
|
const half = (0, _scalar.scalar)(0.5);
|
|
$multiClassLabels = (0, _add.add)((0, _mul.mul)($multiClassLabels, (0, _sub.sub)(one, labelSmoothingScalar)), (0, _mul.mul)(half, labelSmoothingScalar));
|
|
}
|
|
const losses = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);
|
|
return (0, _computeWeightedLoss.computeWeightedLoss)(losses, $weights, reduction);
|
|
}
|
|
const sigmoidCrossEntropy = /* @__PURE__ */ (0, _operation.op)({
|
|
sigmoidCrossEntropy_
|
|
});
|
|
|
|
},{"../../tensor_util_env":"6vfHI","../../util":"ctavo","../abs":"iZQ4e","../add":"aynh7","../exp":"1CsGu","../log1p":"jKhH4","../loss_ops_utils":"6wY9M","../mul":"fOWrC","../neg":"3jQfI","../operation":"ip64W","../relu":"lcv3E","../scalar":"7lhC8","../sub":"jBBQ2","./compute_weighted_loss":"1agzr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cGUog":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "softmaxCrossEntropy", ()=>softmaxCrossEntropy);
|
|
var _gradients = require("../../gradients");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _util = require("../../util");
|
|
var _add = require("../add");
|
|
var _axisUtil = require("../axis_util");
|
|
var _cast = require("../cast");
|
|
var _div = require("../div");
|
|
var _exp = require("../exp");
|
|
var _logSumExp = require("../log_sum_exp");
|
|
var _lossOpsUtils = require("../loss_ops_utils");
|
|
var _mul = require("../mul");
|
|
var _neg = require("../neg");
|
|
var _operation = require("../operation");
|
|
var _reshape = require("../reshape");
|
|
var _scalar = require("../scalar");
|
|
var _sub = require("../sub");
|
|
var _sum = require("../sum");
|
|
var _computeWeightedLoss = require("./compute_weighted_loss");
|
|
/**
|
|
* 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 = (0, _gradients.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 = (0, _logSumExp.logSumExp)(logits, [
|
|
dim
|
|
], keepDims);
|
|
const logResult = (0, _sub.sub)((0, _cast.cast)(logits, "float32"), lse);
|
|
save([
|
|
labels,
|
|
logResult
|
|
]);
|
|
const costVector = (0, _neg.neg)((0, _mul.mul)(logResult, labels));
|
|
const value = (0, _sum.sum)(costVector, [
|
|
dim
|
|
]);
|
|
const gradFunc = (dy, saved)=>{
|
|
const [labels, logResult] = saved;
|
|
const dyShape = (0, _axisUtil.expandShapeToKeepDim)(dy.shape, [
|
|
dim
|
|
]);
|
|
return [
|
|
(0, _mul.mul)((0, _reshape.reshape)(dy, dyShape), (0, _sub.sub)((0, _cast.cast)(labels, "float32"), (0, _exp.exp)(logResult))),
|
|
(0, _mul.mul)((0, _reshape.reshape)(dy, dyShape), (0, _sub.sub)((0, _exp.exp)(logResult), (0, _cast.cast)(labels, "float32")))
|
|
];
|
|
};
|
|
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 = (0, _lossOpsUtils.Reduction).SUM_BY_NONZERO_WEIGHTS) {
|
|
let $onehotLabels = (0, _tensorUtilEnv.convertToTensor)(onehotLabels, "onehotLabels", "softmaxCrossEntropy");
|
|
const $logits = (0, _tensorUtilEnv.convertToTensor)(logits, "logits", "softmaxCrossEntropy");
|
|
let $weights = null;
|
|
if (weights != null) $weights = (0, _tensorUtilEnv.convertToTensor)(weights, "weights", "softmaxCrossEntropy");
|
|
(0, _util.assertShapesMatch)($onehotLabels.shape, $logits.shape, "Error in softmaxCrossEntropy: ");
|
|
if (labelSmoothing > 0) {
|
|
const labelSmoothingScalar = (0, _scalar.scalar)(labelSmoothing);
|
|
const one = (0, _scalar.scalar)(1);
|
|
const numClasses = (0, _scalar.scalar)($onehotLabels.shape[1]);
|
|
$onehotLabels = (0, _add.add)((0, _mul.mul)($onehotLabels, (0, _sub.sub)(one, labelSmoothingScalar)), (0, _div.div)(labelSmoothingScalar, numClasses));
|
|
}
|
|
const losses = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);
|
|
return (0, _computeWeightedLoss.computeWeightedLoss)(losses, $weights, reduction);
|
|
}
|
|
const softmaxCrossEntropy = /* @__PURE__ */ (0, _operation.op)({
|
|
softmaxCrossEntropy_
|
|
});
|
|
|
|
},{"../../gradients":"dDHpg","../../tensor_util_env":"6vfHI","../../util":"ctavo","../add":"aynh7","../axis_util":"hzS4B","../cast":"b4VDA","../div":"5ZT1h","../exp":"1CsGu","../log_sum_exp":"feRCM","../loss_ops_utils":"6wY9M","../mul":"fOWrC","../neg":"3jQfI","../operation":"ip64W","../reshape":"ew3wZ","../scalar":"7lhC8","../sub":"jBBQ2","../sum":"5awd0","./compute_weighted_loss":"1agzr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1MyfF":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseFillEmptyRows", ()=>sparseFillEmptyRows);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* The input SparseTensor is represented via the map of inputs {`indices`,
|
|
* `values`, `denseShape`}. The output SparseTensor has the same `denseShape`
|
|
* but with indices `outputIndices` and values `outputValues`. This op inserts a
|
|
* single entry for every row that doesn't have any values. The index is created
|
|
* as `[row, 0, ..., 0]` and the inserted value is `defaultValue`.
|
|
*
|
|
* For example, suppose `spInput` has shape [5, 6] and non-empty values:
|
|
* [0, 1]: a
|
|
* [0, 3]: b
|
|
* [2, 0]: c
|
|
* [3, 1]: d
|
|
*
|
|
* Rows 1 and 4 are empty, so the output will be of shape [5, 6] with values:
|
|
* [0, 1]: a
|
|
* [0, 3]: b
|
|
* [1, 0]: `defaultValue`
|
|
* [2, 0]: c
|
|
* [3, 1]: d
|
|
* [4, 0]: `defaultValue`
|
|
*
|
|
* The output SparseTensor will be in row-major order and will have the same
|
|
* shape as the input.
|
|
*
|
|
* This op also returns an indicator vector shaped [dense_shape[0]] such that
|
|
* emptyRowIndicator[i] = True iff row i was an empty row.
|
|
*
|
|
* And a reverse index map vector shaped [indices.shape[0]] that is used during
|
|
* backpropagation, reverseIndexMap[i] = outi s.t. indices[i, j] ==
|
|
* outputIndices[outi, j] for all j
|
|
*
|
|
* ```js
|
|
* const result = tf.sparse.sparseFillEmptyRows(
|
|
* [[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]],
|
|
* [0, 10, 13, 14, 32, 33], [5, 6], -1);
|
|
* console.log(result);
|
|
* result['outputIndices'].print(); // [[0, 0], [1, 0], [1, 3], [1, 4],
|
|
* // [2, 0], [3, 2], [3, 3], [4, 0]]
|
|
* result['outputValues'].print(); // [0, 10, 13, 14,-1, 32, 33, -1]
|
|
* result['emptyRowIndicator'].print(); // [false, false, true, false, true]
|
|
* result['reverseIndexMap'].print(); // [0, 1, 2, 3, 5, 6]
|
|
* ```
|
|
* @param indices: 2-D. The indices of the sparse tensor.
|
|
* @param values: 1-D. The values of the sparse tensor.
|
|
* @param denseShape: 1-D. The shape of the sparse tensor.
|
|
* @param defaultValue: 0-D. Default value to insert into location [row, 0, ...,
|
|
* 0] for rows missing from the input sparse tensor.
|
|
* @return A map with the following properties:
|
|
* - outputIndices
|
|
* - outputValues: 1-D. The values of the filled sparse tensor.
|
|
* - emptyRowIndicator: 1-D. Whether the dense row was missing in the input
|
|
* sparse tensor.
|
|
* - reverseIndexMap: 1-D. A map from the input indices to the output
|
|
* indices.
|
|
* @doc {heading: 'Operations', subheading: 'Sparse'}
|
|
*/ function sparseFillEmptyRows_(indices, values, denseShape, defaultValue) {
|
|
const $indices = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "sparseFillEmptyRows", "int32");
|
|
const $values = (0, _tensorUtilEnv.convertToTensor)(values, "values", "sparseFillEmptyRows");
|
|
const $denseShape = (0, _tensorUtilEnv.convertToTensor)(denseShape, "denseShape", "sparseFillEmptyRows", "int32");
|
|
const $defaultValue = (0, _tensorUtilEnv.convertToTensor)(defaultValue, "defaultValue", "sparseFillEmptyRows", $values.dtype);
|
|
if ($indices.rank !== 2) throw new Error(`Indices should be Tensor2D but received shape
|
|
${$indices.shape}`);
|
|
if ($values.rank !== 1) throw new Error(`Values should be Tensor1D but received shape ${$values.shape}`);
|
|
if ($denseShape.rank !== 1) throw new Error(`Dense shape should be Tensor1D but received shape ${$denseShape.shape}`);
|
|
if ($defaultValue.rank !== 0) throw new Error(`Default value should be a scalar but received shape ${$defaultValue.shape}`);
|
|
const inputs = {
|
|
indices: $indices,
|
|
values: $values,
|
|
denseShape: $denseShape,
|
|
defaultValue: $defaultValue
|
|
};
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.SparseFillEmptyRows), inputs);
|
|
return {
|
|
outputIndices: result[0],
|
|
outputValues: result[1],
|
|
emptyRowIndicator: result[2],
|
|
reverseIndexMap: result[3]
|
|
};
|
|
}
|
|
const sparseFillEmptyRows = /* @__PURE__ */ (0, _operation.op)({
|
|
sparseFillEmptyRows_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"f6fUL":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseReshape", ()=>sparseReshape);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* This operation has the same semantics as reshape on the represented dense
|
|
* tensor. The `inputIndices` are recomputed based on the requested `newShape`.
|
|
* If one component of `newShape` is the special value -1, the size of that
|
|
* dimension is computed so that the total dense size remains constant. At most
|
|
* one component of `newShape` can be -1. The number of dense elements implied
|
|
* by `newShape` must be the same as the number of dense elements originally
|
|
* implied by `inputShape`. Reshaping does not affect the order of values in the
|
|
* SparseTensor. If the input tensor has rank R_in and N non-empty values, and
|
|
* `newShape` has length R_out, then `inputIndices` has shape [N, R_in],
|
|
* `inputShape` has length R_in, `outputIndices` has shape [N, R_out], and
|
|
* `outputShape` has length R_out.
|
|
*
|
|
* ```js
|
|
* const result = tf.sparse.sparseReshape(
|
|
* [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]],
|
|
* [2, 3, 6], [9, -1]);
|
|
* console.log(result);
|
|
* result['outputIndices'].print(); //[[0, 0], [0, 1], [1, 2], [4, 2], [8, 1]]
|
|
* result['outputShape'].print(); // [9, 4]
|
|
* ```
|
|
* @param inputIndices: 2-D. N x R_in matrix with the indices of non-empty
|
|
* values in a SparseTensor.
|
|
* @param inputShape: 1-D. R_in Tensor1D with the input SparseTensor's dense
|
|
* shape.
|
|
* @param newShape: 1-D. R_out Tensor1D with the requested new dense shape.
|
|
* @return A map with the following properties:
|
|
* - outputIndices: 2-D. N x R_out matrix with the updated indices of
|
|
* non-empty values in the output SparseTensor.
|
|
* - outputShape: 1-D. R_out vector with the full dense shape of the output
|
|
* SparseTensor. This is the same as newShape but with any -1 dimensions
|
|
* filled in.
|
|
* @doc {heading: 'Operations', subheading: 'Sparse'}
|
|
*/ function sparseReshape_(inputIndices, inputShape, newShape) {
|
|
const $inputIndices = (0, _tensorUtilEnv.convertToTensor)(inputIndices, "inputIndices", "sparseReshape", "int32");
|
|
const $inputShape = (0, _tensorUtilEnv.convertToTensor)(inputShape, "inputShape", "sparseReshape", "int32");
|
|
const $newShape = (0, _tensorUtilEnv.convertToTensor)(newShape, "newShape", "sparseReshape", "int32");
|
|
if ($inputIndices.rank !== 2) throw new Error(`Input indices should be Tensor2D but received shape
|
|
${$inputIndices.shape}`);
|
|
if ($inputShape.rank !== 1) throw new Error(`Input shape should be Tensor1D but received shape ${$inputShape.shape}`);
|
|
if ($newShape.rank !== 1) throw new Error(`New shape should be Tensor1D but received shape ${$newShape.shape}`);
|
|
const inputs = {
|
|
inputIndices: $inputIndices,
|
|
inputShape: $inputShape,
|
|
newShape: $newShape
|
|
};
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.SparseReshape), inputs);
|
|
return {
|
|
outputIndices: result[0],
|
|
outputShape: result[1]
|
|
};
|
|
}
|
|
const sparseReshape = /* @__PURE__ */ (0, _operation.op)({
|
|
sparseReshape_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"d0IYG":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseSegmentMean", ()=>sparseSegmentMean);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Computes the mean along sparse segments of a tensor.
|
|
*
|
|
* ```js
|
|
* const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [6,7,8,9]]);
|
|
* // Select two rows, one segment.
|
|
* const result1 = tf.sparse.sparseSegmentMean(c,
|
|
* tf.tensor1d([0, 1], 'int32'),
|
|
* tf.tensor1d([0, 0], 'int32'));
|
|
* result1.print(); // [[0, 0, 0, 0]]
|
|
*
|
|
* // Select two rows, two segments.
|
|
* const result2 = tf.sparse.sparseSegmentMean(c,
|
|
* tf.tensor1d([0, 1], 'int32'),
|
|
* tf.tensor1d([0, 1], 'int32'));
|
|
* result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]
|
|
*
|
|
* // Select all rows, two segments.
|
|
* const result3 = tf.sparse.sparseSegmentMean(c,
|
|
* tf.tensor1d([0, 1, 2], 'int32'),
|
|
* tf.tensor1d([0, 1, 1], 'int32'));
|
|
* result3.print(); // [[1.0, 2.0, 3.0, 4.0], [2.5, 2.5, 2.5, 2.5]]
|
|
* ```
|
|
* @param data: A Tensor of at least one dimension with data that will be
|
|
* assembled in the output.
|
|
* @param indices: A 1-D Tensor with indices into data. Has same rank as
|
|
* segmentIds.
|
|
* @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values
|
|
* should be sorted and can be repeated.
|
|
* @return Has same shape as data, except for dimension 0 which has equal to
|
|
* the number of segments.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Sparse'}
|
|
*/ function sparseSegmentMean_(data, indices, segmentIds) {
|
|
const $data = (0, _tensorUtilEnv.convertToTensor)(data, "data", "sparseSegmentMean");
|
|
const $indices = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "sparseSegmentMean", "int32");
|
|
const $segmentIds = (0, _tensorUtilEnv.convertToTensor)(segmentIds, "segmentIds", "sparseSegmentMean", "int32");
|
|
if ($data.rank < 1) throw new Error(`Data should be at least 1 dimensional but received scalar`);
|
|
if ($indices.rank !== 1) throw new Error(`Indices should be Tensor1D but received shape
|
|
${$indices.shape}`);
|
|
if ($segmentIds.rank !== 1) throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${$segmentIds.shape}`);
|
|
const inputs = {
|
|
data: $data,
|
|
indices: $indices,
|
|
segmentIds: $segmentIds
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.SparseSegmentMean), inputs);
|
|
}
|
|
const sparseSegmentMean = /* @__PURE__ */ (0, _operation.op)({
|
|
sparseSegmentMean_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7MtJg":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseSegmentSum", ()=>sparseSegmentSum);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Computes the sum along sparse segments of a tensor.
|
|
*
|
|
* ```js
|
|
* const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]);
|
|
* // Select two rows, one segment.
|
|
* const result1 = tf.sparse.sparseSegmentSum(c,
|
|
* tf.tensor1d([0, 1], 'int32'),
|
|
* tf.tensor1d([0, 0], 'int32'));
|
|
* result1.print(); // [[0, 0, 0, 0]]
|
|
*
|
|
* // Select two rows, two segments.
|
|
* const result2 = tf.sparse.sparseSegmentSum(c,
|
|
* tf.tensor1d([0, 1], 'int32'),
|
|
* tf.tensor1d([0, 1], 'int32'));
|
|
* result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]
|
|
*
|
|
* // Select all rows, two segments.
|
|
* const result3 = tf.sparse.sparseSegmentSum(c,
|
|
* tf.tensor1d([0, 1, 2], 'int32'),
|
|
* tf.tensor1d([0, 0, 1], 'int32'));
|
|
* result3.print(); // [[0, 0, 0, 0], [5, 6, 7, 8]]
|
|
* ```
|
|
* @param data: A Tensor of at least one dimension with data that will be
|
|
* assembled in the output.
|
|
* @param indices: A 1-D Tensor with indices into data. Has same rank as
|
|
* segmentIds.
|
|
* @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values
|
|
* should be sorted and can be repeated.
|
|
* @return Has same shape as data, except for dimension 0 which has equal to
|
|
* the number of segments.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'Sparse'}
|
|
*/ function sparseSegmentSum_(data, indices, segmentIds) {
|
|
const $data = (0, _tensorUtilEnv.convertToTensor)(data, "data", "sparseSegmentSum");
|
|
const $indices = (0, _tensorUtilEnv.convertToTensor)(indices, "indices", "sparseSegmentSum", "int32");
|
|
const $segmentIds = (0, _tensorUtilEnv.convertToTensor)(segmentIds, "segmentIds", "sparseSegmentSum", "int32");
|
|
if ($data.rank < 1) throw new Error(`Data should be at least 1 dimensional but received scalar`);
|
|
if ($indices.rank !== 1) throw new Error(`Indices should be Tensor1D but received shape
|
|
${$indices.shape}`);
|
|
if ($segmentIds.rank !== 1) throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${$segmentIds.shape}`);
|
|
const inputs = {
|
|
data: $data,
|
|
indices: $indices,
|
|
segmentIds: $segmentIds
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.SparseSegmentSum), inputs);
|
|
}
|
|
const sparseSegmentSum = /* @__PURE__ */ (0, _operation.op)({
|
|
sparseSegmentSum_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gELNE":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringNGrams", ()=>stringNGrams);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Creates ngrams from ragged string data.
|
|
*
|
|
* This op accepts a ragged tensor with 1 ragged dimension containing only
|
|
* strings and outputs a ragged tensor with 1 ragged dimension containing ngrams
|
|
* of that string, joined along the innermost axis.
|
|
*
|
|
* ```js
|
|
* const result = tf.string.stringNGrams(
|
|
* ['a', 'b', 'c', 'd'], tf.tensor1d([0, 2, 4], 'int32'),
|
|
* '|', [1, 2], 'LP', 'RP', -1, false);
|
|
* result['nGrams'].print(); // ['a', 'b', 'LP|a', 'a|b', 'b|RP',
|
|
* // 'c', 'd', 'LP|c', 'c|d', 'd|RP']
|
|
* result['nGramsSplits'].print(); // [0, 5, 10]
|
|
* ```
|
|
* @param data: The values tensor of the ragged string tensor to make ngrams out
|
|
* of. Must be a 1D string tensor.
|
|
* @param dataSplits: The splits tensor of the ragged string tensor to make
|
|
* ngrams out of.
|
|
* @param separator: The string to append between elements of the token. Use ""
|
|
* for no separator.
|
|
* @param nGramWidths: The sizes of the ngrams to create.
|
|
* @param leftPad: The string to use to pad the left side of the ngram sequence.
|
|
* Only used if pad_width !== 0.
|
|
* @param rightPad: The string to use to pad the right side of the ngram
|
|
* sequence. Only used if pad_width !== 0.
|
|
* @param padWidth: The number of padding elements to add to each side of each
|
|
* sequence. Note that padding will never be greater than `nGramWidths`-1
|
|
* regardless of this value. If `padWidth`=-1, then add max(`nGramWidths`)-1
|
|
* elements.
|
|
* @param preserveShortSequences: If true, then ensure that at least one ngram
|
|
* is generated for each input sequence. In particular, if an input sequence
|
|
* is shorter than min(ngramWidth) + 2*padWidth, then generate a single
|
|
* ngram containing the entire sequence. If false, then no ngrams are
|
|
* generated for these short input sequences.
|
|
* @return A map with the following properties:
|
|
* - nGrams: The values tensor of the output ngrams ragged tensor.
|
|
* - nGramsSplits: The splits tensor of the output ngrams ragged tensor.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'String'}
|
|
*/ function stringNGrams_(data, dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
|
|
const $data = (0, _tensorUtilEnv.convertToTensor)(data, "data", "stringNGrams", "string");
|
|
if ($data.dtype !== "string") throw new Error("Data must be of datatype string");
|
|
if ($data.shape.length !== 1) throw new Error(`Data must be a vector, saw: ${$data.shape}`);
|
|
const $dataSplits = (0, _tensorUtilEnv.convertToTensor)(dataSplits, "dataSplits", "stringNGrams");
|
|
if ($dataSplits.dtype !== "int32") throw new Error("Data splits must be of datatype int32");
|
|
const attrs = {
|
|
separator,
|
|
nGramWidths,
|
|
leftPad,
|
|
rightPad,
|
|
padWidth,
|
|
preserveShortSequences
|
|
};
|
|
const inputs = {
|
|
data: $data,
|
|
dataSplits: $dataSplits
|
|
};
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.StringNGrams), inputs, attrs);
|
|
return {
|
|
nGrams: result[0],
|
|
nGramsSplits: result[1]
|
|
};
|
|
}
|
|
const stringNGrams = /* @__PURE__ */ (0, _operation.op)({
|
|
stringNGrams_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3z1cj":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringSplit", ()=>stringSplit);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Split elements of `input` based on `delimiter` into a SparseTensor .
|
|
*
|
|
* Let N be the size of source (typically N will be the batch size). Split each
|
|
* element of `input` based on `delimiter` and return a SparseTensor containing
|
|
* the splitted tokens. Empty tokens are ignored if `skipEmpty` is set to True.
|
|
*
|
|
* `delimiter` can be empty, or a string of split characters. If `delimiter` is
|
|
* an empty string, each element of `input` is split into individual
|
|
* character strings. Otherwise every character of `delimiter` is a potential
|
|
* split point.
|
|
*
|
|
* ```js
|
|
* const result = tf.string.stringSplit(['hello world', 'a b c'], ' ');
|
|
* result['indices'].print(); // [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2]]
|
|
* result['values'].print(); // ['hello', 'world', 'a', 'b', 'c']
|
|
* result['shape'].print(); // [2, 3]
|
|
* ```
|
|
* @param input: 1-D. Strings to split.
|
|
* @param delimiter: 0-D. Delimiter characters, or empty string.
|
|
* @param skipEmpty: Optional. If true, skip the empty strings from the result.
|
|
* Defaults to true.
|
|
* @return A map with the following properties:
|
|
* - indices: A dense matrix of int32 representing the indices of the sparse
|
|
* tensor.
|
|
* - values: A vector of strings corresponding to the splited values.
|
|
* - shape: a length-2 vector of int32 representing the shape of the sparse
|
|
* tensor, where the first value is N and the second value is the maximum number
|
|
* of tokens in a single input entry.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'String'}
|
|
*/ function stringSplit_(input, delimiter, skipEmpty = true) {
|
|
const $input = (0, _tensorUtilEnv.convertToTensor)(input, "input", "stringSplit", "string");
|
|
const $delimiter = (0, _tensorUtilEnv.convertToTensor)(delimiter, "delimiter", "stringSplit", "string");
|
|
if ($input.rank !== 1) throw new Error(`Input should be Tensor1D but received shape ${$input.shape}`);
|
|
if ($delimiter.rank !== 0) throw new Error(`Delimiter should be a scalar but received shape ${$delimiter.shape}`);
|
|
const attrs = {
|
|
skipEmpty
|
|
};
|
|
const inputs = {
|
|
input: $input,
|
|
delimiter: $delimiter
|
|
};
|
|
const result = (0, _engine.ENGINE).runKernel((0, _kernelNames.StringSplit), inputs, attrs);
|
|
return {
|
|
indices: result[0],
|
|
values: result[1],
|
|
shape: result[2]
|
|
};
|
|
}
|
|
const stringSplit = /* @__PURE__ */ (0, _operation.op)({
|
|
stringSplit_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8mVop":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringToHashBucketFast", ()=>stringToHashBucketFast);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Converts each string in the input Tensor to its hash mod by a number of
|
|
* buckets.
|
|
*
|
|
* The hash function is deterministic on the content of the string within the
|
|
* process and will never change. However, it is not suitable for cryptography.
|
|
* This function may be used when CPU time is scarce and inputs are trusted or
|
|
* unimportant. There is a risk of adversaries constructing inputs that all hash
|
|
* to the same bucket.
|
|
*
|
|
* ```js
|
|
* const result = tf.string.stringToHashBucketFast(
|
|
* ['Hello', 'TensorFlow', '2.x'], 3);
|
|
* result.print(); // [0, 2, 2]
|
|
* ```
|
|
* @param input: The strings to assign a hash bucket.
|
|
* @param numBuckets: The number of buckets.
|
|
* @return A Tensor of the same shape as the input tensor.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'String'}
|
|
*/ function stringToHashBucketFast_(input, numBuckets) {
|
|
const $input = (0, _tensorUtilEnv.convertToTensor)(input, "input", "stringToHashBucketFast", "string");
|
|
const attrs = {
|
|
numBuckets
|
|
};
|
|
if (numBuckets <= 0) throw new Error(`Number of buckets must be at least 1`);
|
|
const inputs = {
|
|
input: $input
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.StringToHashBucketFast), inputs, attrs);
|
|
}
|
|
const stringToHashBucketFast = /* @__PURE__ */ (0, _operation.op)({
|
|
stringToHashBucketFast_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dLgGV":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "staticRegexReplace", ()=>staticRegexReplace);
|
|
var _engine = require("../../engine");
|
|
var _kernelNames = require("../../kernel_names");
|
|
var _tensorUtilEnv = require("../../tensor_util_env");
|
|
var _operation = require("../operation");
|
|
/**
|
|
* Replace the match of a `pattern` in `input` with `rewrite`.
|
|
*
|
|
* ```js
|
|
* const result = tf.string.staticRegexReplace(
|
|
* ['format this spacing better'], ' +', ' ');
|
|
* result.print(); // ['format this spacing better']
|
|
* ```
|
|
* @param input: A Tensor of type string. The text to be processed.
|
|
* @param pattern: A string. The regular expression to match the input.
|
|
* @param rewrite: A string. The rewrite to be applied to the matched
|
|
* expression.
|
|
* @param replaceGlobal: An optional bool. Defaults to True. If True, the
|
|
* replacement is global, otherwise the replacement is done only on the
|
|
* first match.
|
|
* @return A Tensor of type string.
|
|
*
|
|
* @doc {heading: 'Operations', subheading: 'String'}
|
|
*/ function staticRegexReplace_(input, pattern, rewrite, replaceGlobal = true) {
|
|
const $input = (0, _tensorUtilEnv.convertToTensor)(input, "input", "staticRegexReplace", "string");
|
|
const attrs = {
|
|
pattern,
|
|
rewrite,
|
|
replaceGlobal
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.StaticRegexReplace), {
|
|
x: $input
|
|
}, attrs);
|
|
}
|
|
const staticRegexReplace = /* @__PURE__ */ (0, _operation.op)({
|
|
staticRegexReplace_
|
|
});
|
|
|
|
},{"../../engine":"1g2qo","../../kernel_names":"hniYO","../../tensor_util_env":"6vfHI","../operation":"ip64W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1b69z":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/** @doc {heading: 'Training', subheading: 'Classes', namespace: 'train'} */ parcelHelpers.export(exports, "Optimizer", ()=>Optimizer);
|
|
var _globals = require("../globals");
|
|
var _gradients = require("../gradients");
|
|
var _ops = require("../ops/ops");
|
|
var _serialization = require("../serialization");
|
|
class Optimizer extends (0, _serialization.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.
|
|
(0, _globals.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.
|
|
*
|
|
* @doc {heading: 'Training', subheading: 'Optimizers'}
|
|
*/ computeGradients(f, varList) {
|
|
return (0, _gradients.variableGrads)(f, varList);
|
|
}
|
|
/**
|
|
* Dispose the variables (if any) owned by this optimizer instance.
|
|
*/ dispose() {
|
|
if (this.iterations_ != null) (0, _globals.dispose)(this.iterations_);
|
|
}
|
|
async saveIterations() {
|
|
if (this.iterations_ == null) this.iterations_ = 0;
|
|
return {
|
|
name: "iter",
|
|
// TODO(cais): Use 'int64' type when available.
|
|
tensor: (0, _ops.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, Symbol.hasInstance, {
|
|
value: (instance)=>{
|
|
return instance.minimize != null && instance.computeGradients != null && instance.applyGradients != null;
|
|
}
|
|
});
|
|
|
|
},{"../globals":"eO1Ja","../gradients":"dDHpg","../ops/ops":"13k1e","../serialization":"dv6JX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dv6JX":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Serializable defines the serialization contract.
|
|
*
|
|
* TFJS requires serializable classes to return their className when asked
|
|
* to avoid issues with minification.
|
|
*/ parcelHelpers.export(exports, "Serializable", ()=>Serializable);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "SerializationMap", ()=>SerializationMap);
|
|
/**
|
|
* 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 1. Register the class without package name and specified name.
|
|
*
|
|
* ```js
|
|
* class MyCustomLayer extends tf.layers.Layer {
|
|
* static className = 'MyCustomLayer';
|
|
*
|
|
* constructor(config) {
|
|
* super(config);
|
|
* }
|
|
* }
|
|
* tf.serialization.registerClass(MyCustomLayer);
|
|
* console.log(tf.serialization.GLOBALCUSTOMOBJECT.get("Custom>MyCustomLayer"));
|
|
* console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));
|
|
* ```
|
|
*
|
|
* Example 2. Register the class with package name: "Package" and specified
|
|
* name: "MyLayer".
|
|
* ```js
|
|
* class MyCustomLayer extends tf.layers.Layer {
|
|
* static className = 'MyCustomLayer';
|
|
*
|
|
* constructor(config) {
|
|
* super(config);
|
|
* }
|
|
* }
|
|
* tf.serialization.registerClass(MyCustomLayer, "Package", "MyLayer");
|
|
* console.log(tf.serialization.GLOBALCUSTOMOBJECT.get("Package>MyLayer"));
|
|
* console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));
|
|
* ```
|
|
*
|
|
* Example 3. Register the class with specified name: "MyLayer".
|
|
* ```js
|
|
* class MyCustomLayer extends tf.layers.Layer {
|
|
* static className = 'MyCustomLayer';
|
|
*
|
|
* constructor(config) {
|
|
* super(config);
|
|
* }
|
|
* }
|
|
* tf.serialization.registerClass(MyCustomLayer, undefined, "MyLayer");
|
|
* console.log(tf.serialization.GLOBALCUSTOMOBJECT.get("Custom>MyLayer"));
|
|
* console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));
|
|
* ```
|
|
*
|
|
* Example 4. Register the class with specified package name: "Package".
|
|
* ```js
|
|
* class MyCustomLayer extends tf.layers.Layer {
|
|
* static className = 'MyCustomLayer';
|
|
*
|
|
* constructor(config) {
|
|
* super(config);
|
|
* }
|
|
* }
|
|
* tf.serialization.registerClass(MyCustomLayer, "Package");
|
|
* console.log(tf.serialization.GLOBALCUSTOMOBJECT
|
|
* .get("Package>MyCustomLayer"));
|
|
* console.log(tf.serialization.GLOBALCUSTOMNAMES
|
|
* .get(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.
|
|
* @param pkg The pakcage name that this class belongs to. This used to define
|
|
* the key in GlobalCustomObject. If not defined, it defaults to `Custom`.
|
|
* @param name The name that user specified. It defaults to the actual name of
|
|
* the class as specified by its static `className` property.
|
|
* @doc {heading: 'Models', subheading: 'Serialization', ignoreCI: true}
|
|
*/ parcelHelpers.export(exports, "registerClass", ()=>registerClass);
|
|
/**
|
|
* Get the registered name of a class. If the class has not been registered,
|
|
* return the class name.
|
|
*
|
|
* @param cls The class we want to get register name for. It must have a public
|
|
* static member called `className` defined.
|
|
* @returns registered name or class name.
|
|
*/ parcelHelpers.export(exports, "getRegisteredName", ()=>getRegisteredName);
|
|
var _util = require("./util");
|
|
/**
|
|
* Maps to mapping between the custom object and its name.
|
|
*
|
|
* After registering a custom class, these two maps will add key-value pairs
|
|
* for the class object and the registered name.
|
|
*
|
|
* Therefore we can get the relative registered name by calling
|
|
* getRegisteredName() function.
|
|
*
|
|
* For example:
|
|
* GLOBAL_CUSTOM_OBJECT: {key=registeredName: value=corresponding
|
|
* CustomObjectClass}
|
|
*
|
|
* GLOBAL_CUSTOM_NAMES: {key=CustomObjectClass: value=corresponding
|
|
* registeredName}
|
|
*
|
|
*/ const GLOBAL_CUSTOM_OBJECT = new Map();
|
|
const GLOBAL_CUSTOM_NAMES = new Map();
|
|
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);
|
|
}
|
|
}
|
|
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
|
|
];
|
|
}
|
|
}
|
|
function registerClass(cls, pkg, name) {
|
|
(0, _util.assert)(cls.className != null, ()=>`Class being registered does not have the static className ` + `property defined.`);
|
|
(0, _util.assert)(typeof cls.className === "string", ()=>`className is required to be a string, but got type ` + typeof cls.className);
|
|
(0, _util.assert)(cls.className.length > 0, ()=>`Class being registered has an empty-string as its className, ` + `which is disallowed.`);
|
|
if (typeof pkg === "undefined") pkg = "Custom";
|
|
if (typeof name === "undefined") name = cls.className;
|
|
const className = name;
|
|
const registerName = pkg + ">" + className;
|
|
SerializationMap.register(cls);
|
|
GLOBAL_CUSTOM_OBJECT.set(registerName, cls);
|
|
GLOBAL_CUSTOM_NAMES.set(cls, registerName);
|
|
return cls;
|
|
}
|
|
function getRegisteredName(cls) {
|
|
if (GLOBAL_CUSTOM_NAMES.has(cls)) return GLOBAL_CUSTOM_NAMES.get(cls);
|
|
else return cls.className;
|
|
}
|
|
|
|
},{"./util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ddRDd":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/** @doclink Optimizer */ parcelHelpers.export(exports, "AdagradOptimizer", ()=>AdagradOptimizer);
|
|
var _engine = require("../engine");
|
|
var _globals = require("../globals");
|
|
var _add = require("../ops/add");
|
|
var _div = require("../ops/div");
|
|
var _fill = require("../ops/fill");
|
|
var _mul = require("../ops/mul");
|
|
var _sqrt = require("../ops/sqrt");
|
|
var _square = require("../ops/square");
|
|
var _optimizer = require("./optimizer");
|
|
class AdagradOptimizer extends (0, _optimizer.Optimizer) {
|
|
/** @nocollapse */ static get className() {
|
|
// Name matters for Python compatibility.
|
|
// This is a getter instead of a property because when it's a property, it
|
|
// prevents the entire class from being tree-shaken.
|
|
return "Adagrad";
|
|
}
|
|
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 = (0, _engine.ENGINE).registeredVariables[name];
|
|
if (this.accumulatedGrads[i] == null) {
|
|
const trainable = false;
|
|
this.accumulatedGrads[i] = {
|
|
originalName: `${name}/accumulator`,
|
|
variable: (0, _globals.tidy)(()=>(0, _fill.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;
|
|
(0, _globals.tidy)(()=>{
|
|
const newAccumulatedGrad = (0, _add.add)(accumulatedGrad, (0, _square.square)(gradient));
|
|
accumulatedGrad.assign(newAccumulatedGrad);
|
|
const newValue = (0, _add.add)((0, _mul.mul)((0, _div.div)(gradient, (0, _sqrt.sqrt)((0, _add.add)(newAccumulatedGrad, (0, _engine.ENGINE).backend.epsilon()))), -this.learningRate), value);
|
|
value.assign(newValue);
|
|
});
|
|
});
|
|
this.incrementIterations();
|
|
}
|
|
dispose() {
|
|
if (this.accumulatedGrads != null) (0, _globals.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"]);
|
|
}
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../globals":"eO1Ja","../ops/add":"aynh7","../ops/div":"5ZT1h","../ops/fill":"i7goe","../ops/mul":"fOWrC","../ops/sqrt":"cOGi9","../ops/square":"cOosW","./optimizer":"1b69z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5uefH":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "AdamOptimizer", ()=>AdamOptimizer);
|
|
var _engine = require("../engine");
|
|
var _globals = require("../globals");
|
|
var _add = require("../ops/add");
|
|
var _div = require("../ops/div");
|
|
var _mul = require("../ops/mul");
|
|
var _pow = require("../ops/pow");
|
|
var _scalar = require("../ops/scalar");
|
|
var _sqrt = require("../ops/sqrt");
|
|
var _square = require("../ops/square");
|
|
var _sub = require("../ops/sub");
|
|
var _zerosLike = require("../ops/zeros_like");
|
|
var _optimizer = require("./optimizer");
|
|
class AdamOptimizer extends (0, _optimizer.Optimizer) {
|
|
/** @nocollapse */ static get className() {
|
|
// Name matters for Python compatibility.
|
|
// This is a getter instead of a property because when it's a property, it
|
|
// prevents the entire class from being tree-shaken.
|
|
return "Adam";
|
|
}
|
|
constructor(learningRate, beta1, beta2, epsilon = null){
|
|
super();
|
|
this.learningRate = learningRate;
|
|
this.beta1 = beta1;
|
|
this.beta2 = beta2;
|
|
this.epsilon = epsilon;
|
|
this.accumulatedFirstMoment = [];
|
|
this.accumulatedSecondMoment = [];
|
|
(0, _globals.tidy)(()=>{
|
|
// accB* will be updated by batch.
|
|
this.accBeta1 = (0, _scalar.scalar)(beta1).variable();
|
|
this.accBeta2 = (0, _scalar.scalar)(beta2).variable();
|
|
});
|
|
if (epsilon == null) this.epsilon = (0, _engine.ENGINE).backend.epsilon();
|
|
}
|
|
applyGradients(variableGradients) {
|
|
const varNames = Array.isArray(variableGradients) ? variableGradients.map((v)=>v.name) : Object.keys(variableGradients);
|
|
(0, _globals.tidy)(()=>{
|
|
const oneMinusAccBeta1 = (0, _sub.sub)(1, this.accBeta1);
|
|
const oneMinusAccBeta2 = (0, _sub.sub)(1, this.accBeta2);
|
|
varNames.forEach((name, i)=>{
|
|
const value = (0, _engine.ENGINE).registeredVariables[name];
|
|
const trainable = false;
|
|
if (this.accumulatedFirstMoment[i] == null) this.accumulatedFirstMoment[i] = {
|
|
originalName: `${name}/m`,
|
|
variable: (0, _globals.tidy)(()=>(0, _zerosLike.zerosLike)(value).variable(trainable))
|
|
};
|
|
if (this.accumulatedSecondMoment[i] == null) this.accumulatedSecondMoment[i] = {
|
|
originalName: `${name}/v`,
|
|
variable: (0, _globals.tidy)(()=>(0, _zerosLike.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 = (0, _add.add)((0, _mul.mul)(firstMoment, this.beta1), (0, _mul.mul)(gradient, 1 - this.beta1));
|
|
const newSecondMoment = (0, _add.add)((0, _mul.mul)(secondMoment, this.beta2), (0, _mul.mul)((0, _square.square)(gradient), 1 - this.beta2));
|
|
const biasCorrectedFirstMoment = (0, _div.div)(newFirstMoment, oneMinusAccBeta1);
|
|
const biasCorrectedSecondMoment = (0, _div.div)(newSecondMoment, oneMinusAccBeta2);
|
|
firstMoment.assign(newFirstMoment);
|
|
secondMoment.assign(newSecondMoment);
|
|
const newValue = (0, _add.add)((0, _mul.mul)((0, _div.div)(biasCorrectedFirstMoment, (0, _add.add)((0, _sqrt.sqrt)(biasCorrectedSecondMoment), this.epsilon)), -this.learningRate), value);
|
|
value.assign(newValue);
|
|
});
|
|
this.accBeta1.assign((0, _mul.mul)(this.accBeta1, this.beta1));
|
|
this.accBeta2.assign((0, _mul.mul)(this.accBeta2, this.beta2));
|
|
});
|
|
this.incrementIterations();
|
|
}
|
|
dispose() {
|
|
this.accBeta1.dispose();
|
|
this.accBeta2.dispose();
|
|
if (this.accumulatedFirstMoment != null) (0, _globals.dispose)(this.accumulatedFirstMoment.map((v)=>v.variable));
|
|
if (this.accumulatedSecondMoment != null) (0, _globals.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);
|
|
(0, _globals.tidy)(()=>{
|
|
this.accBeta1.assign((0, _pow.pow)(this.beta1, this.iterations_ + 1));
|
|
this.accBeta2.assign((0, _pow.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"]);
|
|
}
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../globals":"eO1Ja","../ops/add":"aynh7","../ops/div":"5ZT1h","../ops/mul":"fOWrC","../ops/pow":"gezpC","../ops/scalar":"7lhC8","../ops/sqrt":"cOGi9","../ops/square":"cOosW","../ops/sub":"jBBQ2","../ops/zeros_like":"1Xjct","./optimizer":"1b69z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"72DSu":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "AdamaxOptimizer", ()=>AdamaxOptimizer);
|
|
var _engine = require("../engine");
|
|
var _globals = require("../globals");
|
|
var _abs = require("../ops/abs");
|
|
var _add = require("../ops/add");
|
|
var _div = require("../ops/div");
|
|
var _maximum = require("../ops/maximum");
|
|
var _mul = require("../ops/mul");
|
|
var _scalar = require("../ops/scalar");
|
|
var _sub = require("../ops/sub");
|
|
var _zerosLike = require("../ops/zeros_like");
|
|
var _optimizer = require("./optimizer");
|
|
class AdamaxOptimizer extends (0, _optimizer.Optimizer) {
|
|
/** @nocollapse */ static get className() {
|
|
// Name matters for Python compatibility.
|
|
// This is a getter instead of a property because when it's a property, it
|
|
// prevents the entire class from being tree-shaken.
|
|
return "Adamax";
|
|
}
|
|
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 = [];
|
|
(0, _globals.tidy)(()=>{
|
|
this.iteration = (0, _scalar.scalar)(0).variable();
|
|
this.accBeta1 = (0, _scalar.scalar)(beta1).variable();
|
|
});
|
|
if (epsilon == null) this.epsilon = (0, _engine.ENGINE).backend.epsilon();
|
|
}
|
|
applyGradients(variableGradients) {
|
|
const variableNames = Array.isArray(variableGradients) ? variableGradients.map((item)=>item.name) : Object.keys(variableGradients);
|
|
(0, _globals.tidy)(()=>{
|
|
const oneMinusAccBeta1 = (0, _sub.sub)(1, this.accBeta1);
|
|
const lr = (0, _div.div)(-this.learningRate, (0, _add.add)((0, _mul.mul)(this.iteration, this.decay), 1));
|
|
variableNames.forEach((name, i)=>{
|
|
const value = (0, _engine.ENGINE).registeredVariables[name];
|
|
const trainable = false;
|
|
if (this.accumulatedFirstMoment[i] == null) this.accumulatedFirstMoment[i] = {
|
|
originalName: `${name}/m`,
|
|
variable: (0, _zerosLike.zerosLike)(value).variable(trainable)
|
|
};
|
|
if (this.accumulatedWeightedInfNorm[i] == null) this.accumulatedWeightedInfNorm[i] = {
|
|
originalName: `${name}/v`,
|
|
variable: (0, _zerosLike.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 = (0, _add.add)((0, _mul.mul)(firstMoment, this.beta1), (0, _mul.mul)(gradient, 1 - this.beta1));
|
|
const ut0 = (0, _mul.mul)(weightedInfNorm, this.beta2);
|
|
const ut1 = (0, _abs.abs)(gradient);
|
|
const newWeightedInfNorm = (0, _maximum.maximum)(ut0, ut1);
|
|
firstMoment.assign(newFirstMoment);
|
|
weightedInfNorm.assign(newWeightedInfNorm);
|
|
const newValue = (0, _add.add)((0, _mul.mul)((0, _div.div)(lr, oneMinusAccBeta1), (0, _div.div)(newFirstMoment, (0, _add.add)(newWeightedInfNorm, this.epsilon))), value);
|
|
value.assign(newValue);
|
|
});
|
|
this.iteration.assign((0, _add.add)(this.iteration, 1));
|
|
this.accBeta1.assign((0, _mul.mul)(this.accBeta1, this.beta1));
|
|
});
|
|
this.incrementIterations();
|
|
}
|
|
dispose() {
|
|
this.accBeta1.dispose();
|
|
this.iteration.dispose();
|
|
if (this.accumulatedFirstMoment != null) (0, _globals.dispose)(this.accumulatedFirstMoment.map((v)=>v.variable));
|
|
if (this.accumulatedWeightedInfNorm != null) (0, _globals.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"]);
|
|
}
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../globals":"eO1Ja","../ops/abs":"iZQ4e","../ops/add":"aynh7","../ops/div":"5ZT1h","../ops/maximum":"1nFpL","../ops/mul":"fOWrC","../ops/scalar":"7lhC8","../ops/sub":"jBBQ2","../ops/zeros_like":"1Xjct","./optimizer":"1b69z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bKhX1":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/** @doclink Optimizer */ parcelHelpers.export(exports, "MomentumOptimizer", ()=>MomentumOptimizer);
|
|
var _engine = require("../engine");
|
|
var _globals = require("../globals");
|
|
var _add = require("../ops/add");
|
|
var _mul = require("../ops/mul");
|
|
var _scalar = require("../ops/scalar");
|
|
var _zerosLike = require("../ops/zeros_like");
|
|
var _sgdOptimizer = require("./sgd_optimizer");
|
|
class MomentumOptimizer extends (0, _sgdOptimizer.SGDOptimizer) {
|
|
/** @nocollapse */ // Name matters for Python compatibility.
|
|
static get className() {
|
|
// Name matters for Python compatibility.
|
|
// This is a getter instead of a property because when it's a property, it
|
|
// prevents the entire class from being tree-shaken.
|
|
return "Momentum";
|
|
}
|
|
constructor(learningRate, momentum, useNesterov = false){
|
|
super(learningRate);
|
|
this.learningRate = learningRate;
|
|
this.momentum = momentum;
|
|
this.useNesterov = useNesterov;
|
|
this.accumulations = [];
|
|
this.m = (0, _scalar.scalar)(this.momentum);
|
|
}
|
|
applyGradients(variableGradients) {
|
|
const variableNames = Array.isArray(variableGradients) ? variableGradients.map((item)=>item.name) : Object.keys(variableGradients);
|
|
variableNames.forEach((name, i)=>{
|
|
const value = (0, _engine.ENGINE).registeredVariables[name];
|
|
if (this.accumulations[i] == null) {
|
|
const trainable = false;
|
|
this.accumulations[i] = {
|
|
originalName: `${name}/momentum`,
|
|
variable: (0, _globals.tidy)(()=>(0, _zerosLike.zerosLike)(value).variable(trainable))
|
|
};
|
|
}
|
|
const accumulation = this.accumulations[i].variable;
|
|
const gradient = Array.isArray(variableGradients) ? variableGradients[i].tensor : variableGradients[name];
|
|
if (gradient == null) return;
|
|
(0, _globals.tidy)(()=>{
|
|
let newValue;
|
|
const newAccumulation = (0, _add.add)((0, _mul.mul)(this.m, accumulation), gradient);
|
|
if (this.useNesterov) newValue = (0, _add.add)((0, _mul.mul)(this.c, (0, _add.add)(gradient, (0, _mul.mul)(newAccumulation, this.m))), value);
|
|
else newValue = (0, _add.add)((0, _mul.mul)(this.c, newAccumulation), value);
|
|
accumulation.assign(newAccumulation);
|
|
value.assign(newValue);
|
|
});
|
|
});
|
|
this.incrementIterations();
|
|
}
|
|
dispose() {
|
|
this.m.dispose();
|
|
if (this.accumulations != null) (0, _globals.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"]);
|
|
}
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../globals":"eO1Ja","../ops/add":"aynh7","../ops/mul":"fOWrC","../ops/scalar":"7lhC8","../ops/zeros_like":"1Xjct","./sgd_optimizer":"4dxnr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4dxnr":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/** @doclink Optimizer */ parcelHelpers.export(exports, "SGDOptimizer", ()=>SGDOptimizer);
|
|
var _engine = require("../engine");
|
|
var _globals = require("../globals");
|
|
var _add = require("../ops/add");
|
|
var _mul = require("../ops/mul");
|
|
var _scalar = require("../ops/scalar");
|
|
var _optimizer = require("./optimizer");
|
|
class SGDOptimizer extends (0, _optimizer.Optimizer) {
|
|
/** @nocollapse */ static get className() {
|
|
// Name matters for Python compatibility.
|
|
// This is a getter instead of a property because when it's a property, it
|
|
// prevents the entire class from being tree-shaken.
|
|
return "SGD";
|
|
}
|
|
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 = (0, _engine.ENGINE).registeredVariables[name];
|
|
(0, _globals.tidy)(()=>{
|
|
const newValue = (0, _add.add)((0, _mul.mul)(this.c, gradient), 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 = (0, _globals.keep)((0, _scalar.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"]);
|
|
}
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../globals":"eO1Ja","../ops/add":"aynh7","../ops/mul":"fOWrC","../ops/scalar":"7lhC8","./optimizer":"1b69z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"66Wvy":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/** @doclink Optimizer */ parcelHelpers.export(exports, "RMSPropOptimizer", ()=>RMSPropOptimizer);
|
|
var _engine = require("../engine");
|
|
var _globals = require("../globals");
|
|
var _add = require("../ops/add");
|
|
var _div = require("../ops/div");
|
|
var _mul = require("../ops/mul");
|
|
var _sqrt = require("../ops/sqrt");
|
|
var _square = require("../ops/square");
|
|
var _sub = require("../ops/sub");
|
|
var _zerosLike = require("../ops/zeros_like");
|
|
var _optimizer = require("./optimizer");
|
|
class RMSPropOptimizer extends (0, _optimizer.Optimizer) {
|
|
/** @nocollapse */ static get className() {
|
|
// Name matters for Python compatibility.
|
|
// This is a getter instead of a property because when it's a property, it
|
|
// prevents the entire class from being tree-shaken.
|
|
return "RMSProp";
|
|
}
|
|
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 = (0, _engine.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 = (0, _engine.ENGINE).registeredVariables[name];
|
|
const trainable = false;
|
|
if (this.accumulatedMeanSquares[i] == null) this.accumulatedMeanSquares[i] = {
|
|
originalName: `${name}/rms`,
|
|
variable: (0, _globals.tidy)(()=>(0, _zerosLike.zerosLike)(value).variable(trainable))
|
|
};
|
|
if (this.accumulatedMoments[i] == null) this.accumulatedMoments[i] = {
|
|
originalName: `${name}/momentum`,
|
|
variable: (0, _globals.tidy)(()=>(0, _zerosLike.zerosLike)(value).variable(trainable))
|
|
};
|
|
if (this.accumulatedMeanGrads[i] == null && this.centered) this.accumulatedMeanGrads[i] = {
|
|
originalName: `${name}/mg`,
|
|
variable: (0, _globals.tidy)(()=>(0, _zerosLike.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;
|
|
(0, _globals.tidy)(()=>{
|
|
const newAccumulatedMeanSquare = (0, _add.add)((0, _mul.mul)(accumulatedMeanSquare, this.decay), (0, _mul.mul)((0, _square.square)(gradient), 1 - this.decay));
|
|
if (this.centered) {
|
|
const accumulatedMeanGrad = this.accumulatedMeanGrads[i].variable;
|
|
// Centered gradient
|
|
const newAccumulatedMeanGrad = (0, _add.add)((0, _mul.mul)(accumulatedMeanGrad, this.decay), (0, _mul.mul)(gradient, 1 - this.decay));
|
|
const gradContribution = (0, _div.div)((0, _mul.mul)(gradient, this.learningRate), (0, _sqrt.sqrt)((0, _sub.sub)(newAccumulatedMeanSquare, (0, _add.add)((0, _square.square)(newAccumulatedMeanGrad), this.epsilon))));
|
|
const newAccumulatedMoments = (0, _add.add)((0, _mul.mul)(accumulatedMoments, this.momentum), gradContribution);
|
|
accumulatedMeanSquare.assign(newAccumulatedMeanSquare);
|
|
accumulatedMeanGrad.assign(newAccumulatedMeanGrad);
|
|
accumulatedMoments.assign(newAccumulatedMoments);
|
|
const newValue = (0, _sub.sub)(value, newAccumulatedMoments);
|
|
value.assign(newValue);
|
|
} else {
|
|
// Plain gradient
|
|
const newAccumulatedMeanSquare = (0, _add.add)((0, _mul.mul)(accumulatedMeanSquare, this.decay), (0, _mul.mul)((0, _square.square)(gradient), 1 - this.decay));
|
|
const newAccumulatedMoments = (0, _add.add)((0, _mul.mul)(accumulatedMoments, this.momentum), (0, _div.div)((0, _mul.mul)(gradient, this.learningRate), (0, _sqrt.sqrt)((0, _add.add)(newAccumulatedMeanSquare, this.epsilon))));
|
|
accumulatedMeanSquare.assign(newAccumulatedMeanSquare);
|
|
accumulatedMoments.assign(newAccumulatedMoments);
|
|
const newValue = (0, _sub.sub)(value, newAccumulatedMoments);
|
|
value.assign(newValue);
|
|
}
|
|
});
|
|
});
|
|
this.incrementIterations();
|
|
}
|
|
dispose() {
|
|
if (this.accumulatedMeanSquares != null) (0, _globals.dispose)(this.accumulatedMeanSquares.map((v)=>v.variable));
|
|
if (this.accumulatedMeanGrads != null && this.centered) (0, _globals.dispose)(this.accumulatedMeanGrads.map((v)=>v.variable));
|
|
if (this.accumulatedMoments != null) (0, _globals.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"]);
|
|
}
|
|
}
|
|
|
|
},{"../engine":"1g2qo","../globals":"eO1Ja","../ops/add":"aynh7","../ops/div":"5ZT1h","../ops/mul":"fOWrC","../ops/sqrt":"cOGi9","../ops/square":"cOosW","../ops/sub":"jBBQ2","../ops/zeros_like":"1Xjct","./optimizer":"1b69z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ATETN":[function(require,module,exports) {
|
|
/**
|
|
* @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 is tfjs-core without auto registration of things like flags,
|
|
// gradients, chained ops or the opHandler. See base_side_effects.ts for parts
|
|
// tfjs core that are required side effects.
|
|
/**
|
|
* @fileoverview
|
|
* @suppress {partialAlias} Optimization disabled due to passing the module
|
|
* object into a function below:
|
|
*
|
|
* import * as ops from './ops/ops';
|
|
* setOpHandler(ops);
|
|
*/ // Serialization.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "AdadeltaOptimizer", ()=>(0, _adadeltaOptimizer.AdadeltaOptimizer));
|
|
parcelHelpers.export(exports, "AdagradOptimizer", ()=>(0, _adagradOptimizer.AdagradOptimizer));
|
|
parcelHelpers.export(exports, "AdamOptimizer", ()=>(0, _adamOptimizer.AdamOptimizer));
|
|
parcelHelpers.export(exports, "AdamaxOptimizer", ()=>(0, _adamaxOptimizer.AdamaxOptimizer));
|
|
parcelHelpers.export(exports, "MomentumOptimizer", ()=>(0, _momentumOptimizer.MomentumOptimizer));
|
|
parcelHelpers.export(exports, "Optimizer", ()=>(0, _optimizer.Optimizer));
|
|
// Optimizers.
|
|
parcelHelpers.export(exports, "OptimizerConstructors", ()=>(0, _optimizerConstructors.OptimizerConstructors));
|
|
parcelHelpers.export(exports, "RMSPropOptimizer", ()=>(0, _rmspropOptimizer.RMSPropOptimizer));
|
|
parcelHelpers.export(exports, "SGDOptimizer", ()=>(0, _sgdOptimizer.SGDOptimizer));
|
|
parcelHelpers.export(exports, "Tensor", ()=>(0, _tensor.Tensor));
|
|
parcelHelpers.export(exports, "TensorBuffer", ()=>(0, _tensor.TensorBuffer));
|
|
parcelHelpers.export(exports, "Variable", ()=>(0, _tensor.Variable));
|
|
parcelHelpers.export(exports, "Rank", ()=>(0, _types.Rank));
|
|
parcelHelpers.export(exports, "sumOutType", ()=>(0, _types.sumOutType));
|
|
parcelHelpers.export(exports, "upcastType", ()=>(0, _types.upcastType));
|
|
parcelHelpers.export(exports, "Reduction", ()=>(0, _lossOpsUtils.Reduction));
|
|
parcelHelpers.export(exports, "customGrad", ()=>(0, _gradients.customGrad));
|
|
parcelHelpers.export(exports, "grad", ()=>(0, _gradients.grad));
|
|
parcelHelpers.export(exports, "grads", ()=>(0, _gradients.grads));
|
|
parcelHelpers.export(exports, "valueAndGrad", ()=>(0, _gradients.valueAndGrad));
|
|
parcelHelpers.export(exports, "valueAndGrads", ()=>(0, _gradients.valueAndGrads));
|
|
parcelHelpers.export(exports, "variableGrads", ()=>(0, _gradients.variableGrads));
|
|
parcelHelpers.export(exports, "Environment", ()=>(0, _environment.Environment));
|
|
parcelHelpers.export(exports, "env", ()=>(0, _environment.env));
|
|
parcelHelpers.export(exports, "ENV", ()=>(0, _environment.ENV));
|
|
// Top-level method exports.
|
|
parcelHelpers.export(exports, "nextFrame", ()=>(0, _browserUtil.nextFrame));
|
|
// Backend specific.
|
|
parcelHelpers.export(exports, "KernelBackend", ()=>(0, _backend.KernelBackend));
|
|
parcelHelpers.export(exports, "DataStorage", ()=>(0, _backend.DataStorage));
|
|
parcelHelpers.export(exports, "version_core", ()=>(0, _version.version));
|
|
parcelHelpers.export(exports, "browser", ()=>_browser);
|
|
parcelHelpers.export(exports, "io", ()=>_io);
|
|
parcelHelpers.export(exports, "math", ()=>_math);
|
|
parcelHelpers.export(exports, "serialization", ()=>_serialization);
|
|
parcelHelpers.export(exports, "test_util", ()=>_testUtil);
|
|
parcelHelpers.export(exports, "util", ()=>_util);
|
|
parcelHelpers.export(exports, "backend_util", ()=>_backendUtil);
|
|
parcelHelpers.export(exports, "broadcast_util", ()=>_broadcastUtil);
|
|
parcelHelpers.export(exports, "tensor_util", ()=>_tensorUtil);
|
|
parcelHelpers.export(exports, "slice_util", ()=>_sliceUtil);
|
|
parcelHelpers.export(exports, "gather_util", ()=>_gatherNdUtil);
|
|
parcelHelpers.export(exports, "scatter_util", ()=>_scatterNdUtil);
|
|
parcelHelpers.export(exports, "device_util", ()=>_deviceUtil);
|
|
parcelHelpers.export(exports, "kernel_impls", ()=>_kernelImpls);
|
|
var _io = require("./io/io");
|
|
var _math = require("./math");
|
|
var _broadcastUtil = require("./ops/broadcast_util");
|
|
var _browser = require("./ops/browser");
|
|
var _gatherNdUtil = require("./ops/gather_nd_util");
|
|
var _scatterNdUtil = require("./ops/scatter_nd_util");
|
|
var _sliceUtil = require("./ops/slice_util");
|
|
var _serialization = require("./serialization");
|
|
var _tensorUtil = require("./tensor_util");
|
|
var _testUtil = require("./test_util");
|
|
var _util = require("./util");
|
|
var _version = require("./version");
|
|
var _adadeltaOptimizer = require("./optimizers/adadelta_optimizer");
|
|
var _adagradOptimizer = require("./optimizers/adagrad_optimizer");
|
|
var _adamOptimizer = require("./optimizers/adam_optimizer");
|
|
var _adamaxOptimizer = require("./optimizers/adamax_optimizer");
|
|
var _momentumOptimizer = require("./optimizers/momentum_optimizer");
|
|
var _optimizer = require("./optimizers/optimizer");
|
|
var _optimizerConstructors = require("./optimizers/optimizer_constructors");
|
|
var _rmspropOptimizer = require("./optimizers/rmsprop_optimizer");
|
|
var _sgdOptimizer = require("./optimizers/sgd_optimizer");
|
|
var _tensor = require("./tensor");
|
|
var _types = require("./types");
|
|
var _ops = require("./ops/ops");
|
|
parcelHelpers.exportAll(_ops, exports);
|
|
var _lossOpsUtils = require("./ops/loss_ops_utils");
|
|
var _train = require("./train");
|
|
parcelHelpers.exportAll(_train, exports);
|
|
var _globals = require("./globals");
|
|
parcelHelpers.exportAll(_globals, exports);
|
|
var _kernelRegistry = require("./kernel_registry");
|
|
parcelHelpers.exportAll(_kernelRegistry, exports);
|
|
var _gradients = require("./gradients");
|
|
var _environment = require("./environment");
|
|
var _browserUtil = require("./browser_util");
|
|
// Second level exports.
|
|
var _backendUtil = require("./backends/backend_util");
|
|
var _deviceUtil = require("./device_util");
|
|
var _kernelImpls = require("./backends/kernel_impls");
|
|
var _backend = require("./backends/backend");
|
|
// Export all kernel names / info.
|
|
var _kernelNames = require("./kernel_names");
|
|
parcelHelpers.exportAll(_kernelNames, exports);
|
|
|
|
},{"./io/io":"d1chw","./math":"8ony7","./ops/broadcast_util":"eLo4J","./ops/browser":"iaaSH","./ops/gather_nd_util":"4RUOy","./ops/scatter_nd_util":"dDUQ5","./ops/slice_util":"3A9Ql","./serialization":"dv6JX","./tensor_util":"8jzJG","./test_util":"3IEFi","./util":"ctavo","./version":"5jZGL","./optimizers/adadelta_optimizer":"a2jsK","./optimizers/adagrad_optimizer":"ddRDd","./optimizers/adam_optimizer":"5uefH","./optimizers/adamax_optimizer":"72DSu","./optimizers/momentum_optimizer":"bKhX1","./optimizers/optimizer":"1b69z","./optimizers/optimizer_constructors":"eaK8y","./optimizers/rmsprop_optimizer":"66Wvy","./optimizers/sgd_optimizer":"4dxnr","./tensor":"cJNoh","./types":"10R8n","./ops/ops":"13k1e","./ops/loss_ops_utils":"6wY9M","./train":"cWOs6","./globals":"eO1Ja","./kernel_registry":"aG7g9","./gradients":"dDHpg","./environment":"dXmHm","./browser_util":"dz6Y8","./backends/backend_util":"8IvgS","./device_util":"5fozk","./backends/kernel_impls":"cylCc","./backends/backend":"dL2i3","./kernel_names":"hniYO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"d1chw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "copyModel", ()=>(0, _modelManagement.copyModel));
|
|
parcelHelpers.export(exports, "listModels", ()=>(0, _modelManagement.listModels));
|
|
parcelHelpers.export(exports, "moveModel", ()=>(0, _modelManagement.moveModel));
|
|
parcelHelpers.export(exports, "removeModel", ()=>(0, _modelManagement.removeModel));
|
|
parcelHelpers.export(exports, "browserFiles", ()=>(0, _browserFiles.browserFiles));
|
|
parcelHelpers.export(exports, "browserHTTPRequest", ()=>(0, _http.browserHTTPRequest));
|
|
parcelHelpers.export(exports, "CompositeArrayBuffer", ()=>(0, _compositeArrayBuffer.CompositeArrayBuffer));
|
|
parcelHelpers.export(exports, "concatenateArrayBuffers", ()=>(0, _ioUtils.concatenateArrayBuffers));
|
|
parcelHelpers.export(exports, "decodeWeights", ()=>(0, _ioUtils.decodeWeights));
|
|
parcelHelpers.export(exports, "decodeWeightsStream", ()=>(0, _ioUtils.decodeWeightsStream));
|
|
parcelHelpers.export(exports, "encodeWeights", ()=>(0, _ioUtils.encodeWeights));
|
|
parcelHelpers.export(exports, "fromMemory", ()=>(0, _passthrough.fromMemory));
|
|
parcelHelpers.export(exports, "fromMemorySync", ()=>(0, _passthrough.fromMemorySync));
|
|
parcelHelpers.export(exports, "getLoadHandlers", ()=>(0, _routerRegistry.getLoadHandlers));
|
|
parcelHelpers.export(exports, "getModelArtifactsForJSON", ()=>(0, _ioUtils.getModelArtifactsForJSON));
|
|
parcelHelpers.export(exports, "getModelArtifactsForJSONSync", ()=>(0, _ioUtils.getModelArtifactsForJSONSync));
|
|
parcelHelpers.export(exports, "getModelArtifactsInfoForJSON", ()=>(0, _ioUtils.getModelArtifactsInfoForJSON));
|
|
parcelHelpers.export(exports, "getSaveHandlers", ()=>(0, _routerRegistry.getSaveHandlers));
|
|
parcelHelpers.export(exports, "getWeightSpecs", ()=>(0, _ioUtils.getWeightSpecs));
|
|
parcelHelpers.export(exports, "http", ()=>(0, _http.http));
|
|
parcelHelpers.export(exports, "isHTTPScheme", ()=>(0, _http.isHTTPScheme));
|
|
parcelHelpers.export(exports, "loadWeights", ()=>(0, _weightsLoader.loadWeights));
|
|
parcelHelpers.export(exports, "registerLoadRouter", ()=>(0, _routerRegistry.registerLoadRouter));
|
|
parcelHelpers.export(exports, "registerSaveRouter", ()=>(0, _routerRegistry.registerSaveRouter));
|
|
parcelHelpers.export(exports, "weightsLoaderFactory", ()=>(0, _weightsLoader.weightsLoaderFactory));
|
|
parcelHelpers.export(exports, "withSaveHandler", ()=>(0, _passthrough.withSaveHandler));
|
|
parcelHelpers.export(exports, "withSaveHandlerSync", ()=>(0, _passthrough.withSaveHandlerSync));
|
|
var _indexedDb = require("./indexed_db");
|
|
var _localStorage = require("./local_storage");
|
|
var _browserFiles = require("./browser_files");
|
|
var _http = require("./http");
|
|
var _ioUtils = require("./io_utils");
|
|
var _passthrough = require("./passthrough");
|
|
var _routerRegistry = require("./router_registry");
|
|
var _weightsLoader = require("./weights_loader");
|
|
var _compositeArrayBuffer = require("./composite_array_buffer");
|
|
var _modelManagement = require("./model_management");
|
|
|
|
},{"./indexed_db":"aWBtv","./local_storage":"c3TPR","./browser_files":"ijOTx","./http":"aHrPE","./io_utils":"hW5iQ","./passthrough":"aUTFH","./router_registry":"btpsw","./weights_loader":"9BLSt","./composite_array_buffer":"gHH7C","./model_management":"iB0Mw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ijOTx":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "BrowserDownloads", ()=>BrowserDownloads);
|
|
parcelHelpers.export(exports, "browserDownloadsRouter", ()=>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
|
|
* }
|
|
*/ parcelHelpers.export(exports, "browserDownloads", ()=>browserDownloads);
|
|
/**
|
|
* 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
|
|
* }
|
|
*/ parcelHelpers.export(exports, "browserFiles", ()=>browserFiles);
|
|
var _flags = require("../flags");
|
|
var _environment = require("../environment");
|
|
var _ioUtils = require("./io_utils");
|
|
var _routerRegistry = require("./router_registry");
|
|
var _compositeArrayBuffer = require("./composite_array_buffer");
|
|
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 BrowserDownloads {
|
|
constructor(fileNamePrefix){
|
|
if (!(0, _environment.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(BrowserDownloads.URL_SCHEME)) fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length);
|
|
if (fileNamePrefix == null || fileNamePrefix.length === 0) fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;
|
|
this.modelJsonFileName = 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");
|
|
// TODO(mattsoulanille): Support saving models over 2GB that exceed
|
|
// Chrome's ArrayBuffer size limit.
|
|
const weightBuffer = (0, _compositeArrayBuffer.CompositeArrayBuffer).join(modelArtifacts.weightData);
|
|
const weightsURL = window.URL.createObjectURL(new Blob([
|
|
weightBuffer
|
|
], {
|
|
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 modelJSON = (0, _ioUtils.getModelJSONForModelArtifacts)(modelArtifacts, weightsManifest);
|
|
const modelJsonURL = window.URL.createObjectURL(new Blob([
|
|
JSON.stringify(modelJSON)
|
|
], {
|
|
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.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor;
|
|
jsonAnchor.download = this.modelJsonFileName;
|
|
jsonAnchor.href = modelJsonURL;
|
|
// 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: (0, _ioUtils.getModelArtifactsInfoForJSON)(modelArtifacts)
|
|
};
|
|
}
|
|
}
|
|
}
|
|
BrowserDownloads.URL_SCHEME = "downloads://";
|
|
class 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.jsonFile = files[0];
|
|
this.weightsFiles = files.slice(1);
|
|
}
|
|
async load() {
|
|
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 ${this.jsonFile.name}`));
|
|
return;
|
|
}
|
|
const weightsManifest = modelJSON.weightsManifest;
|
|
if (weightsManifest == null) {
|
|
reject(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));
|
|
return;
|
|
}
|
|
if (this.weightsFiles.length === 0) {
|
|
resolve({
|
|
modelTopology
|
|
});
|
|
return;
|
|
}
|
|
const modelArtifactsPromise = (0, _ioUtils.getModelArtifactsForJSON)(modelJSON, (weightsManifest)=>this.loadWeights(weightsManifest));
|
|
resolve(modelArtifactsPromise);
|
|
};
|
|
jsonReader.onerror = (error)=>reject(`Failed to read model topology and weights manifest JSON ` + `from file '${this.jsonFile.name}'. BrowserFiles supports loading ` + `Keras-style tf.Model artifacts only.`);
|
|
jsonReader.readAsText(this.jsonFile);
|
|
});
|
|
}
|
|
loadWeights(weightsManifest) {
|
|
const weightSpecs = [];
|
|
const paths = [];
|
|
for (const entry of weightsManifest){
|
|
weightSpecs.push(...entry.weights);
|
|
paths.push(...entry.paths);
|
|
}
|
|
const pathToFile = this.checkManifestAndWeightFiles(weightsManifest);
|
|
const promises = paths.map((path)=>this.loadWeightsFile(path, pathToFile[path]));
|
|
return Promise.all(promises).then((buffers)=>[
|
|
weightSpecs,
|
|
buffers
|
|
]);
|
|
}
|
|
loadWeightsFile(path, file) {
|
|
return new Promise((resolve, reject)=>{
|
|
const weightFileReader = new FileReader();
|
|
weightFileReader.onload = (event)=>{
|
|
// tslint:disable-next-line:no-any
|
|
const weightData = event.target.result;
|
|
resolve(weightData);
|
|
};
|
|
weightFileReader.onerror = (error)=>reject(`Failed to weights data from file of path '${path}'.`);
|
|
weightFileReader.readAsArrayBuffer(file);
|
|
});
|
|
}
|
|
/**
|
|
* Check the compatibility between weights manifest and weight files.
|
|
*/ checkManifestAndWeightFiles(manifest) {
|
|
const basenames = [];
|
|
const fileNames = this.weightsFiles.map((file)=>(0, _ioUtils.basename)(file.name));
|
|
const pathToFile = {};
|
|
for (const group of manifest)group.paths.forEach((path)=>{
|
|
const pathBasename = (0, _ioUtils.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] = this.weightsFiles[fileNames.indexOf(pathBasename)];
|
|
});
|
|
if (basenames.length !== this.weightsFiles.length) throw new Error(`Mismatch in the number of files in weights manifest ` + `(${basenames.length}) and the number of weight files provided ` + `(${this.weightsFiles.length}).`);
|
|
return pathToFile;
|
|
}
|
|
}
|
|
const browserDownloadsRouter = (url)=>{
|
|
if (!(0, _environment.env)().getBool("IS_BROWSER")) return null;
|
|
else {
|
|
if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));
|
|
else return null;
|
|
}
|
|
};
|
|
(0, _routerRegistry.IORouterRegistry).registerSaveRouter(browserDownloadsRouter);
|
|
function browserDownloads(fileNamePrefix = "model") {
|
|
return new BrowserDownloads(fileNamePrefix);
|
|
}
|
|
function browserFiles(files) {
|
|
return new BrowserFiles(files);
|
|
}
|
|
|
|
},{"../flags":"5yJGC","../environment":"dXmHm","./io_utils":"hW5iQ","./router_registry":"btpsw","./composite_array_buffer":"gHH7C","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aHrPE":[function(require,module,exports) {
|
|
/**
|
|
* @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).
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "HTTPRequest", ()=>HTTPRequest);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "parseUrl", ()=>parseUrl);
|
|
parcelHelpers.export(exports, "isHTTPScheme", ()=>isHTTPScheme);
|
|
parcelHelpers.export(exports, "httpRouter", ()=>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 reconstitutes 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
|
|
* }
|
|
*/ parcelHelpers.export(exports, "http", ()=>http);
|
|
/**
|
|
* Deprecated. Use `tf.io.http`.
|
|
* @param path
|
|
* @param loadOptions
|
|
*/ parcelHelpers.export(exports, "browserHTTPRequest", ()=>browserHTTPRequest);
|
|
var _environment = require("../environment");
|
|
var _util = require("../util");
|
|
var _ioUtils = require("./io_utils");
|
|
var _compositeArrayBuffer = require("./composite_array_buffer");
|
|
var _routerRegistry = require("./router_registry");
|
|
var _weightsLoader = require("./weights_loader");
|
|
const OCTET_STREAM_MIME_TYPE = "application/octet-stream";
|
|
const JSON_TYPE = "application/json";
|
|
class HTTPRequest {
|
|
constructor(path, loadOptions){
|
|
this.DEFAULT_METHOD = "POST";
|
|
if (loadOptions == null) loadOptions = {};
|
|
this.weightPathPrefix = loadOptions.weightPathPrefix;
|
|
this.weightUrlConverter = loadOptions.weightUrlConverter;
|
|
if (loadOptions.fetchFunc != null) {
|
|
(0, _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 = (0, _environment.env)().platform.fetch;
|
|
(0, _util.assert)(path != null && path.length > 0, ()=>"URL path for http must not be null, undefined or empty.");
|
|
if (Array.isArray(path)) (0, _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 || {};
|
|
this.loadOptions = loadOptions;
|
|
}
|
|
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 = (0, _ioUtils.getModelJSONForModelArtifacts)(modelArtifacts, weightsManifest);
|
|
init.body.append("model.json", new Blob([
|
|
JSON.stringify(modelTopologyAndWeightManifest)
|
|
], {
|
|
type: JSON_TYPE
|
|
}), "model.json");
|
|
if (modelArtifacts.weightData != null) {
|
|
// TODO(mattsoulanille): Support saving models over 2GB that exceed
|
|
// Chrome's ArrayBuffer size limit.
|
|
const weightBuffer = (0, _compositeArrayBuffer.CompositeArrayBuffer).join(modelArtifacts.weightData);
|
|
init.body.append("model.weights.bin", new Blob([
|
|
weightBuffer
|
|
], {
|
|
type: OCTET_STREAM_MIME_TYPE
|
|
}), "model.weights.bin");
|
|
}
|
|
const response = await this.fetch(this.path, init);
|
|
if (response.ok) return {
|
|
modelArtifactsInfo: (0, _ioUtils.getModelArtifactsInfoForJSON)(modelArtifacts),
|
|
responses: [
|
|
response
|
|
]
|
|
};
|
|
else throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ` + `${response.status}.`);
|
|
}
|
|
async loadModelJSON() {
|
|
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 modelJSON;
|
|
try {
|
|
modelJSON = 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);
|
|
}
|
|
// We do not allow both modelTopology and weightsManifest to be missing.
|
|
const modelTopology = modelJSON.modelTopology;
|
|
const weightsManifest = modelJSON.weightsManifest;
|
|
if (modelTopology == null && weightsManifest == null) throw new Error(`The JSON from HTTP path ${this.path} contains neither model ` + `topology or manifest for weights.`);
|
|
return modelJSON;
|
|
}
|
|
/**
|
|
* 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() {
|
|
if (this.loadOptions.streamWeights) return this.loadStream();
|
|
const modelJSON = await this.loadModelJSON();
|
|
return (0, _ioUtils.getModelArtifactsForJSON)(modelJSON, (weightsManifest)=>this.loadWeights(weightsManifest));
|
|
}
|
|
async loadStream() {
|
|
const modelJSON = await this.loadModelJSON();
|
|
const fetchURLs = await this.getWeightUrls(modelJSON.weightsManifest);
|
|
const weightSpecs = (0, _ioUtils.getWeightSpecs)(modelJSON.weightsManifest);
|
|
const stream = ()=>(0, _weightsLoader.streamWeights)(fetchURLs, this.loadOptions);
|
|
return Object.assign(Object.assign({}, modelJSON), {
|
|
weightSpecs,
|
|
getWeightStream: stream
|
|
});
|
|
}
|
|
async getWeightUrls(weightsManifest) {
|
|
const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;
|
|
const [prefix, suffix] = parseUrl(weightPath);
|
|
const pathPrefix = this.weightPathPrefix || prefix;
|
|
const fetchURLs = [];
|
|
const urlPromises = [];
|
|
for (const weightsGroup of weightsManifest){
|
|
for (const path of weightsGroup.paths)if (this.weightUrlConverter != null) urlPromises.push(this.weightUrlConverter(path));
|
|
else fetchURLs.push(pathPrefix + path + suffix);
|
|
}
|
|
if (this.weightUrlConverter) fetchURLs.push(...await Promise.all(urlPromises));
|
|
return fetchURLs;
|
|
}
|
|
async loadWeights(weightsManifest) {
|
|
const fetchURLs = await this.getWeightUrls(weightsManifest);
|
|
const weightSpecs = (0, _ioUtils.getWeightSpecs)(weightsManifest);
|
|
const buffers = await (0, _weightsLoader.loadWeightsAsArrayBuffer)(fetchURLs, this.loadOptions);
|
|
return [
|
|
weightSpecs,
|
|
buffers
|
|
];
|
|
}
|
|
}
|
|
HTTPRequest.URL_SCHEME_REGEX = /^https?:\/\//;
|
|
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(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;
|
|
};
|
|
(0, _routerRegistry.IORouterRegistry).registerSaveRouter(httpRouter);
|
|
(0, _routerRegistry.IORouterRegistry).registerLoadRouter(httpRouter);
|
|
function http(path, loadOptions) {
|
|
return new HTTPRequest(path, loadOptions);
|
|
}
|
|
function browserHTTPRequest(path, loadOptions) {
|
|
return http(path, loadOptions);
|
|
}
|
|
|
|
},{"../environment":"dXmHm","../util":"ctavo","./io_utils":"hW5iQ","./composite_array_buffer":"gHH7C","./router_registry":"btpsw","./weights_loader":"9BLSt","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9BLSt":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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`.
|
|
*/ parcelHelpers.export(exports, "loadWeightsAsArrayBuffer", ()=>loadWeightsAsArrayBuffer);
|
|
parcelHelpers.export(exports, "streamWeights", ()=>streamWeights);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "loadWeights", ()=>loadWeights);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "weightsLoaderFactory", ()=>weightsLoaderFactory);
|
|
var _environment = require("../environment");
|
|
var _util = require("../util");
|
|
var _compositeArrayBuffer = require("./composite_array_buffer");
|
|
var _ioUtils = require("./io_utils");
|
|
var _progress = require("./progress");
|
|
var _types = require("./types");
|
|
async function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) {
|
|
if (loadOptions == null) loadOptions = {};
|
|
const fetchFunc = loadOptions.fetchFunc == null ? (0, _environment.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 (0, _progress.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 (0, _progress.monitorPromisesProgress)(bufferPromises, loadOptions.onProgress, bufferStartFraction, bufferEndFraction);
|
|
return buffers;
|
|
}
|
|
function streamWeights(fetchURLs, loadOptions) {
|
|
var _a;
|
|
const fetchFunc = loadOptions.fetchFunc == null ? (0, _environment.env)().platform.fetch : loadOptions.fetchFunc;
|
|
let fetchIndex = 0;
|
|
let chunkReader;
|
|
(_a = loadOptions.onProgress) === null || _a === void 0 || _a.call(loadOptions, 0);
|
|
return new ReadableStream({
|
|
pull: async (controller)=>{
|
|
var _a;
|
|
while(fetchIndex < fetchURLs.length){
|
|
if (!chunkReader) {
|
|
const body = (await fetchFunc(fetchURLs[fetchIndex], loadOptions.requestInit, {
|
|
isBinary: true
|
|
})).body;
|
|
chunkReader = body.getReader();
|
|
}
|
|
const { done, value } = await chunkReader.read();
|
|
if (done) {
|
|
fetchIndex++;
|
|
chunkReader = undefined;
|
|
(_a = loadOptions.onProgress) === null || _a === void 0 || _a.call(loadOptions, fetchIndex / fetchURLs.length);
|
|
continue;
|
|
}
|
|
controller.enqueue(value);
|
|
return;
|
|
}
|
|
controller.close();
|
|
}
|
|
});
|
|
}
|
|
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);
|
|
}
|
|
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 = (0, _types.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;
|
|
const weightsBuffer = new (0, _compositeArrayBuffer.CompositeArrayBuffer)(buffers.slice(bufferIndexOffset, bufferIndexOffset + numBuffers));
|
|
const weightsEntries = groupWeightsToFetch[i];
|
|
weightsEntries.forEach((weightsEntry)=>{
|
|
const byteBuffer = weightsBuffer.slice(weightsEntry.groupOffset, weightsEntry.groupOffset + weightsEntry.sizeBytes);
|
|
const nameToTensorMap = (0, _ioUtils.decodeWeights)(byteBuffer, [
|
|
weightsEntry.manifestEntry
|
|
]);
|
|
for(const name in nameToTensorMap)weightsTensorMap[name] = nameToTensorMap[name];
|
|
});
|
|
bufferIndexOffset += numBuffers;
|
|
});
|
|
return weightsTensorMap;
|
|
};
|
|
}
|
|
|
|
},{"../environment":"dXmHm","../util":"ctavo","./composite_array_buffer":"gHH7C","./io_utils":"hW5iQ","./progress":"O6WSZ","./types":"ixgVc","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"O6WSZ":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "monitorPromisesProgress", ()=>monitorPromisesProgress);
|
|
var _util = require("../util");
|
|
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) {
|
|
(0, _util.assert)(promises != null && Array.isArray(promises) && promises.length > 0, ()=>"promises must be a none empty array");
|
|
}
|
|
function checkFraction(startFraction, endFraction) {
|
|
(0, _util.assert)(startFraction >= 0 && startFraction <= 1, ()=>`Progress fraction must be in range [0, 1], but ` + `got startFraction ${startFraction}`);
|
|
(0, _util.assert)(endFraction >= 0 && endFraction <= 1, ()=>`Progress fraction must be in range [0, 1], but ` + `got endFraction ${endFraction}`);
|
|
(0, _util.assert)(endFraction >= startFraction, ()=>`startFraction must be no more than endFraction, but ` + `got startFraction ${startFraction} and endFraction ` + `${endFraction}`);
|
|
}
|
|
return Promise.all(promises.map(registerMonitor));
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aUTFH":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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. Optional.
|
|
* @param weightData A single `ArrayBuffer` containing the weight data,
|
|
* concatenated in the order described by the weightSpecs. Optional.
|
|
* @param trainingConfig Model training configuration. Optional.
|
|
*
|
|
* @returns A passthrough `IOHandler` that simply loads the provided data.
|
|
*/ parcelHelpers.export(exports, "fromMemory", ()=>fromMemory);
|
|
/**
|
|
* 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. Optional.
|
|
* @param weightData A single `ArrayBuffer` containing the weight data,
|
|
* concatenated in the order described by the weightSpecs. Optional.
|
|
* @param trainingConfig Model training configuration. Optional.
|
|
*
|
|
* @returns A passthrough `IOHandlerSync` that simply loads the provided data.
|
|
*/ parcelHelpers.export(exports, "fromMemorySync", ()=>fromMemorySync);
|
|
/**
|
|
* 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
|
|
* promise that resolves to a `SaveResult`.
|
|
*/ parcelHelpers.export(exports, "withSaveHandler", ()=>withSaveHandler);
|
|
/**
|
|
* Creates an IOHandlerSync 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`.
|
|
*/ parcelHelpers.export(exports, "withSaveHandlerSync", ()=>withSaveHandlerSync);
|
|
class PassthroughLoader {
|
|
constructor(modelArtifacts){
|
|
this.modelArtifacts = modelArtifacts;
|
|
}
|
|
load() {
|
|
return this.modelArtifacts;
|
|
}
|
|
}
|
|
class PassthroughSaver {
|
|
constructor(saveHandler){
|
|
this.saveHandler = saveHandler;
|
|
}
|
|
save(modelArtifacts) {
|
|
return this.saveHandler(modelArtifacts);
|
|
}
|
|
}
|
|
class PassthroughAsync {
|
|
constructor(handler){
|
|
if (handler.load) this.load = ()=>Promise.resolve(handler.load());
|
|
if (handler.save) this.save = (modelArtifacts)=>Promise.resolve(handler.save(modelArtifacts));
|
|
}
|
|
}
|
|
function fromMemory(modelArtifacts, weightSpecs, weightData, trainingConfig) {
|
|
const args = arguments;
|
|
return new PassthroughAsync(fromMemorySync(...args));
|
|
}
|
|
function fromMemorySync(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
|
|
});
|
|
}
|
|
}
|
|
function withSaveHandler(saveHandler) {
|
|
return new PassthroughSaver(saveHandler);
|
|
}
|
|
function withSaveHandlerSync(saveHandler) {
|
|
return new PassthroughSaver(saveHandler);
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8ony7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ /**
|
|
* Exports under the tf.math.* namespace.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "confusionMatrix", ()=>(0, _confusionMatrix.confusionMatrix));
|
|
var _confusionMatrix = require("./ops/confusion_matrix");
|
|
|
|
},{"./ops/confusion_matrix":"fAWJm","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fAWJm":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "confusionMatrix_", ()=>confusionMatrix_);
|
|
parcelHelpers.export(exports, "confusionMatrix", ()=>confusionMatrix);
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _util = require("../util");
|
|
var _cast = require("./cast");
|
|
var _matMul = require("./mat_mul");
|
|
var _oneHot = require("./one_hot");
|
|
var _operation = require("./operation");
|
|
var _transpose = require("./transpose");
|
|
function confusionMatrix_(labels, predictions, numClasses) {
|
|
const $labels = (0, _tensorUtilEnv.convertToTensor)(labels, "labels", "confusionMatrix");
|
|
const $predictions = (0, _tensorUtilEnv.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 = (0, _oneHot.oneHot)((0, _cast.cast)($labels, "int32"), numClasses);
|
|
const oneHotPredictions = (0, _oneHot.oneHot)((0, _cast.cast)($predictions, "int32"), numClasses);
|
|
const oneHotLabelsT = (0, _transpose.transpose)(oneHotLabels);
|
|
const product = (0, _matMul.matMul)(oneHotLabelsT, oneHotPredictions);
|
|
return (0, _cast.cast)(product, "int32");
|
|
}
|
|
const confusionMatrix = /* @__PURE__ */ (0, _operation.op)({
|
|
confusionMatrix_
|
|
});
|
|
|
|
},{"../tensor_util_env":"6vfHI","../util":"ctavo","./cast":"b4VDA","./mat_mul":"fiMp4","./one_hot":"91jNM","./operation":"ip64W","./transpose":"2bqbS","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iaaSH":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Creates a `tf.Tensor` from an image in async way.
|
|
*
|
|
* ```js
|
|
* const image = new ImageData(1, 1);
|
|
* image.data[0] = 100;
|
|
* image.data[1] = 150;
|
|
* image.data[2] = 200;
|
|
* image.data[3] = 255;
|
|
*
|
|
* (await tf.browser.fromPixelsAsync(image)).print();
|
|
* ```
|
|
* This API is the async version of fromPixels. The API will first
|
|
* check |WRAP_TO_IMAGEBITMAP| flag, and try to wrap the input to
|
|
* imageBitmap if the flag is set to true.
|
|
*
|
|
* @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}
|
|
*/ parcelHelpers.export(exports, "fromPixelsAsync", ()=>fromPixelsAsync);
|
|
/**
|
|
* 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 tensor with shape `[height, width]`, or a rank-3 tensor
|
|
* of shape `[height, width, numChannels]`. 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'}
|
|
*/ parcelHelpers.export(exports, "toPixels", ()=>toPixels);
|
|
/**
|
|
* Draws a `tf.Tensor` to 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].
|
|
*
|
|
* @param image The tensor to draw on the canvas. Must match one of
|
|
* these shapes:
|
|
* - Rank-2 with shape `[height, width`]: Drawn as grayscale.
|
|
* - Rank-3 with shape `[height, width, 1]`: Drawn as grayscale.
|
|
* - Rank-3 with shape `[height, width, 3]`: Drawn as RGB with alpha set in
|
|
* `imageOptions` (defaults to 1, which is opaque).
|
|
* - Rank-3 with shape `[height, width, 4]`: Drawn as RGBA.
|
|
* @param canvas The canvas to draw to.
|
|
* @param options The configuration arguments for image to be drawn and the
|
|
* canvas to draw to.
|
|
*
|
|
* @doc {heading: 'Browser', namespace: 'browser'}
|
|
*/ parcelHelpers.export(exports, "draw", ()=>draw);
|
|
parcelHelpers.export(exports, "fromPixels", ()=>fromPixels);
|
|
var _engine = require("../engine");
|
|
var _environment = require("../environment");
|
|
var _kernelNames = require("../kernel_names");
|
|
var _kernelRegistry = require("../kernel_registry");
|
|
var _tensor = require("../tensor");
|
|
var _tensorUtilEnv = require("../tensor_util_env");
|
|
var _cast = require("./cast");
|
|
var _operation = require("./operation");
|
|
var _tensor3D = require("./tensor3d");
|
|
let fromPixels2DContext;
|
|
let hasToPixelsWarned = false;
|
|
/**
|
|
* 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).
|
|
*
|
|
* @returns A Tensor3D with the shape `[height, width, numChannels]`.
|
|
*
|
|
* Note: fromPixels can be lossy in some cases, same image may result in
|
|
* slightly different tensor values, if rendered by different rendering
|
|
* engines. This means that results from different browsers, or even same
|
|
* browser with CPU and GPU rendering engines can be different. See discussion
|
|
* in details:
|
|
* https://github.com/tensorflow/tfjs/issues/5482
|
|
*
|
|
* @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;
|
|
let isImageBitmap = 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;
|
|
else if (pixels.getContext != null) isCanvasLike = true;
|
|
else if (typeof ImageBitmap !== "undefined" && pixels instanceof ImageBitmap) isImageBitmap = 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 the current backend has 'FromPixels' registered, it has a more
|
|
// efficient way of handling pixel uploads, so we call that.
|
|
const kernel = (0, _kernelRegistry.getKernel)((0, _kernelNames.FromPixels), (0, _engine.ENGINE).backendName);
|
|
if (kernel != null) {
|
|
const inputs = {
|
|
pixels
|
|
};
|
|
const attrs = {
|
|
numChannels
|
|
};
|
|
return (0, _engine.ENGINE).runKernel((0, _kernelNames.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 || isImageBitmap) {
|
|
if (fromPixels2DContext == null) {
|
|
if (typeof document === "undefined") {
|
|
if (typeof OffscreenCanvas !== "undefined" && typeof OffscreenCanvasRenderingContext2D !== "undefined") // @ts-ignore
|
|
fromPixels2DContext = new OffscreenCanvas(1, 1).getContext("2d");
|
|
else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");
|
|
} else fromPixels2DContext = document.createElement("canvas").getContext("2d", {
|
|
willReadFrequently: true
|
|
});
|
|
}
|
|
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 (0, _tensor3D.tensor3d)(values, outShape, "int32");
|
|
}
|
|
// Helper functions for |fromPixelsAsync| to check whether the input can
|
|
// be wrapped into imageBitmap.
|
|
function isPixelData(pixels) {
|
|
return pixels != null && pixels.data instanceof Uint8Array;
|
|
}
|
|
function isImageBitmapFullySupported() {
|
|
return typeof window !== "undefined" && typeof ImageBitmap !== "undefined" && window.hasOwnProperty("createImageBitmap");
|
|
}
|
|
function isNonEmptyPixels(pixels) {
|
|
return pixels != null && pixels.width !== 0 && pixels.height !== 0;
|
|
}
|
|
function canWrapPixelsToImageBitmap(pixels) {
|
|
return isImageBitmapFullySupported() && !(pixels instanceof ImageBitmap) && isNonEmptyPixels(pixels) && !isPixelData(pixels);
|
|
}
|
|
async function fromPixelsAsync(pixels, numChannels = 3) {
|
|
let inputs = null;
|
|
// Check whether the backend needs to wrap |pixels| to imageBitmap and
|
|
// whether |pixels| can be wrapped to imageBitmap.
|
|
if ((0, _environment.env)().getBool("WRAP_TO_IMAGEBITMAP") && canWrapPixelsToImageBitmap(pixels)) {
|
|
// Force the imageBitmap creation to not do any premultiply alpha
|
|
// ops.
|
|
let imageBitmap;
|
|
try {
|
|
// wrap in try-catch block, because createImageBitmap may not work
|
|
// properly in some browsers, e.g.
|
|
// https://bugzilla.mozilla.org/show_bug.cgi?id=1335594
|
|
// tslint:disable-next-line: no-any
|
|
imageBitmap = await createImageBitmap(pixels, {
|
|
premultiplyAlpha: "none"
|
|
});
|
|
} catch (e) {
|
|
imageBitmap = null;
|
|
}
|
|
// createImageBitmap will clip the source size.
|
|
// In some cases, the input will have larger size than its content.
|
|
// E.g. new Image(10, 10) but with 1 x 1 content. Using
|
|
// createImageBitmap will clip the size from 10 x 10 to 1 x 1, which
|
|
// is not correct. We should avoid wrapping such resouce to
|
|
// imageBitmap.
|
|
if (imageBitmap != null && imageBitmap.width === pixels.width && imageBitmap.height === pixels.height) inputs = imageBitmap;
|
|
else inputs = pixels;
|
|
} else inputs = pixels;
|
|
return fromPixels_(inputs, numChannels);
|
|
}
|
|
function validateImgTensor(img) {
|
|
if (img.rank !== 2 && img.rank !== 3) throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${img.rank}.`);
|
|
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}`);
|
|
if (img.dtype !== "float32" && img.dtype !== "int32") throw new Error(`Unsupported type for toPixels: ${img.dtype}.` + ` Please use float32 or int32 tensors.`);
|
|
}
|
|
function validateImageOptions(imageOptions) {
|
|
const alpha = (imageOptions === null || imageOptions === void 0 ? void 0 : imageOptions.alpha) || 1;
|
|
if (alpha > 1 || alpha < 0) throw new Error(`Alpha value ${alpha} is suppoed to be in range [0 - 1].`);
|
|
}
|
|
async function toPixels(img, canvas) {
|
|
let $img = (0, _tensorUtilEnv.convertToTensor)(img, "img", "toPixels");
|
|
if (!(img instanceof (0, _tensor.Tensor))) {
|
|
// Assume int32 if user passed a native array.
|
|
const originalImgTensor = $img;
|
|
$img = (0, _cast.cast)(originalImgTensor, "int32");
|
|
originalImgTensor.dispose();
|
|
}
|
|
validateImgTensor($img);
|
|
const [height, width] = $img.shape.slice(0, 2);
|
|
const depth = $img.rank === 2 ? 1 : $img.shape[2];
|
|
const data = await $img.data();
|
|
const multiplier = $img.dtype === "float32" ? 255 : 1;
|
|
const bytes = new Uint8ClampedArray(width * height * 4);
|
|
for(let i = 0; i < height * width; ++i){
|
|
const rgba = [
|
|
0,
|
|
0,
|
|
0,
|
|
255
|
|
];
|
|
for(let d = 0; d < depth; d++){
|
|
const value = data[i * depth + d];
|
|
if ($img.dtype === "float32") {
|
|
if (value < 0 || value > 1) throw new Error(`Tensor values for a float32 Tensor must be in the ` + `range [0 - 1] but encountered ${value}.`);
|
|
} else if ($img.dtype === "int32") {
|
|
if (value < 0 || value > 255) throw new Error(`Tensor values for a int32 Tensor must be in the ` + `range [0 - 255] but encountered ${value}.`);
|
|
}
|
|
if (depth === 1) {
|
|
rgba[0] = value * multiplier;
|
|
rgba[1] = value * multiplier;
|
|
rgba[2] = value * multiplier;
|
|
} else rgba[d] = value * multiplier;
|
|
}
|
|
const j = i * 4;
|
|
bytes[j + 0] = Math.round(rgba[0]);
|
|
bytes[j + 1] = Math.round(rgba[1]);
|
|
bytes[j + 2] = Math.round(rgba[2]);
|
|
bytes[j + 3] = Math.round(rgba[3]);
|
|
}
|
|
if (canvas != null) {
|
|
if (!hasToPixelsWarned) {
|
|
const kernel = (0, _kernelRegistry.getKernel)((0, _kernelNames.Draw), (0, _engine.ENGINE).backendName);
|
|
if (kernel != null) {
|
|
console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead.");
|
|
hasToPixelsWarned = true;
|
|
}
|
|
}
|
|
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;
|
|
}
|
|
function draw(image, canvas, options) {
|
|
let $img = (0, _tensorUtilEnv.convertToTensor)(image, "img", "draw");
|
|
if (!(image instanceof (0, _tensor.Tensor))) {
|
|
// Assume int32 if user passed a native array.
|
|
const originalImgTensor = $img;
|
|
$img = (0, _cast.cast)(originalImgTensor, "int32");
|
|
originalImgTensor.dispose();
|
|
}
|
|
validateImgTensor($img);
|
|
validateImageOptions(options === null || options === void 0 ? void 0 : options.imageOptions);
|
|
const inputs = {
|
|
image: $img
|
|
};
|
|
const attrs = {
|
|
canvas,
|
|
options
|
|
};
|
|
(0, _engine.ENGINE).runKernel((0, _kernelNames.Draw), inputs, attrs);
|
|
}
|
|
const fromPixels = /* @__PURE__ */ (0, _operation.op)({
|
|
fromPixels_
|
|
});
|
|
|
|
},{"../engine":"1g2qo","../environment":"dXmHm","../kernel_names":"hniYO","../kernel_registry":"aG7g9","../tensor":"cJNoh","../tensor_util_env":"6vfHI","./cast":"b4VDA","./operation":"ip64W","./tensor3d":"lVDsd","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4RUOy":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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]
|
|
*/ parcelHelpers.export(exports, "prepareAndValidate", ()=>prepareAndValidate);
|
|
var _util = require("../util");
|
|
function prepareAndValidate(tensor, indices) {
|
|
const tensorRank = tensor.shape.length;
|
|
const indicesRank = indices.shape.length;
|
|
if (tensorRank < 1) throw new Error("tf.gatherND() expects the input to be rank 1 or higher," + ` but the rank was ${tensorRank}.`);
|
|
if (indicesRank < 1) throw new Error("tf.gatherND() expects the indices to be rank 1 or higher," + ` but the rank was ${indicesRank}.`);
|
|
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[indicesRank - 1] > tensorRank) throw new Error("index innermost dimension length must be <= tensor rank; saw: " + `${indices.shape[indicesRank - 1]} vs. ${tensorRank}`);
|
|
if ((0, _util.sizeFromShape)(tensor.shape) === 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 < tensorRank; ++i){
|
|
sliceSize *= inputShape[i];
|
|
resultShape.push(inputShape[i]);
|
|
}
|
|
const strides = [
|
|
...(0, _util.computeStrides)(tensor.shape).map((stride)=>stride / sliceSize),
|
|
1
|
|
].slice(0, sliceRank);
|
|
return [
|
|
resultShape,
|
|
nResult,
|
|
sliceSize,
|
|
strides
|
|
];
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3A9Ql":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "assertParamsValid", ()=>assertParamsValid);
|
|
/** Converts a binary mask to an array of axes. Used in stridedSlice(). */ parcelHelpers.export(exports, "maskToAxes", ()=>maskToAxes);
|
|
/** Computes the output shape given the strided slice params. */ parcelHelpers.export(exports, "computeOutShape", ()=>computeOutShape);
|
|
// Creates full selection at the elided dimensions. If the dimension matches
|
|
// the ellipsis mask, override the current stride value. Otherwise, insert.
|
|
parcelHelpers.export(exports, "stridesWithElidedDims", ()=>stridesWithElidedDims);
|
|
// Normalize the start, end and strides.
|
|
parcelHelpers.export(exports, "getNormalizedAxes", ()=>getNormalizedAxes);
|
|
// Creates full selection at the elided dimensions. If the dimension matches
|
|
// the ellipsis mask, override the current start value. Otherwise, insert.
|
|
parcelHelpers.export(exports, "startIndicesWithElidedDims", ()=>startIndicesWithElidedDims);
|
|
// Creates full selection at the elided dimensions. If the dimension matches
|
|
// the ellipsis mask, override the current stop value. Otherwise, insert.
|
|
parcelHelpers.export(exports, "stopIndicesWithElidedDims", ()=>stopIndicesWithElidedDims);
|
|
parcelHelpers.export(exports, "stridesForAxis", ()=>stridesForAxis);
|
|
parcelHelpers.export(exports, "startForAxis", ()=>startForAxis);
|
|
parcelHelpers.export(exports, "stopForAxis", ()=>stopForAxis);
|
|
/**
|
|
* Returns true if the slice occupies a continous set of elements in the
|
|
* 'flat' space.
|
|
*/ parcelHelpers.export(exports, "isSliceContinous", ()=>isSliceContinous);
|
|
parcelHelpers.export(exports, "computeFlatOffset", ()=>computeFlatOffset);
|
|
parcelHelpers.export(exports, "parseSliceParams", ()=>parseSliceParams);
|
|
// Convert the slicing specification from a sparse representation to a dense
|
|
// representation. This means that all ellipses and newaxis are expanded out.
|
|
parcelHelpers.export(exports, "sliceInfo", ()=>sliceInfo);
|
|
var _util = require("../util");
|
|
const NEW_AXIS = -2;
|
|
const SHRINK_AXIS = -1;
|
|
function assertParamsValid(input, begin, size) {
|
|
const inputRank = input.shape.length;
|
|
_util.assert(inputRank === begin.length, ()=>`Error in slice${inputRank}D: Length of begin ${begin} must ` + `match the rank of the array (${inputRank}).`);
|
|
_util.assert(inputRank === size.length, ()=>`Error in slice${inputRank}D: Length of size ${size} must ` + `match the rank of the array (${inputRank}).`);
|
|
for(let i = 0; i < inputRank; ++i)_util.assert(begin[i] + size[i] <= input.shape[i], ()=>`Error in slice${inputRank}D: begin[${i}] + size[${i}] ` + `(${begin[i] + size[i]}) would overflow input.shape[${i}] (${input.shape[i]})`);
|
|
}
|
|
function maskToAxes(mask) {
|
|
const axes = [];
|
|
let axis = 0;
|
|
while(mask > 0){
|
|
if (mask & 1) axes.push(axis);
|
|
mask /= 2;
|
|
axis++;
|
|
}
|
|
return axes;
|
|
}
|
|
function 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;
|
|
}
|
|
function stridesWithElidedDims(strides, ellipsisInsertionIndex, numElidedAxes, inputShape) {
|
|
const newStrides = [
|
|
...strides
|
|
];
|
|
for(let i = newStrides.length; i < inputShape.length; i++)newStrides.push(1);
|
|
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;
|
|
}
|
|
function unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, normalizedAxis) {
|
|
if (normalizedAxis <= ellipsisInsertionIndex) return normalizedAxis;
|
|
return normalizedAxis - (numElidedAxes - 1);
|
|
}
|
|
function getElidedAxes(numElidedAxes, ellipsisInsertionIndex) {
|
|
const elidedAxes = [];
|
|
for(let i = 0; i < numElidedAxes; i++)elidedAxes.push(ellipsisInsertionIndex + i);
|
|
return elidedAxes;
|
|
}
|
|
function getNormalizedAxes(inputShape, ellipsisAxes, numInterpolatedAxes, begin, end, strides, beginMask, endMask, ellipsisMask) {
|
|
const inputRank = inputShape.length;
|
|
let normalizedBegin = new Array(inputRank), normalizedEnd = new Array(inputRank), normalizedStrides = new Array(inputRank);
|
|
if (ellipsisAxes.length && numInterpolatedAxes > 0) {
|
|
const fullIndex = ellipsisAxes[0];
|
|
// The ellipsis applies to the masked index as well as any dimensions
|
|
// that are interpolated.
|
|
const numElidedAxes = numInterpolatedAxes + 1;
|
|
normalizedBegin = startIndicesWithElidedDims(beginMask, fullIndex, numElidedAxes, begin, inputShape);
|
|
normalizedEnd = stopIndicesWithElidedDims(endMask, fullIndex, numElidedAxes, end, inputShape);
|
|
normalizedStrides = stridesWithElidedDims(strides, fullIndex, numElidedAxes, inputShape);
|
|
} else for(let axis = 0; axis < inputRank; axis++){
|
|
normalizedBegin[axis] = startForAxis(beginMask, begin, strides, inputShape, axis, ellipsisMask);
|
|
normalizedEnd[axis] = stopForAxis(endMask, end, strides, inputShape, axis, ellipsisMask);
|
|
normalizedStrides[axis] = stridesForAxis(strides, axis, ellipsisMask);
|
|
}
|
|
return {
|
|
begin: normalizedBegin,
|
|
end: normalizedEnd,
|
|
strides: normalizedStrides
|
|
};
|
|
}
|
|
function startIndicesWithElidedDims(beginMask, ellipsisInsertionIndex, numElidedAxes, originalBegin, inputShape) {
|
|
const newIndices = [
|
|
...inputShape
|
|
];
|
|
const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
|
|
for(let axis = 0; axis < newIndices.length; axis++)if (elidedAxes.indexOf(axis) > -1) newIndices[axis] = 0;
|
|
else {
|
|
const originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
|
|
let originalValue = originalBegin[originalAxis];
|
|
if (beginMask & 1 << originalAxis) originalValue = 0;
|
|
newIndices[axis] = originalValue;
|
|
}
|
|
return newIndices;
|
|
}
|
|
function stopIndicesWithElidedDims(endMask, ellipsisInsertionIndex, numElidedAxes, originalEnd, inputShape) {
|
|
const newIndices = [
|
|
...inputShape
|
|
];
|
|
const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
|
|
for(let axis = 0; axis < newIndices.length; axis++)if (elidedAxes.indexOf(axis) > -1) newIndices[axis] = Number.MAX_SAFE_INTEGER;
|
|
else {
|
|
const originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
|
|
let originalValue = originalEnd[originalAxis];
|
|
if (endMask & 1 << originalAxis) originalValue = Number.MAX_SAFE_INTEGER;
|
|
newIndices[axis] = originalValue;
|
|
}
|
|
for(let i = 0; i < newIndices.length; i++){
|
|
// Handle negative indices
|
|
const axisSize = inputShape[i];
|
|
if (newIndices[i] < 0) newIndices[i] += axisSize;
|
|
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;
|
|
}
|
|
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;
|
|
}
|
|
function parseSliceParams(x, begin, size) {
|
|
// The following logic allows for more ergonomic calls.
|
|
let begin_;
|
|
const xRank = x.shape.length;
|
|
if (typeof begin === "number") begin_ = [
|
|
begin,
|
|
...new Array(xRank - 1).fill(0)
|
|
];
|
|
else if (begin.length < xRank) begin_ = begin.concat(new Array(xRank - 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(xRank).fill(-1);
|
|
else if (typeof size === "number") size_ = [
|
|
size,
|
|
...new Array(xRank - 1).fill(-1)
|
|
];
|
|
else if (size.length < xRank) size_ = size.concat(new Array(xRank - 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];
|
|
}
|
|
});
|
|
return [
|
|
begin_,
|
|
size_
|
|
];
|
|
}
|
|
function sliceInfo(xShape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
|
|
let stridesNonNull;
|
|
if (strides == null) {
|
|
stridesNonNull = new Array(begin.length);
|
|
stridesNonNull.fill(1);
|
|
} else stridesNonNull = strides;
|
|
// Only one non-zero bit is allowed in ellipsisMask, which means ellipsisMask
|
|
// is a power of 2. Use bit compares to ensure ellipsisMask is 0 or a power
|
|
// of 2. When i is a power of 2, i & (i - 1) is always 0.
|
|
// Also ref:
|
|
// https://stackoverflow.com/questions/600293/how-to-check-if-a-number-is-a-power-of-2
|
|
if (ellipsisMask != null && (ellipsisMask & ellipsisMask - 1) !== 0) throw new Error("Multiple ellipses in slice is not allowed.");
|
|
// Step 1: Account for ellipsis and new axis.
|
|
// Check for ellipsis and count how many non-newaxis there are after.
|
|
let ellipsisSeen = false;
|
|
const sparseSpec = {
|
|
dims: stridesNonNull.length,
|
|
numAddAxisAfterEllipsis: 0,
|
|
begin: begin.slice(),
|
|
end: end.slice(),
|
|
strides: stridesNonNull.slice(),
|
|
beginMask,
|
|
endMask,
|
|
ellipsisMask,
|
|
newAxisMask,
|
|
shrinkAxisMask
|
|
};
|
|
for(let i = 0; i < sparseSpec.dims; i++){
|
|
if (ellipsisSeen && (1 << i & newAxisMask) !== 0) sparseSpec.numAddAxisAfterEllipsis++;
|
|
if (1 << i & ellipsisMask) ellipsisSeen = true;
|
|
}
|
|
// If no ellipsis insert one at the end.
|
|
if (!ellipsisSeen) {
|
|
sparseSpec.ellipsisMask |= 1 << sparseSpec.dims;
|
|
sparseSpec.dims++; // this effects loop iteration below
|
|
}
|
|
// Step 2: Make a sparse spec into a full index spec.
|
|
//
|
|
// The sparse spec deos not correspond to the number of dimensions.
|
|
// Make a dense spec that cooresponds to the number of dimensions.
|
|
//
|
|
// For example suppose foo[...,3:] on foo.shape = [2, 2, 3] then we need to
|
|
// produce the missing beginMask for the first two dimensions i.e. from
|
|
// beginMaskSpec = 0, endMaskSpec = 2, we achieve beginMask = 6 (110),
|
|
// endMask = 7 (111).
|
|
const denseSpec = {
|
|
dims: xShape.length,
|
|
beginMask: 0,
|
|
endMask: 0,
|
|
beginValid: false,
|
|
endValid: false
|
|
};
|
|
buildDenseSpec(sparseSpec, denseSpec);
|
|
// Step 3: Make implicit ranges (non-zero beginMasks and endMasks) explicit
|
|
// and bounds check.
|
|
let isIdentity = true;
|
|
let sliceDim0 = true;
|
|
let isSimpleSlice = true;
|
|
const processingShape = [];
|
|
const finalShape = [];
|
|
for(let i = 0; i < xShape.length; ++i){
|
|
if (denseSpec.strides[i] === 0) throw Error(`strides[${i}] must be non-zero`);
|
|
const shrinkI = !!(denseSpec.shrinkAxisMask & 1 << i);
|
|
const dimI = xShape[i];
|
|
if (dimI === -1) {
|
|
processingShape.push(shrinkI ? 1 : -1);
|
|
continue;
|
|
}
|
|
const masks = [
|
|
denseSpec.beginMask & 1 << i,
|
|
denseSpec.endMask & 1 << i
|
|
];
|
|
const validRange = [
|
|
denseSpec.strides[i] > 0 ? 0 : -1,
|
|
denseSpec.strides[i] > 0 ? dimI : dimI - 1
|
|
];
|
|
if (shrinkI && denseSpec.strides[i] <= 0) throw Error("only stride 1 allowed on non-range indexing.");
|
|
isSimpleSlice = isSimpleSlice && denseSpec.strides[i] === 1;
|
|
const beginAndEndMasked = !!(denseSpec.beginMask & 1 << i && denseSpec.endMask & 1 << i);
|
|
if (denseSpec.beginValid && denseSpec.endValid) {
|
|
if (shrinkI) {
|
|
// If we are shrinking, the end index is now possibly incorrect. In
|
|
// particular foo[-1] produces sparseBegin = -1, sparseEnd = 0.
|
|
// and canonical puts these to n-1 and 0, which implies a degenerate
|
|
// interval. Fortunately, it is now safe to re-create end as begin + 1.
|
|
const xFwd = denseSpec.begin[i] < 0 ? dimI + denseSpec.begin[i] : denseSpec.begin[i];
|
|
denseSpec.begin[i] = xFwd;
|
|
denseSpec.end[i] = denseSpec.begin[i] + 1;
|
|
if (xFwd < 0 || xFwd >= dimI) throw Error(`slice index ${denseSpec.begin[i]} of dimension ${i} out of bounds.`);
|
|
} else {
|
|
denseSpec.begin[i] = canonical(denseSpec.begin[i], 0, denseSpec.strides[i], dimI, masks, validRange);
|
|
denseSpec.end[i] = canonical(denseSpec.end[i], 1, denseSpec.strides[i], dimI, masks, validRange);
|
|
}
|
|
// Update optimization values
|
|
const takeAllInDimension = denseSpec.strides[i] === 1 && denseSpec.begin[i] === 0 && denseSpec.end[i] === dimI;
|
|
isIdentity = isIdentity && takeAllInDimension;
|
|
sliceDim0 = sliceDim0 && (i === 0 && denseSpec.strides[i] === 1 || takeAllInDimension);
|
|
} else {
|
|
isIdentity = isIdentity && denseSpec.strides[i] === 1 && beginAndEndMasked;
|
|
sliceDim0 = sliceDim0 && (i === 0 && denseSpec.strides[i] === 1 || beginAndEndMasked);
|
|
}
|
|
// Compute the processing shape (the intermediate Eigen will produce)
|
|
let intervalLength;
|
|
let knownInterval = false;
|
|
if (denseSpec.beginValid && denseSpec.endValid) {
|
|
intervalLength = denseSpec.end[i] - denseSpec.begin[i];
|
|
knownInterval = true;
|
|
} else if (shrinkI) {
|
|
// The dimension is still known as 1 for the processingShape, but will be
|
|
// discarded for the final shape.
|
|
intervalLength = 1;
|
|
knownInterval = true;
|
|
} else if (beginAndEndMasked) // Even if we don't have values for begin or end, we do know that this
|
|
// dimension covers the whole interval. If we have shape information for
|
|
// this dimension, that tells us the interval length.
|
|
{
|
|
if (dimI >= 0) {
|
|
if (denseSpec.strides[i] < 0) intervalLength = -dimI;
|
|
else intervalLength = dimI;
|
|
knownInterval = true;
|
|
}
|
|
}
|
|
if (knownInterval) {
|
|
let sizeI;
|
|
// Hold zero if the interval is degenerate, otherwise account for
|
|
// remainder
|
|
if (intervalLength === 0 || intervalLength < 0 !== denseSpec.strides[i] < 0) sizeI = 0;
|
|
else sizeI = Math.trunc(intervalLength / denseSpec.strides[i]) + (intervalLength % denseSpec.strides[i] !== 0 ? 1 : 0);
|
|
processingShape.push(sizeI);
|
|
} else processingShape.push(-1);
|
|
}
|
|
// Step 4: Compute the final shape
|
|
//
|
|
// newAxis will increase dimension by 1 (with a one-size dimension)
|
|
// slices like foo[3, ...] will reduce dimension by 1.
|
|
// This cannot be done earlier, because it depends on Step 3.
|
|
for(let denseDim = 0; denseDim < denseSpec.finalShapeGatherIndices.length; ++denseDim){
|
|
const gatherIndex = denseSpec.finalShapeGatherIndices[denseDim];
|
|
if (gatherIndex >= 0) finalShape.push(processingShape[gatherIndex]);
|
|
else if (gatherIndex === NEW_AXIS) finalShape.push(1);
|
|
}
|
|
const finalShapeSparse = finalShape.filter((dim, i)=>denseSpec.finalShapeGatherIndices[i] !== NEW_AXIS);
|
|
return {
|
|
finalShapeSparse,
|
|
finalShape,
|
|
isIdentity,
|
|
sliceDim0,
|
|
isSimpleSlice,
|
|
begin: denseSpec.begin,
|
|
end: denseSpec.end,
|
|
strides: denseSpec.strides
|
|
};
|
|
}
|
|
function buildDenseSpec(sparse, dense) {
|
|
dense.beginMask = 0;
|
|
dense.endMask = 0;
|
|
dense.shrinkAxisMask = 0;
|
|
let fullIndex = 0;
|
|
dense.beginValid = sparse.begin != null;
|
|
dense.endValid = sparse.end != null;
|
|
dense.begin = new Array(dense.dims);
|
|
dense.end = new Array(dense.dims);
|
|
dense.strides = new Array(dense.dims);
|
|
dense.finalShapeGatherIndices = [];
|
|
dense.finalShapeGatherIndicesSparse = [];
|
|
dense.inputShapeGatherIndicesSparse = new Array(dense.dims);
|
|
for(let i = 0; i < sparse.dims; i++){
|
|
if (1 << i & sparse.ellipsisMask) {
|
|
// Only the bit that has ellipsis will fall in this condition.
|
|
// Expand the ellipsis into the appropriate indices
|
|
// Note: this only works because we guaranteed one ellipsis.
|
|
const nextIndex = Math.min(dense.dims - (sparse.dims - i) + 1 + sparse.numAddAxisAfterEllipsis, dense.dims);
|
|
for(; fullIndex < nextIndex; fullIndex++){
|
|
// newAxis aren't real axis so you have to skip.
|
|
dense.begin[fullIndex] = 0;
|
|
dense.end[fullIndex] = 0;
|
|
dense.strides[fullIndex] = 1;
|
|
dense.beginMask |= 1 << fullIndex;
|
|
dense.endMask |= 1 << fullIndex;
|
|
dense.finalShapeGatherIndices.push(fullIndex);
|
|
dense.finalShapeGatherIndicesSparse.push(-1);
|
|
dense.inputShapeGatherIndicesSparse[fullIndex] = i;
|
|
}
|
|
} else if (1 << i & sparse.newAxisMask) {
|
|
// Only the bit that has newAxis will fall in this condition.
|
|
dense.finalShapeGatherIndices.push(NEW_AXIS);
|
|
dense.finalShapeGatherIndicesSparse.push(-1);
|
|
} else {
|
|
if (fullIndex === dense.begin.length) throw Error(`Index out of range using input dim ${fullIndex}; input ` + `has only ${dense.dims} dims, ${dense.begin.length}.`);
|
|
// Gather slicing spec into appropriate index.
|
|
if (sparse.begin != null) dense.begin[fullIndex] = sparse.begin[i];
|
|
if (sparse.end != null) dense.end[fullIndex] = sparse.end[i];
|
|
dense.strides[fullIndex] = sparse.strides[i];
|
|
if (sparse.beginMask & 1 << i) dense.beginMask |= 1 << fullIndex;
|
|
if (sparse.endMask & 1 << i) dense.endMask |= 1 << fullIndex;
|
|
// If shrink, record where to get the dimensionality from (i.e. newAxis)
|
|
// creates a fake 1 size dimension. Also remember shrink axis (now in
|
|
// dense form) so we can ignore dense.end below.
|
|
if (sparse.shrinkAxisMask & 1 << i) {
|
|
dense.finalShapeGatherIndices.push(SHRINK_AXIS);
|
|
dense.finalShapeGatherIndicesSparse.push(-1);
|
|
dense.shrinkAxisMask |= 1 << fullIndex;
|
|
} else {
|
|
dense.finalShapeGatherIndices.push(fullIndex);
|
|
// Remember that where in the sparse shape the dense dim comes from.
|
|
dense.finalShapeGatherIndicesSparse.push(i);
|
|
}
|
|
dense.inputShapeGatherIndicesSparse[fullIndex] = i;
|
|
fullIndex++;
|
|
}
|
|
}
|
|
}
|
|
function canonical(x, c, strideI, dimI, masks, validRange) {
|
|
if (masks[c]) return strideI > 0 ? validRange[c] : validRange[c + 1 & 1];
|
|
else {
|
|
const xFwd = x < 0 ? dimI + x : x; // make negative indices positive
|
|
return xFwd < validRange[0] ? validRange[0] : xFwd > validRange[1] ? validRange[1] : xFwd;
|
|
}
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5jZGL":[function(require,module,exports) {
|
|
/** @license See the LICENSE file. */ // This code is auto-generated, do not modify this file!
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "version", ()=>version);
|
|
const version = "4.21.0";
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eaK8y":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "OptimizerConstructors", ()=>OptimizerConstructors);
|
|
var _adadeltaOptimizer = require("./adadelta_optimizer");
|
|
var _adagradOptimizer = require("./adagrad_optimizer");
|
|
var _adamOptimizer = require("./adam_optimizer");
|
|
var _adamaxOptimizer = require("./adamax_optimizer");
|
|
var _momentumOptimizer = require("./momentum_optimizer");
|
|
var _rmspropOptimizer = require("./rmsprop_optimizer");
|
|
var _sgdOptimizer = require("./sgd_optimizer");
|
|
class 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 (0, _sgdOptimizer.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 (0, _momentumOptimizer.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 = .9, momentum = 0.0, epsilon = null, centered = false) {
|
|
return new (0, _rmspropOptimizer.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 (0, _adamOptimizer.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 = .001, rho = .95, epsilon = null) {
|
|
return new (0, _adadeltaOptimizer.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 (0, _adamaxOptimizer.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 (0, _adagradOptimizer.AdagradOptimizer)(learningRate, initialAccumulatorValue);
|
|
}
|
|
}
|
|
|
|
},{"./adadelta_optimizer":"a2jsK","./adagrad_optimizer":"ddRDd","./adam_optimizer":"5uefH","./adamax_optimizer":"72DSu","./momentum_optimizer":"bKhX1","./rmsprop_optimizer":"66Wvy","./sgd_optimizer":"4dxnr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cWOs6":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "train", ()=>train);
|
|
var _optimizerConstructors = require("./optimizers/optimizer_constructors");
|
|
const train = (0, _optimizerConstructors.OptimizerConstructors);
|
|
|
|
},{"./optimizers/optimizer_constructors":"eaK8y","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dz6Y8":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nextFrame", ()=>nextFrame);
|
|
const delayCallback = (()=>{
|
|
if (typeof requestAnimationFrame !== "undefined") return requestAnimationFrame;
|
|
else if (typeof setImmediate !== "undefined") return setImmediate;
|
|
return (f)=>f(); // no delays
|
|
})();
|
|
/**
|
|
* Returns a promise that resolves 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()));
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8IvgS":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "upcastType", ()=>(0, _types.upcastType));
|
|
parcelHelpers.export(exports, "slice_util", ()=>_sliceUtil);
|
|
parcelHelpers.export(exports, "segment_util", ()=>_segmentUtil);
|
|
parcelHelpers.export(exports, "fromUint8ToStringArray", ()=>fromUint8ToStringArray);
|
|
parcelHelpers.export(exports, "fromStringArrayToUint8", ()=>fromStringArrayToUint8);
|
|
var _util = require("../util");
|
|
// Utilities needed by backend consumers of tf-core.
|
|
var _axisUtil = require("../ops/axis_util");
|
|
parcelHelpers.exportAll(_axisUtil, exports);
|
|
var _broadcastUtil = require("../ops/broadcast_util");
|
|
parcelHelpers.exportAll(_broadcastUtil, exports);
|
|
var _concatUtil = require("../ops/concat_util");
|
|
parcelHelpers.exportAll(_concatUtil, exports);
|
|
var _convUtil = require("../ops/conv_util");
|
|
parcelHelpers.exportAll(_convUtil, exports);
|
|
var _fusedUtil = require("../ops/fused_util");
|
|
parcelHelpers.exportAll(_fusedUtil, exports);
|
|
var _fusedTypes = require("../ops/fused_types");
|
|
parcelHelpers.exportAll(_fusedTypes, exports);
|
|
var _raggedToDenseUtil = require("../ops/ragged_to_dense_util");
|
|
parcelHelpers.exportAll(_raggedToDenseUtil, exports);
|
|
var _reduceUtil = require("../ops/reduce_util");
|
|
parcelHelpers.exportAll(_reduceUtil, exports);
|
|
var _sliceUtil = require("../ops/slice_util");
|
|
var _types = require("../types");
|
|
var _rotateUtil = require("../ops/rotate_util");
|
|
parcelHelpers.exportAll(_rotateUtil, exports);
|
|
var _arrayOpsUtil = require("../ops/array_ops_util");
|
|
parcelHelpers.exportAll(_arrayOpsUtil, exports);
|
|
var _gatherNdUtil = require("../ops/gather_nd_util");
|
|
parcelHelpers.exportAll(_gatherNdUtil, exports);
|
|
var _scatterNdUtil = require("../ops/scatter_nd_util");
|
|
parcelHelpers.exportAll(_scatterNdUtil, exports);
|
|
var _seluUtil = require("../ops/selu_util");
|
|
parcelHelpers.exportAll(_seluUtil, exports);
|
|
parcelHelpers.exportAll(_fusedUtil, exports);
|
|
var _erfUtil = require("../ops/erf_util");
|
|
parcelHelpers.exportAll(_erfUtil, exports);
|
|
var _log = require("../log");
|
|
parcelHelpers.exportAll(_log, exports);
|
|
var _complexUtil = require("../backends/complex_util");
|
|
parcelHelpers.exportAll(_complexUtil, exports);
|
|
var _einsumUtil = require("../backends/einsum_util");
|
|
parcelHelpers.exportAll(_einsumUtil, exports);
|
|
var _splitUtil = require("../ops/split_util");
|
|
parcelHelpers.exportAll(_splitUtil, exports);
|
|
var _sparseFillEmptyRowsUtil = require("../ops/sparse/sparse_fill_empty_rows_util");
|
|
parcelHelpers.exportAll(_sparseFillEmptyRowsUtil, exports);
|
|
var _sparseReshapeUtil = require("../ops/sparse/sparse_reshape_util");
|
|
parcelHelpers.exportAll(_sparseReshapeUtil, exports);
|
|
var _sparseSegmentReductionUtil = require("../ops/sparse/sparse_segment_reduction_util");
|
|
parcelHelpers.exportAll(_sparseSegmentReductionUtil, exports);
|
|
var _segmentUtil = require("../ops/segment_util");
|
|
function fromUint8ToStringArray(vals) {
|
|
try {
|
|
// Decode the bytes into string.
|
|
return vals.map((val)=>(0, _util.decodeString)(val));
|
|
} catch (err) {
|
|
throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${err}`);
|
|
}
|
|
}
|
|
function fromStringArrayToUint8(strings) {
|
|
return strings.map((s)=>(0, _util.encodeString)(s));
|
|
}
|
|
|
|
},{"../util":"ctavo","../ops/axis_util":"hzS4B","../ops/broadcast_util":"eLo4J","../ops/concat_util":"9tQ1B","../ops/conv_util":"bf4MH","../ops/fused_util":"8847K","../ops/fused_types":"71RqE","../ops/ragged_to_dense_util":"CafDV","../ops/reduce_util":"lSy0z","../ops/slice_util":"3A9Ql","../types":"10R8n","../ops/rotate_util":"28w8O","../ops/array_ops_util":"fuOID","../ops/gather_nd_util":"4RUOy","../ops/scatter_nd_util":"dDUQ5","../ops/selu_util":"f1Rmi","../ops/erf_util":"lREHE","../log":"5xR9j","../backends/complex_util":"eEkKB","../backends/einsum_util":"4URRN","../ops/split_util":"5SjNI","../ops/sparse/sparse_fill_empty_rows_util":"6kj4w","../ops/sparse/sparse_reshape_util":"eH8pS","../ops/sparse/sparse_segment_reduction_util":"lUp7V","../ops/segment_util":"dZEhU","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9tQ1B":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "assertParamsConsistent", ()=>assertParamsConsistent);
|
|
parcelHelpers.export(exports, "computeOutShape", ()=>computeOutShape);
|
|
var _util = require("../util");
|
|
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;
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"71RqE":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"CafDV":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "RowPartitionType", ()=>RowPartitionType);
|
|
parcelHelpers.export(exports, "combineRaggedTensorToTensorShapes", ()=>combineRaggedTensorToTensorShapes);
|
|
parcelHelpers.export(exports, "getRowPartitionTypesHelper", ()=>getRowPartitionTypesHelper);
|
|
parcelHelpers.export(exports, "getRaggedRank", ()=>getRaggedRank);
|
|
parcelHelpers.export(exports, "validateDefaultValueShape", ()=>validateDefaultValueShape);
|
|
var RowPartitionType;
|
|
(function(RowPartitionType) {
|
|
RowPartitionType[RowPartitionType["FIRST_DIM_SIZE"] = 0] = "FIRST_DIM_SIZE";
|
|
RowPartitionType[RowPartitionType["VALUE_ROWIDS"] = 1] = "VALUE_ROWIDS";
|
|
RowPartitionType[RowPartitionType["ROW_LENGTHS"] = 2] = "ROW_LENGTHS";
|
|
RowPartitionType[RowPartitionType["ROW_SPLITS"] = 3] = "ROW_SPLITS";
|
|
RowPartitionType[RowPartitionType["ROW_LIMITS"] = 4] = "ROW_LIMITS";
|
|
RowPartitionType[RowPartitionType["ROW_STARTS"] = 5] = "ROW_STARTS";
|
|
})(RowPartitionType || (RowPartitionType = {}));
|
|
function combineRaggedTensorToTensorShapes(raggedRank, shape, valueShape) {
|
|
// Test for consistency of valueShape and shape specified.
|
|
// If shape is unspecified and valueShape is specified, then copy
|
|
// over the size from the valueShape dimension.
|
|
let outputShape = new Array();
|
|
if (valueShape == null && shape == null) return outputShape;
|
|
if (shape == null) // Here, value_shape must be of known size.
|
|
while(outputShape.length < raggedRank + valueShape.length)outputShape.push(-1);
|
|
else outputShape = shape.slice();
|
|
if (valueShape == null) return outputShape;
|
|
// At this point, valueShape and output_shape have known ranks.
|
|
if (raggedRank + valueShape.length !== outputShape.length) throw new Error(`rt input.shape and shape=${shape} are incompatible: rt input.rank = ${raggedRank + valueShape.length}, but shape.rank = ${outputShape.length}`);
|
|
for(let i = 1; i < valueShape.length; ++i){
|
|
const valueDim = valueShape[i];
|
|
const outputShapeDimIndex = outputShape[outputShape.length - valueShape.length + i];
|
|
const outputShapeDim = outputShape[outputShapeDimIndex];
|
|
if (valueDim >= 0) {
|
|
if (outputShapeDim >= 0) {
|
|
if (outputShapeDim !== valueDim) throw new Error(`rt input.shape and shape=${shape} are incompatible: rt input.shape[${i + raggedRank}] = ${valueDim} but shape[${i + raggedRank}] = ${outputShapeDim}`);
|
|
} else outputShape[outputShapeDimIndex] = valueDim;
|
|
}
|
|
}
|
|
return outputShape;
|
|
}
|
|
function getRowPartitionTypesHelper(rowPartitionTypeStrings) {
|
|
const stringToType = {
|
|
"FIRST_DIM_SIZE": RowPartitionType.FIRST_DIM_SIZE,
|
|
"VALUE_ROWIDS": RowPartitionType.VALUE_ROWIDS,
|
|
"ROW_LENGTHS": RowPartitionType.ROW_LENGTHS,
|
|
"ROW_SPLITS": RowPartitionType.ROW_SPLITS,
|
|
"ROW_LIMITS": RowPartitionType.ROW_LIMITS,
|
|
"ROW_STARTS": RowPartitionType.ROW_STARTS
|
|
};
|
|
const result = [];
|
|
for (const typeStr of rowPartitionTypeStrings){
|
|
if (typeStr in stringToType) result.push(stringToType[typeStr]);
|
|
else break;
|
|
}
|
|
return result;
|
|
}
|
|
function getRaggedRank(rowPartitionTypes) {
|
|
if (rowPartitionTypes.length === 0) return 0;
|
|
if (rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) return rowPartitionTypes.length - 1;
|
|
return rowPartitionTypes.length;
|
|
}
|
|
function validateDefaultValueShape(defaultValueShape, valueShape) {
|
|
if (defaultValueShape == null || valueShape == null) return;
|
|
const defaultNDims = defaultValueShape.length;
|
|
const valuesNDims = valueShape.length;
|
|
if (defaultNDims >= valuesNDims) throw new Error(`defaultValue.shape=${defaultValueShape} and ragged tensor flatValues.shape=${valueShape}, are incompatible: defaultValue.rank = ${defaultNDims} must be less than ragged tensor input flatValues.rank = ${valuesNDims})`);
|
|
for(let i = 0; i < Math.min(defaultNDims, valuesNDims - 1); ++i){
|
|
const defaultDim = defaultValueShape[i];
|
|
const valueDim = valueShape[i + 1];
|
|
if (defaultDim >= 0 && valueDim >= 0 && defaultDim !== 1 && defaultDim !== valueDim) throw new Error(`defaultValue.shape=${defaultValueShape}, and ragged tensor input flatValues.shape=${valueShape} are incompatible: defaultValue.shape[${i - defaultValueShape.length}] = ${defaultDim} but ragged tensor input.flatValues.shape[${i - defaultValueShape.length}] = ${valueDim}`);
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lSy0z":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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.
|
|
* =============================================================================
|
|
*/ /**
|
|
* Inputs of size above this threshold will be parallelized by calling multiple
|
|
* shader programs.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "PARALLELIZE_THRESHOLD", ()=>PARALLELIZE_THRESHOLD);
|
|
parcelHelpers.export(exports, "computeOptimalWindowSize", ()=>computeOptimalWindowSize);
|
|
var _util = require("../util");
|
|
const PARALLELIZE_THRESHOLD = 30;
|
|
function computeOptimalWindowSize(inSize) {
|
|
if (inSize <= PARALLELIZE_THRESHOLD) return inSize;
|
|
return (0, _util.nearestDivisor)(inSize, Math.floor(Math.sqrt(inSize)));
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"28w8O":[function(require,module,exports) {
|
|
/**
|
|
* @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 the image center in pixels.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getImageCenter", ()=>getImageCenter);
|
|
function getImageCenter(center, imageHeight, imageWidth) {
|
|
const centerX = imageWidth * (typeof center === "number" ? center : center[0]);
|
|
const centerY = imageHeight * (typeof center === "number" ? center : center[1]);
|
|
return [
|
|
centerX,
|
|
centerY
|
|
];
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fuOID":[function(require,module,exports) {
|
|
/**
|
|
* @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
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getReshaped", ()=>getReshaped);
|
|
/**
|
|
* 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
|
|
*/ parcelHelpers.export(exports, "getPermuted", ()=>getPermuted);
|
|
/**
|
|
* 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
|
|
*/ parcelHelpers.export(exports, "getReshapedPermuted", ()=>getReshapedPermuted);
|
|
/**
|
|
* Converts the crops argument into the beginning coordinates of a slice
|
|
* operation.
|
|
*/ parcelHelpers.export(exports, "getSliceBeginCoords", ()=>getSliceBeginCoords);
|
|
/**
|
|
* 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
|
|
*/ parcelHelpers.export(exports, "getSliceSize", ()=>getSliceSize);
|
|
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;
|
|
}
|
|
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;
|
|
}
|
|
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;
|
|
}
|
|
function getSliceBeginCoords(crops, blockShape) {
|
|
const sliceBeginCoords = [
|
|
0
|
|
];
|
|
for(let i = 0; i < blockShape; ++i)sliceBeginCoords.push(crops[i][0]);
|
|
return sliceBeginCoords;
|
|
}
|
|
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;
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"f1Rmi":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "SELU_SCALEALPHA", ()=>SELU_SCALEALPHA);
|
|
parcelHelpers.export(exports, "SELU_SCALE", ()=>SELU_SCALE);
|
|
const SELU_SCALEALPHA = 1.7580993408473768599402175208123;
|
|
const SELU_SCALE = 1.0507009873554804934193349852946;
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lREHE":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ERF_P", ()=>ERF_P);
|
|
parcelHelpers.export(exports, "ERF_A1", ()=>ERF_A1);
|
|
parcelHelpers.export(exports, "ERF_A2", ()=>ERF_A2);
|
|
parcelHelpers.export(exports, "ERF_A3", ()=>ERF_A3);
|
|
parcelHelpers.export(exports, "ERF_A4", ()=>ERF_A4);
|
|
parcelHelpers.export(exports, "ERF_A5", ()=>ERF_A5);
|
|
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;
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eEkKB":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mergeRealAndImagArrays", ()=>mergeRealAndImagArrays);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "splitRealAndImagArrays", ()=>splitRealAndImagArrays);
|
|
/**
|
|
* Extracts even indexed complex values in the given array.
|
|
* @param complex The complex tensor values
|
|
*/ parcelHelpers.export(exports, "complexWithEvenIndex", ()=>complexWithEvenIndex);
|
|
/**
|
|
* Extracts odd indexed comple values in the given array.
|
|
* @param complex The complex tensor values
|
|
*/ parcelHelpers.export(exports, "complexWithOddIndex", ()=>complexWithOddIndex);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getComplexWithIndex", ()=>getComplexWithIndex);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "assignToTypedArray", ()=>assignToTypedArray);
|
|
/**
|
|
* Make the list of exponent terms used by FFT.
|
|
*/ parcelHelpers.export(exports, "exponents", ()=>exponents);
|
|
/**
|
|
* Make the exponent term used by FFT.
|
|
*/ parcelHelpers.export(exports, "exponent", ()=>exponent);
|
|
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;
|
|
}
|
|
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
|
|
};
|
|
}
|
|
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
|
|
};
|
|
}
|
|
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
|
|
};
|
|
}
|
|
function getComplexWithIndex(complex, index) {
|
|
const real = complex[index * 2];
|
|
const imag = complex[index * 2 + 1];
|
|
return {
|
|
real,
|
|
imag
|
|
};
|
|
}
|
|
function assignToTypedArray(data, real, imag, index) {
|
|
data[index * 2] = real;
|
|
data[index * 2 + 1] = imag;
|
|
}
|
|
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
|
|
};
|
|
}
|
|
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
|
|
};
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4URRN":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Parse an equation for einsum.
|
|
*
|
|
* @param equation The einsum equation (e.g., "ij,jk->ik").
|
|
* @param numTensors Number of tensors provided along with `equation`. Used to
|
|
* check matching number of input tensors.
|
|
* @returns An object consisting of the following fields:
|
|
* - allDims: all dimension names as strings.
|
|
* - summedDims: a list of all dimensions being summed over, as indices to
|
|
* the elements of `allDims`.
|
|
* - idDims: indices of the dimensions in each input tensor, as indices to
|
|
* the elements of `allDims.
|
|
*/ parcelHelpers.export(exports, "decodeEinsumEquation", ()=>decodeEinsumEquation);
|
|
/**
|
|
* Get the permutation for a given input tensor.
|
|
*
|
|
* @param nDims Total number of dimension of all tensors involved in the einsum
|
|
* operation.
|
|
* @param idDims Dimension indices involve in the tensor in question.
|
|
* @returns An object consisting of the following fields:
|
|
* - permutationIndices: Indices to permute the axes of the tensor with.
|
|
* - expandDims: Indices to the dimension that need to be expanded from the
|
|
* tensor after permutation.
|
|
*/ parcelHelpers.export(exports, "getEinsumPermutation", ()=>getEinsumPermutation);
|
|
/**
|
|
* Checks that the dimension sizes from different input tensors match the
|
|
* equation.
|
|
*/ parcelHelpers.export(exports, "checkEinsumDimSizes", ()=>checkEinsumDimSizes);
|
|
/**
|
|
* Gets path of computation for einsum.
|
|
*
|
|
* @param summedDims indices to the dimensions being summed over.
|
|
* @param idDims A look up table for the dimensions present in each input
|
|
* tensor. Each consituent array contains indices for the dimensions in the
|
|
* corresponding input tensor.
|
|
*
|
|
* @return A map with two fields:
|
|
* - path: The path of computation, with each element indicating the dimension
|
|
* being summed over after the element-wise multiplication in that step.
|
|
* - steps: With the same length as `path`. Each element contains the indices
|
|
* to the input tensors being used for element-wise multiplication in the
|
|
* corresponding step.
|
|
*/ parcelHelpers.export(exports, "getEinsumComputePath", ()=>getEinsumComputePath);
|
|
/** Determines if an axes permutation is the identity permutation. */ parcelHelpers.export(exports, "isIdentityPermutation", ()=>isIdentityPermutation);
|
|
var _utilBase = require("../util_base");
|
|
const ARROW = "->";
|
|
const ARROW_REGEX = /->/g;
|
|
const COMMA = ",";
|
|
const ELLIPSIS = "...";
|
|
function decodeEinsumEquation(equation, numTensors) {
|
|
equation = equation.replace(/\s/g, ""); // Remove witespace in equation.
|
|
const numArrows = (equation.length - equation.replace(ARROW_REGEX, "").length) / ARROW.length;
|
|
if (numArrows < 1) throw new Error("Equations without an arrow are not supported.");
|
|
else if (numArrows > 1) throw new Error(`Equation must contain exactly one arrow ("${ARROW}").`);
|
|
const [inputString, outputString] = equation.split(ARROW);
|
|
(0, _utilBase.assert)(inputString.indexOf(ELLIPSIS) === -1, ()=>`The ellipsis notation ("${ELLIPSIS}") is not supported yet.`);
|
|
const inputTerms = inputString.split(COMMA);
|
|
const numInputs = inputTerms.length;
|
|
if (numTensors !== numInputs) throw new Error(`Expected ${numInputs} input tensors, received ${numTensors}`);
|
|
if (numInputs > 2) throw new Error("Support for more than 2 input tensors is not implemented yet.");
|
|
const allDims = [];
|
|
for(let i = 0; i < outputString.length; ++i){
|
|
const dimName = outputString[i];
|
|
if (!inputTerms.some((inputTerm)=>inputTerm.indexOf(dimName) !== -1)) throw new Error(`Output subscripts contain the label ${dimName} ` + `not present in the input subscripts.`);
|
|
if (allDims.indexOf(dimName) === -1) allDims.push(dimName);
|
|
}
|
|
for(let i = 0; i < inputString.length; ++i){
|
|
const dimName = inputString[i];
|
|
if (allDims.indexOf(dimName) === -1 && dimName !== COMMA) allDims.push(dimName);
|
|
}
|
|
const idDims = new Array(inputTerms.length);
|
|
for(let i = 0; i < numInputs; ++i){
|
|
if (new Set(inputTerms[i].split("")).size !== inputTerms[i].length) throw new Error(`Found duplicate axes in input component ${inputTerms[i]}. ` + `Support for duplicate axes in input is not implemented yet.`);
|
|
idDims[i] = [];
|
|
for(let j = 0; j < inputTerms[i].length; ++j)idDims[i].push(allDims.indexOf(inputTerms[i][j]));
|
|
}
|
|
const numDims = allDims.length; // Number of unique dimensions.
|
|
const numOutDims = outputString.length; // Number of output dimensions.
|
|
const summedDims = []; // Dimensions being summed over.
|
|
for(let i = numOutDims; i < numDims; ++i)summedDims.push(i);
|
|
return {
|
|
allDims,
|
|
summedDims,
|
|
idDims
|
|
};
|
|
}
|
|
function getEinsumPermutation(nDims, idDims) {
|
|
let permutationIndices = new Array(nDims);
|
|
permutationIndices.fill(-1);
|
|
for(let i = 0; i < idDims.length; ++i)permutationIndices[idDims[i]] = i;
|
|
const expandDims = [];
|
|
for(let i = 0; i < nDims; ++i)if (permutationIndices[i] === -1) expandDims.push(i);
|
|
permutationIndices = permutationIndices.filter((d)=>d !== -1);
|
|
return {
|
|
permutationIndices,
|
|
expandDims
|
|
};
|
|
}
|
|
function checkEinsumDimSizes(nDims, idDims, tensors) {
|
|
const dimSizes = new Array(nDims);
|
|
for(let i = 0; i < tensors.length; ++i){
|
|
const shape = tensors[i].shape;
|
|
for(let j = 0; j < idDims[i].length; ++j)if (dimSizes[idDims[i][j]] === undefined) dimSizes[idDims[i][j]] = shape[j];
|
|
else (0, _utilBase.assert)(dimSizes[idDims[i][j]] === shape[j], ()=>`Expected dimension ${dimSizes[idDims[i][j]]} at axis ${j} ` + `of input shaped ${JSON.stringify(shape)}, ` + `but got dimension ${shape[j]}`);
|
|
}
|
|
}
|
|
function getEinsumComputePath(summedDims, idDims) {
|
|
const path = summedDims;
|
|
const steps = [];
|
|
let nSteps = 0;
|
|
if (summedDims.length === 0) // Einsum that involes no summing: e.g., transpose and outer product.
|
|
path.push(-1);
|
|
nSteps = summedDims.length + 1;
|
|
for(let i = 0; i < nSteps; ++i)steps.push([]);
|
|
const computedTermIndices = [];
|
|
for(let i = 0; i < path.length; ++i){
|
|
const summedDim = path[i];
|
|
const termIndices = findTermsWithDim(idDims, summedDim);
|
|
for (const termIndex of termIndices)if (computedTermIndices.indexOf(termIndex) === -1) {
|
|
steps[i].push(termIndex);
|
|
computedTermIndices.push(termIndex);
|
|
}
|
|
}
|
|
return {
|
|
path,
|
|
steps
|
|
};
|
|
}
|
|
function isIdentityPermutation(perm) {
|
|
return perm.every((dim, index)=>dim === index);
|
|
}
|
|
function findTermsWithDim(idDims, dim) {
|
|
const termIndices = [];
|
|
for(let i = 0; i < idDims.length; ++i)if (idDims[i].length === 0 || idDims[i].indexOf(dim) !== -1 || dim === -1) termIndices.push(i);
|
|
return termIndices;
|
|
}
|
|
|
|
},{"../util_base":"4Vo4a","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5SjNI":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Prepare the split size array. When the input is a number, the axis is evenly
|
|
* divided among the split size. When the input contains the negative value, the
|
|
* rest of the axis is allocated toward that.
|
|
*/ parcelHelpers.export(exports, "prepareSplitSize", ()=>prepareSplitSize);
|
|
var _util = require("../util");
|
|
function prepareSplitSize(x, numOrSizeSplits, axis = 0) {
|
|
let splitSizes = [];
|
|
if (typeof numOrSizeSplits === "number") {
|
|
(0, _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 {
|
|
const numOfNegs = numOrSizeSplits.reduce((count, value)=>{
|
|
if (value === -1) count += 1;
|
|
return count;
|
|
}, 0);
|
|
(0, _util.assert)(numOfNegs <= 1, ()=>"There should be only one negative value in split array.");
|
|
const negIndex = numOrSizeSplits.indexOf(-1);
|
|
// Allow the number of split array to be -1, which indicates the rest
|
|
// of dimension is allocated to that split.
|
|
if (negIndex !== -1) {
|
|
const total = numOrSizeSplits.reduce((a, b)=>b > 0 ? a + b : a);
|
|
numOrSizeSplits[negIndex] = x.shape[axis] - total;
|
|
}
|
|
(0, _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;
|
|
}
|
|
return splitSizes;
|
|
}
|
|
|
|
},{"../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6kj4w":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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.
|
|
* =============================================================================
|
|
*/ /**
|
|
* Generates sparse fill empty rows indices, dense shape mismatch error message.
|
|
*
|
|
* @param indicesLength The first dimension of indices.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getSparseFillEmptyRowsIndicesDenseShapeMismatch", ()=>getSparseFillEmptyRowsIndicesDenseShapeMismatch);
|
|
/**
|
|
* Generates sparse fill empty rows negative index error message.
|
|
*
|
|
* @param index The index with a negative value.
|
|
* @param value The negative value.
|
|
*/ parcelHelpers.export(exports, "getSparseFillEmptyRowsNegativeIndexErrorMessage", ()=>getSparseFillEmptyRowsNegativeIndexErrorMessage);
|
|
/**
|
|
* Generates sparse fill empty rows out of range index error message.
|
|
*
|
|
* @param index The index with an out of range value.
|
|
* @param value The out of range value.
|
|
* @param limit The upper limit for indices.
|
|
*/ parcelHelpers.export(exports, "getSparseFillEmptyRowsOutOfRangeIndexErrorMessage", ()=>getSparseFillEmptyRowsOutOfRangeIndexErrorMessage);
|
|
function getSparseFillEmptyRowsIndicesDenseShapeMismatch(indicesLength) {
|
|
return `Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${indicesLength}`;
|
|
}
|
|
function getSparseFillEmptyRowsNegativeIndexErrorMessage(index, value) {
|
|
return `indices(${index}, 0) is invalid: ${value} < 0`;
|
|
}
|
|
function getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(index, value, limit) {
|
|
return `indices(${index}, 0) is invalid: ${value} >= ${limit}`;
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eH8pS":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Generates sparse reshape multiple negative 1 output dimension error message.
|
|
*
|
|
* @param dim1 The first dimension with a negative 1 value.
|
|
* @param dim2 The second dimension with a negative 1 value.
|
|
*/ parcelHelpers.export(exports, "getSparseReshapeMultipleNegativeOneOutputDimErrorMessage", ()=>getSparseReshapeMultipleNegativeOneOutputDimErrorMessage);
|
|
/**
|
|
* Generates sparse reshape negative output dimension error message.
|
|
*
|
|
* @param dim The dimension with a negative value.
|
|
* @param value The negative value.
|
|
*/ parcelHelpers.export(exports, "getSparseReshapeNegativeOutputDimErrorMessage", ()=>getSparseReshapeNegativeOutputDimErrorMessage);
|
|
/**
|
|
* Generates sparse reshape empty tensor zero output dimension error message.
|
|
*
|
|
*/ parcelHelpers.export(exports, "getSparseReshapeEmptyTensorZeroOutputDimErrorMessage", ()=>getSparseReshapeEmptyTensorZeroOutputDimErrorMessage);
|
|
/**
|
|
* Generates sparse reshape input output multiple mismatch error message.
|
|
*
|
|
* @param inputShape the input shape.
|
|
* @param outputShape the requested output shape.
|
|
*/ parcelHelpers.export(exports, "getSparseReshapeInputOutputMultipleErrorMessage", ()=>getSparseReshapeInputOutputMultipleErrorMessage);
|
|
/**
|
|
* Generates sparse reshape input output inequality error message.
|
|
*
|
|
* @param inputShape the input shape.
|
|
* @param outputShape the requested output shape.
|
|
*/ parcelHelpers.export(exports, "getSparseReshapeInputOutputMismatchErrorMessage", ()=>getSparseReshapeInputOutputMismatchErrorMessage);
|
|
var _util = require("../../util");
|
|
function getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(dim1, dim2) {
|
|
return `only one output dimension may be -1, not both ${dim1} and ${dim2}`;
|
|
}
|
|
function getSparseReshapeNegativeOutputDimErrorMessage(dim, value) {
|
|
return `size ${dim} must be non-negative, not ${value}`;
|
|
}
|
|
function getSparseReshapeEmptyTensorZeroOutputDimErrorMessage() {
|
|
return "reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero";
|
|
}
|
|
function getSparseReshapeInputOutputMultipleErrorMessage(inputShape, outputShape) {
|
|
const inputSize = (0, _util.sizeFromShape)(inputShape);
|
|
const outputSize = (0, _util.sizeFromShape)(outputShape);
|
|
return `Input to reshape is a SparseTensor with ${inputSize}
|
|
dense values, but the requested shape requires a multiple of ${outputSize}. inputShape=${inputShape} outputShape= ${outputShape}`;
|
|
}
|
|
function getSparseReshapeInputOutputMismatchErrorMessage(inputShape, outputShape) {
|
|
const inputSize = (0, _util.sizeFromShape)(inputShape);
|
|
const outputSize = (0, _util.sizeFromShape)(outputShape);
|
|
return `Input to reshape is a tensor with ${inputSize} dense values, but the requested shape has ${outputSize}. inputShape=${inputShape} outputShape=${outputShape}`;
|
|
}
|
|
|
|
},{"../../util":"ctavo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lUp7V":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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.
|
|
* =============================================================================
|
|
*/ /**
|
|
* Generates sparse segment reduction negative segment ids error message.
|
|
*
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getSparseSegmentReductionNegativeSegmentIdsErrorMessage", ()=>getSparseSegmentReductionNegativeSegmentIdsErrorMessage);
|
|
/**
|
|
* Generates sparse segment reduction non increasing segment ids error message.
|
|
*
|
|
*/ parcelHelpers.export(exports, "getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage", ()=>getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage);
|
|
/**
|
|
* Generates sparse segment reduction segment id out of range error message.
|
|
*
|
|
* @param segmentId The segment id index that is out of range.
|
|
* @param outputRows Upper bound of valid segment id values.
|
|
*/ parcelHelpers.export(exports, "getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage", ()=>getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage);
|
|
/**
|
|
* Generates sparse segment reduction input indice out of range error message.
|
|
*
|
|
* @param index The index that holds the out of range value.
|
|
* @param indexValue The value that is out of range.
|
|
* @param inputRows Upper bound of valid index values.
|
|
*/ parcelHelpers.export(exports, "getSparseSegmentReductionIndicesOutOfRangeErrorMessage", ()=>getSparseSegmentReductionIndicesOutOfRangeErrorMessage);
|
|
function getSparseSegmentReductionNegativeSegmentIdsErrorMessage() {
|
|
return `segment ids must be >= 0`;
|
|
}
|
|
function getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage() {
|
|
return `segment ids are not increasing`;
|
|
}
|
|
function getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(segmentId, outputRows) {
|
|
return `Segment id ${segmentId} out of range [0, ${outputRows}), possibly because segmentIds input is not sorted.`;
|
|
}
|
|
function getSparseSegmentReductionIndicesOutOfRangeErrorMessage(index, indexValue, inputRows) {
|
|
return `Bad: indices[${index}] == ${indexValue} out of range [0, ${inputRows})`;
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dZEhU":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "segOpComputeOptimalWindowSize", ()=>segOpComputeOptimalWindowSize);
|
|
parcelHelpers.export(exports, "computeOutShape", ()=>computeOutShape);
|
|
parcelHelpers.export(exports, "collectGatherOpShapeInfo", ()=>collectGatherOpShapeInfo);
|
|
var _util = require("../util");
|
|
var _reduceUtil = require("./reduce_util");
|
|
function segOpComputeOptimalWindowSize(inSize, numSegments) {
|
|
let done = false;
|
|
let res;
|
|
if (inSize <= (0, _reduceUtil.PARALLELIZE_THRESHOLD)) {
|
|
res = inSize;
|
|
done = true;
|
|
} else res = (0, _util.nearestDivisor)(inSize, Math.floor(Math.sqrt(inSize)));
|
|
while(!done)if (res > numSegments || res === inSize) done = true;
|
|
else res = (0, _util.nearestDivisor)(inSize, res + 1);
|
|
return res;
|
|
}
|
|
function 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, batchDims) {
|
|
const indicesRank = indices.shape.length;
|
|
const xRank = x.shape.length;
|
|
if (batchDims !== 0) {
|
|
if (batchDims < -indicesRank || batchDims > indicesRank) throw new Error(`Expect batchDims in the range of [-${indicesRank}, ${indicesRank}], but got ${batchDims}`);
|
|
}
|
|
if (batchDims < 0) batchDims += indicesRank;
|
|
if (batchDims > xRank) throw new Error(`batchDims (${batchDims}) must be less than rank(x) (
|
|
${xRank}).`);
|
|
if (axis < batchDims) throw new Error(`batchDims (${batchDims}) must be less than or equal to axis (${axis}).`);
|
|
for(let i = 0; i < batchDims; ++i){
|
|
if (x.shape[i] !== indices.shape[i]) throw new Error(`x.shape[${i}]: ${x.shape[i]} should be equal to indices.shape[${i}]: ${indices.shape[i]}.`);
|
|
}
|
|
const dimSize = x.shape[axis];
|
|
const outputShape = [];
|
|
let batchSize = 1;
|
|
let outerSize = 1;
|
|
let sliceSize = 1;
|
|
for(let i = 0; i < batchDims; ++i){
|
|
outputShape.push(x.shape[i]);
|
|
batchSize *= x.shape[i];
|
|
}
|
|
for(let i = batchDims; i < axis; i++){
|
|
outputShape.push(x.shape[i]);
|
|
outerSize *= x.shape[i];
|
|
}
|
|
for(let i = batchDims; i < indicesRank; i++)outputShape.push(indices.shape[i]);
|
|
for(let i = axis + 1; i < xRank; i++){
|
|
outputShape.push(x.shape[i]);
|
|
sliceSize *= x.shape[i];
|
|
}
|
|
return {
|
|
batchSize,
|
|
sliceSize,
|
|
outerSize,
|
|
dimSize,
|
|
outputShape
|
|
};
|
|
}
|
|
|
|
},{"../util":"ctavo","./reduce_util":"lSy0z","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cylCc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV3Impl", ()=>(0, _nonMaxSuppressionImpl.nonMaxSuppressionV3Impl));
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV4Impl", ()=>(0, _nonMaxSuppressionImpl.nonMaxSuppressionV4Impl));
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV5Impl", ()=>(0, _nonMaxSuppressionImpl.nonMaxSuppressionV5Impl));
|
|
parcelHelpers.export(exports, "whereImpl", ()=>(0, _whereImpl.whereImpl));
|
|
var _nonMaxSuppressionImpl = require("./non_max_suppression_impl");
|
|
var _whereImpl = require("./where_impl");
|
|
|
|
},{"./non_max_suppression_impl":"e0x4w","./where_impl":"lNCmF","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bXLEs":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // All exports from this package should be in base.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
var _base = require("./base");
|
|
parcelHelpers.exportAll(_base, exports);
|
|
var _registerAllKernels = require("./register_all_kernels");
|
|
|
|
},{"./base":"iTvOJ","./register_all_kernels":"es42p","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iTvOJ":[function(require,module,exports) {
|
|
/**
|
|
* @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 is the webgl backend without auto kernel registration.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "version_webgl", ()=>(0, _version.version));
|
|
parcelHelpers.export(exports, "webgl", ()=>webgl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _backendWebgl = require("./backend_webgl");
|
|
var _version = require("./version");
|
|
// Export webgl utilities
|
|
var _webgl = require("./webgl");
|
|
parcelHelpers.exportAll(_webgl, exports);
|
|
if ((0, _tfjsCore.device_util).isBrowser()) (0, _tfjsCore.registerBackend)("webgl", ()=>new (0, _backendWebgl.MathBackendWebGL)(), 2 /* priority */ );
|
|
const webgl = {
|
|
forceHalfFloat: (0, _webgl.forceHalfFloat)
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./backend_webgl":"9XxNW","./version":"8XYZf","./webgl":"l4jNp","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9XxNW":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 webgl flags.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "EPSILON_FLOAT32", ()=>EPSILON_FLOAT32);
|
|
parcelHelpers.export(exports, "EPSILON_FLOAT16", ()=>EPSILON_FLOAT16);
|
|
parcelHelpers.export(exports, "getBinaryCache", ()=>getBinaryCache);
|
|
parcelHelpers.export(exports, "MathBackendWebGL", ()=>MathBackendWebGL);
|
|
var _flagsWebgl = require("./flags_webgl");
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _canvasUtil = require("./canvas_util");
|
|
var _decodeMatrixGpu = require("./decode_matrix_gpu");
|
|
var _decodeMatrixPackedGpu = require("./decode_matrix_packed_gpu");
|
|
var _encodeFloatGpu = require("./encode_float_gpu");
|
|
var _encodeFloatPackedGpu = require("./encode_float_packed_gpu");
|
|
var _encodeMatrixGpu = require("./encode_matrix_gpu");
|
|
var _encodeMatrixPackedGpu = require("./encode_matrix_packed_gpu");
|
|
var _gpgpuContext = require("./gpgpu_context");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _shared = require("./kernel_utils/shared");
|
|
var _packGpu = require("./pack_gpu");
|
|
var _reshapePackedGpu = require("./reshape_packed_gpu");
|
|
var _texUtil = require("./tex_util");
|
|
var _textureManager = require("./texture_manager");
|
|
var _unaryopGpu = require("./unaryop_gpu");
|
|
var _unaryopPackedGpu = require("./unaryop_packed_gpu");
|
|
var _unpackGpu = require("./unpack_gpu");
|
|
var _webglUtil = require("./webgl_util");
|
|
const whereImpl = (0, _tfjsCore.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];
|
|
}
|
|
// Empirically determined constant used to determine size threshold for handing
|
|
// off execution to the CPU.
|
|
const CPU_HANDOFF_SIZE_THRESHOLD = (0, _tfjsCore.env)().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");
|
|
// 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 ((0, _tfjsCore.env)().global.screen == null) return 1024; // 1 GB.
|
|
return (0, _tfjsCore.env)().global.screen.height * (0, _tfjsCore.env)().global.screen.width * window.devicePixelRatio * BEFORE_PAGING_CONSTANT / 1024 / 1024;
|
|
}
|
|
class MathBackendWebGL extends (0, _tfjsCore.KernelBackend) {
|
|
nextDataId() {
|
|
return MathBackendWebGL.nextDataId++;
|
|
}
|
|
constructor(gpuResource){
|
|
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;
|
|
// record the last manual GL Flush time.
|
|
this.lastGlFlushTime = 0;
|
|
this.warnedAboutMemory = false;
|
|
this.pendingDeletes = 0;
|
|
this.disposed = false;
|
|
if (!(0, _tfjsCore.env)().getBool("HAS_WEBGL")) throw new Error("WebGL is not supported on this device");
|
|
let newGPGPU;
|
|
if (gpuResource != null) {
|
|
if (gpuResource instanceof (0, _gpgpuContext.GPGPUContext)) newGPGPU = gpuResource;
|
|
else {
|
|
const gl = (0, _canvasUtil.getWebGLContext)((0, _tfjsCore.env)().getNumber("WEBGL_VERSION"), gpuResource);
|
|
newGPGPU = new (0, _gpgpuContext.GPGPUContext)(gl);
|
|
}
|
|
this.binaryCache = {};
|
|
this.gpgpuCreatedLocally = false;
|
|
} else {
|
|
const gl = (0, _canvasUtil.getWebGLContext)((0, _tfjsCore.env)().getNumber("WEBGL_VERSION"));
|
|
newGPGPU = new (0, _gpgpuContext.GPGPUContext)(gl);
|
|
this.binaryCache = getBinaryCache((0, _tfjsCore.env)().getNumber("WEBGL_VERSION"));
|
|
this.gpgpuCreatedLocally = true;
|
|
}
|
|
this.gpgpu = newGPGPU;
|
|
this.canvas = this.gpgpu.gl.canvas;
|
|
this.textureManager = new (0, _textureManager.TextureManager)(this.gpgpu);
|
|
this.numMBBeforeWarning = numMBBeforeWarning();
|
|
this.texData = new (0, _tfjsCore.DataStorage)(this, (0, _tfjsCore.engine)());
|
|
}
|
|
numDataIds() {
|
|
return this.texData.numDataIds() - this.pendingDeletes;
|
|
}
|
|
// Writes a new entry to the data store with a WebGL texture, and registers it
|
|
// to the texture manager.
|
|
writeTexture(texture, shape, dtype, texHeight, texWidth, channels) {
|
|
// Temporarily create an tensor info to make the texture compatible with
|
|
// the runWebGLProgram's input.
|
|
const input = this.makeTensorInfo(shape, dtype);
|
|
const inData = this.texData.get(input.dataId);
|
|
// Even though the input texture could be unpacked or dense packed, it is
|
|
// always considered as unpacked for EncodeMatrixProgram.
|
|
inData.isPacked = false;
|
|
// Bind texture to the input tensor.
|
|
inData.texture = {
|
|
texture,
|
|
texShape: [
|
|
texHeight,
|
|
texWidth
|
|
]
|
|
};
|
|
inData.texShape = [
|
|
texHeight,
|
|
texWidth
|
|
];
|
|
const shapeAs3D = _webglUtil.getShapeAs3D(shape);
|
|
const program = new (0, _encodeMatrixGpu.EncodeMatrixProgram)(shapeAs3D, false, channels);
|
|
const output = this.runWebGLProgram(program, [
|
|
input
|
|
], dtype, [
|
|
[
|
|
texHeight,
|
|
texWidth
|
|
]
|
|
]);
|
|
output.shape = shape;
|
|
// Unbind the texture from the input tensor to avoid the texture being
|
|
// released.
|
|
inData.texture = null;
|
|
this.disposeIntermediateTensorInfo(input);
|
|
return output.dataId;
|
|
}
|
|
write(values, shape, dtype) {
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS") || (0, _tfjsCore.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 = {
|
|
id: this.nextDataId()
|
|
};
|
|
this.texData.set(dataId, {
|
|
shape,
|
|
dtype,
|
|
values,
|
|
usage: (0, _texUtil.TextureUsage).UPLOAD,
|
|
refCount: 1
|
|
});
|
|
return dataId;
|
|
}
|
|
/** Return refCount of a `TensorData`. */ refCount(dataId) {
|
|
if (this.texData.has(dataId)) {
|
|
const tensorData = this.texData.get(dataId);
|
|
return tensorData.refCount;
|
|
}
|
|
return 0;
|
|
}
|
|
/** Increase refCount of a `TextureData`. */ incRef(dataId) {
|
|
const texData = this.texData.get(dataId);
|
|
texData.refCount++;
|
|
}
|
|
/** Decrease refCount of a `TextureData`. */ decRef(dataId) {
|
|
if (this.texData.has(dataId)) {
|
|
const texData = this.texData.get(dataId);
|
|
texData.refCount--;
|
|
}
|
|
}
|
|
move(dataId, values, shape, dtype, refCount) {
|
|
if ((0, _tfjsCore.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: (0, _texUtil.TextureUsage).UPLOAD,
|
|
refCount
|
|
});
|
|
}
|
|
disposeIntermediateTensorInfo(tensorInfo) {
|
|
this.disposeData(tensorInfo.dataId);
|
|
}
|
|
readSync(dataId) {
|
|
const texData = this.texData.get(dataId);
|
|
const { values, dtype, complexTensorInfos, slice, shape, isPacked } = texData;
|
|
// The presence of `slice` indicates this tensor is a shallow slice of a
|
|
// different tensor, and is using that original tensor's texture. Run
|
|
// `clone` in order to copy that texture and read from it.
|
|
if (slice != null) {
|
|
let program;
|
|
if (isPacked) program = new (0, _unaryopPackedGpu.UnaryOpPackedProgram)(shape, _unaryopGpu.CLONE);
|
|
else program = new (0, _unaryopGpu.UnaryOpProgram)(shape, _unaryopGpu.CLONE);
|
|
const res = this.runWebGLProgram(program, [
|
|
{
|
|
dataId,
|
|
shape,
|
|
dtype
|
|
}
|
|
], dtype);
|
|
const data = this.readSync(res.dataId);
|
|
this.disposeIntermediateTensorInfo(res);
|
|
return data;
|
|
}
|
|
if (values != null) return this.convertAndCacheOnCPU(dataId);
|
|
if (dtype === "string") return values;
|
|
const shouldTimeProgram = this.activeTimers != null;
|
|
let start;
|
|
if (shouldTimeProgram) start = (0, _tfjsCore.util).now();
|
|
let result;
|
|
if (dtype === "complex64") {
|
|
const realValues = this.readSync(complexTensorInfos.real.dataId);
|
|
const imagValues = this.readSync(complexTensorInfos.imag.dataId);
|
|
result = (0, _tfjsCore.backend_util).mergeRealAndImagArrays(realValues, imagValues);
|
|
} else result = this.getValuesFromTexture(dataId);
|
|
if (shouldTimeProgram) this.downloadWaitMs += (0, _tfjsCore.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, complexTensorInfos, isPacked } = texData;
|
|
// The presence of `slice` indicates this tensor is a shallow slice of a
|
|
// different tensor, and is using that original tensor's texture. Run
|
|
// `clone` in order to copy that texture and read from it.
|
|
if (slice != null) {
|
|
let program;
|
|
if (isPacked) program = new (0, _unaryopPackedGpu.UnaryOpPackedProgram)(shape, _unaryopGpu.CLONE);
|
|
else program = new (0, _unaryopGpu.UnaryOpProgram)(shape, _unaryopGpu.CLONE);
|
|
const res = this.runWebGLProgram(program, [
|
|
{
|
|
dataId,
|
|
shape,
|
|
dtype
|
|
}
|
|
], dtype);
|
|
const data = this.read(res.dataId);
|
|
this.disposeIntermediateTensorInfo(res);
|
|
return data;
|
|
}
|
|
if (values != null) return this.convertAndCacheOnCPU(dataId);
|
|
if ((0, _tfjsCore.env)().getBool("DEBUG")) {
|
|
// getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED') caused a blocking GPU call.
|
|
// For performance reason, only check it for debugging. In production,
|
|
// it doesn't handle this use case anyway, so behavior is not changed.
|
|
if (!(0, _tfjsCore.env)().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED") && (0, _tfjsCore.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" && (0, _tfjsCore.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.texture, ..._texUtil.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([
|
|
this.read(complexTensorInfos.real.dataId),
|
|
this.read(complexTensorInfos.imag.dataId)
|
|
]);
|
|
const realValues = ps[0];
|
|
const imagValues = ps[1];
|
|
vals = (0, _tfjsCore.backend_util).mergeRealAndImagArrays(realValues, imagValues);
|
|
} else if (buffer == null) vals = this.getValuesFromTexture(dataId);
|
|
else {
|
|
const size = (0, _tfjsCore.util).sizeFromShape(shape);
|
|
vals = this.gpgpu.downloadFloat32MatrixFromBuffer(buffer, size);
|
|
}
|
|
if (tmpDownloadTarget != null) this.disposeIntermediateTensorInfo(tmpDownloadTarget);
|
|
if (buffer != null) {
|
|
const gl = this.gpgpu.gl;
|
|
_webglUtil.callAndCheck(gl, ()=>gl.deleteBuffer(buffer));
|
|
}
|
|
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);
|
|
if (this.disposeData(dataId)) (0, _tfjsCore.engine)().removeDataId(dataId, this);
|
|
this.pendingDeletes--;
|
|
}
|
|
return dTypeVals;
|
|
}
|
|
/**
|
|
* Read tensor to a new texture that is densely packed for ease of use.
|
|
* @param dataId The source tensor.
|
|
* @param options
|
|
* customTexShape: Optional. If set, will use the user defined texture
|
|
* shape to create the texture.
|
|
*/ readToGPU(dataId, options = {}) {
|
|
const texData = this.texData.get(dataId);
|
|
const { values, shape, slice, dtype, isPacked, texture } = texData;
|
|
if (dtype === "complex64") throw new Error("Does not support reading texture for complex64 dtype.");
|
|
// The presence of `slice` indicates this tensor is a shallow slice of a
|
|
// different tensor, and is using that original tensor's texture. Run
|
|
// `clone` in order to copy that texture and read from it.
|
|
if (slice != null) {
|
|
let program;
|
|
if (isPacked) program = new (0, _unaryopPackedGpu.UnaryOpPackedProgram)(shape, _unaryopGpu.CLONE);
|
|
else program = new (0, _unaryopGpu.UnaryOpProgram)(shape, _unaryopGpu.CLONE);
|
|
const res = this.runWebGLProgram(program, [
|
|
{
|
|
dataId,
|
|
shape,
|
|
dtype
|
|
}
|
|
], dtype);
|
|
const gpuResouorce = this.readToGPU(res, options);
|
|
this.disposeIntermediateTensorInfo(res);
|
|
return gpuResouorce;
|
|
}
|
|
if (texture == null) {
|
|
if (values != null) throw new Error("Data is not on GPU but on CPU.");
|
|
else throw new Error("There is no data on GPU or CPU.");
|
|
}
|
|
// Decode the texture so that it is stored densely (using four channels).
|
|
const tmpTarget = this.decode(dataId, options.customTexShape);
|
|
// Make engine track this tensor, so that we can dispose it later.
|
|
const tensorRef = (0, _tfjsCore.engine)().makeTensorFromTensorInfo(tmpTarget);
|
|
const tmpData = this.texData.get(tmpTarget.dataId);
|
|
return Object.assign({
|
|
tensorRef
|
|
}, tmpData.texture);
|
|
}
|
|
bufferSync(t) {
|
|
const data = this.readSync(t.dataId);
|
|
if (t.dtype === "string") try {
|
|
// Decode the bytes into string.
|
|
const strings = data.map((d)=>(0, _tfjsCore.util).decodeString(d));
|
|
return (0, _tfjsCore.buffer)(t.shape, t.dtype, strings);
|
|
} catch (_a) {
|
|
throw new Error("Failed to decode encoded string bytes into utf-8");
|
|
}
|
|
return (0, _tfjsCore.buffer)(t.shape, t.dtype, data);
|
|
}
|
|
checkNumericalProblems(values) {
|
|
if (values == null) return;
|
|
for(let i = 0; i < values.length; i++){
|
|
const num = values[i];
|
|
if (!_webglUtil.canBeRepresented(num)) {
|
|
if ((0, _tfjsCore.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 = (0, _tfjsCore.util).sizeFromShape(shape);
|
|
if ((0, _tfjsCore.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.texture, ..._texUtil.getDenseTexShape(shape)).subarray(0, size);
|
|
this.disposeIntermediateTensorInfo(tmpTarget);
|
|
return vals;
|
|
}
|
|
const shouldUsePackedProgram = (0, _tfjsCore.env)().getBool("WEBGL_PACK") && isPacked === true;
|
|
const outputShape = shouldUsePackedProgram ? _webglUtil.getShapeAs3D(shape) : shape;
|
|
const program = shouldUsePackedProgram ? new (0, _encodeFloatPackedGpu.EncodeFloatPackedProgram)(outputShape) : new (0, _encodeFloatGpu.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.texture, tmpData.texShape[0], tmpData.texShape[1]).subarray(0, size);
|
|
this.disposeIntermediateTensorInfo(output);
|
|
return vals;
|
|
}
|
|
timerAvailable() {
|
|
return (0, _tfjsCore.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0;
|
|
}
|
|
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 = (0, _tfjsCore.util).flatten(this.activeTimers.map((d)=>d.query)).filter((d)=>d != null);
|
|
const flattenedActiveTimerNames = (0, _tfjsCore.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
|
|
};
|
|
return (async ()=>{
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
|
|
const kernelMs = await Promise.all(flattenedActiveTimerQueries);
|
|
res["kernelMs"] = (0, _tfjsCore.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,
|
|
numBytesInGPUAllocated: this.textureManager.numBytesAllocated,
|
|
numBytesInGPUFree: this.textureManager.numBytesFree
|
|
};
|
|
}
|
|
startTimer() {
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) return this.gpgpu.beginQuery();
|
|
return {
|
|
startMs: (0, _tfjsCore.util).now(),
|
|
endMs: null
|
|
};
|
|
}
|
|
endTimer(query) {
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
|
|
this.gpgpu.endQuery();
|
|
return query;
|
|
}
|
|
query.endMs = (0, _tfjsCore.util).now();
|
|
return query;
|
|
}
|
|
async getQueryTime(query) {
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) return this.gpgpu.waitForQueryAndGetTime(query);
|
|
const timerQuery = query;
|
|
return timerQuery.endMs - timerQuery.startMs;
|
|
}
|
|
/**
|
|
* Decrease the RefCount on the dataId and dispose the memory if the dataId
|
|
* has 0 refCount. If there are pending read on the data, the disposal would
|
|
* added to the pending delete queue. Return true if the dataId is removed
|
|
* from backend or the backend does not contain the dataId, false if the
|
|
* dataId is not removed. Memory may or may not be released even when dataId
|
|
* is removed, which also depends on dataRefCount, see `releaseGPU`.
|
|
* @param dataId
|
|
* @oaram force Optional, remove the data regardless of refCount
|
|
*/ disposeData(dataId, force = false) {
|
|
if (this.pendingDisposal.has(dataId)) return false;
|
|
// No-op if already disposed.
|
|
if (!this.texData.has(dataId)) return true;
|
|
// if force flag is set, change refCount to 0, this would ensure disposal
|
|
// when added to the pendingDisposal queue. Memory may or may not be
|
|
// released, which also depends on dataRefCount, see `releaseGPU`.
|
|
if (force) this.texData.get(dataId).refCount = 0;
|
|
else this.texData.get(dataId).refCount--;
|
|
if (!force && this.texData.get(dataId).refCount > 0) return false;
|
|
if (this.pendingRead.has(dataId)) {
|
|
this.pendingDisposal.add(dataId);
|
|
this.pendingDeletes++;
|
|
return false;
|
|
}
|
|
this.releaseGPUData(dataId);
|
|
const { complexTensorInfos } = this.texData.get(dataId);
|
|
if (complexTensorInfos != null) {
|
|
this.disposeData(complexTensorInfos.real.dataId, force);
|
|
this.disposeData(complexTensorInfos.imag.dataId, force);
|
|
}
|
|
this.texData.delete(dataId);
|
|
return true;
|
|
}
|
|
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.texture;
|
|
}
|
|
/**
|
|
* Returns internal information for the specific data bucket. Used in unit
|
|
* tests.
|
|
*/ getDataInfo(dataId) {
|
|
return this.texData.get(dataId);
|
|
}
|
|
/*
|
|
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 (0, _tfjsCore.env)().getBool("WEBGL_CPU_FORWARD") && inputs.every((input)=>this.texData.get(input.dataId).texture == null && (0, _tfjsCore.util).sizeFromShape(input.shape) < sizeThreshold);
|
|
}
|
|
getGPGPUContext() {
|
|
return this.gpgpu;
|
|
}
|
|
where(condition) {
|
|
(0, _tfjsCore.backend_util).warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");
|
|
const condVals = condition.dataSync();
|
|
return whereImpl(condition.shape, condVals);
|
|
}
|
|
packedUnaryOp(x, op, dtype) {
|
|
const program = new (0, _unaryopPackedGpu.UnaryOpPackedProgram)(x.shape, op);
|
|
const outInfo = this.compileAndRun(program, [
|
|
x
|
|
], dtype);
|
|
return (0, _tfjsCore.engine)().makeTensorFromTensorInfo(outInfo);
|
|
}
|
|
// TODO(msoulanille) remove this once the backend has been modularized
|
|
// a copy is needed here to break a circular dependency.
|
|
// Also remove the op from unary_op.
|
|
abs(x) {
|
|
// TODO: handle cases when x is complex.
|
|
if (this.shouldExecuteOnCPU([
|
|
x
|
|
]) && x.dtype !== "complex64") {
|
|
const outValues = (0, _shared.simpleAbsImplCPU)(this.texData.get(x.dataId).values);
|
|
return this.makeOutput(x.shape, x.dtype, outValues);
|
|
}
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_PACK_UNARY_OPERATIONS")) return this.packedUnaryOp(x, _unaryopGpu.ABS, x.dtype);
|
|
const program = new (0, _unaryopGpu.UnaryOpProgram)(x.shape, _unaryopGpu.ABS);
|
|
const outInfo = this.compileAndRun(program, [
|
|
x
|
|
]);
|
|
return (0, _tfjsCore.engine)().makeTensorFromTensorInfo(outInfo);
|
|
}
|
|
makeTensorInfo(shape, dtype, values) {
|
|
let dataId;
|
|
if (dtype === "string" && values != null && values.length > 0 && (0, _tfjsCore.util).isString(values[0])) {
|
|
const encodedValues = values.map((d)=>(0, _tfjsCore.util).encodeString(d));
|
|
dataId = this.write(encodedValues, shape, dtype);
|
|
} else dataId = this.write(values, shape, dtype);
|
|
this.texData.get(dataId).usage = null;
|
|
return {
|
|
dataId,
|
|
shape,
|
|
dtype
|
|
};
|
|
}
|
|
makeOutput(shape, dtype, values) {
|
|
return (0, _tfjsCore.engine)().makeTensorFromTensorInfo(this.makeTensorInfo(shape, dtype, values), this);
|
|
}
|
|
unpackTensor(input) {
|
|
const program = new (0, _unpackGpu.UnpackProgram)(input.shape);
|
|
return this.runWebGLProgram(program, [
|
|
input
|
|
], input.dtype);
|
|
}
|
|
packTensor(input) {
|
|
const program = new (0, _packGpu.PackProgram)(input.shape);
|
|
const preventEagerUnpackingOutput = true;
|
|
return this.runWebGLProgram(program, [
|
|
input
|
|
], input.dtype, null, preventEagerUnpackingOutput);
|
|
}
|
|
packedReshape(input, afterShape) {
|
|
const input3DShape = [
|
|
_webglUtil.getBatchDim(input.shape),
|
|
..._webglUtil.getRowsCols(input.shape)
|
|
];
|
|
const input3D = {
|
|
dtype: input.dtype,
|
|
shape: input3DShape,
|
|
dataId: input.dataId
|
|
};
|
|
const afterShapeAs3D = [
|
|
_webglUtil.getBatchDim(afterShape),
|
|
..._webglUtil.getRowsCols(afterShape)
|
|
];
|
|
const program = new (0, _reshapePackedGpu.ReshapePackedProgram)(afterShapeAs3D, input3DShape);
|
|
const preventEagerUnpackingOfOutput = true;
|
|
const customValues = [
|
|
input3DShape
|
|
];
|
|
const output = this.runWebGLProgram(program, [
|
|
input3D
|
|
], input.dtype, customValues, preventEagerUnpackingOfOutput);
|
|
return {
|
|
dataId: output.dataId,
|
|
shape: afterShape,
|
|
dtype: output.dtype
|
|
};
|
|
}
|
|
decode(dataId, customTexShape) {
|
|
const texData = this.texData.get(dataId);
|
|
const { isPacked, shape, dtype } = texData;
|
|
if (customTexShape != null) {
|
|
const size = (0, _tfjsCore.util).sizeFromShape(shape);
|
|
const texSize = customTexShape[0] * customTexShape[1] * 4;
|
|
(0, _tfjsCore.util).assert(size <= texSize, ()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.");
|
|
}
|
|
const shapeAs3D = _webglUtil.getShapeAs3D(shape);
|
|
let program;
|
|
if (isPacked) program = new (0, _decodeMatrixPackedGpu.DecodeMatrixPackedProgram)(shapeAs3D);
|
|
else program = new (0, _decodeMatrixGpu.DecodeMatrixProgram)(shapeAs3D);
|
|
const preventEagerUnpackingOfOutput = true;
|
|
const customValues = [
|
|
customTexShape != null ? customTexShape : _texUtil.getDenseTexShape(shapeAs3D)
|
|
];
|
|
const out = this.runWebGLProgram(program, [
|
|
{
|
|
shape: shapeAs3D,
|
|
dtype,
|
|
dataId
|
|
}
|
|
], dtype, customValues, preventEagerUnpackingOfOutput, customTexShape);
|
|
return {
|
|
dtype,
|
|
shape,
|
|
dataId: out.dataId
|
|
};
|
|
}
|
|
runWebGLProgram(program, inputs, outputDtype, customUniformValues, preventEagerUnpackingOfOutput = false, customTexShape) {
|
|
const output = this.makeTensorInfo(program.outputShape, outputDtype);
|
|
const outData = this.texData.get(output.dataId);
|
|
if (program.packedOutput) outData.isPacked = true;
|
|
if (program.outPackingScheme === _texUtil.PackingScheme.DENSE) {
|
|
const texelShape = customTexShape != null ? customTexShape : _texUtil.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 ((0, _tfjsCore.util).sizeFromShape(output.shape) === 0) {
|
|
// Short-circuit the computation since the result is empty (has 0 in its
|
|
// shape).
|
|
outData.values = (0, _tfjsCore.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 && (0, _tfjsCore.util).sizeFromShape(input.shape) <= (0, _tfjsCore.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;
|
|
}
|
|
}
|
|
this.uploadToGPU(input.dataId);
|
|
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 && !_webglUtil.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;
|
|
}
|
|
return {
|
|
shape: input.shape,
|
|
texData,
|
|
isUniform: false
|
|
};
|
|
});
|
|
this.uploadToGPU(output.dataId);
|
|
const outputData = {
|
|
shape: output.shape,
|
|
texData: outData,
|
|
isUniform: false
|
|
};
|
|
const key = _gpgpuMath.makeShaderKey(program, inputsData, outputData);
|
|
const binary = this.getAndSaveBinary(key, ()=>{
|
|
return _gpgpuMath.compileProgram(this.gpgpu, program, inputsData, outputData);
|
|
});
|
|
const shouldTimeProgram = this.activeTimers != null;
|
|
let query;
|
|
if (shouldTimeProgram) query = this.startTimer();
|
|
if (!(0, _tfjsCore.env)().get("ENGINE_COMPILE_ONLY")) _gpgpuMath.runProgram(this.gpgpu, binary, inputsData, outputData, customUniformValues);
|
|
dataToDispose.forEach((info)=>this.disposeIntermediateTensorInfo(info));
|
|
if (shouldTimeProgram) {
|
|
query = this.endTimer(query);
|
|
this.activeTimers.push({
|
|
name: program.constructor.name,
|
|
query: this.getQueryTime(query)
|
|
});
|
|
}
|
|
const glFlushThreshold = (0, _tfjsCore.env)().getNumber("WEBGL_FLUSH_THRESHOLD");
|
|
// Manually GL flush requested
|
|
if (glFlushThreshold > 0) {
|
|
const time = (0, _tfjsCore.util).now();
|
|
if (time - this.lastGlFlushTime > glFlushThreshold) {
|
|
this.gpgpu.gl.flush();
|
|
this.lastGlFlushTime = time;
|
|
}
|
|
}
|
|
if (!(0, _tfjsCore.env)().getBool("WEBGL_LAZILY_UNPACK") && outData.isPacked && preventEagerUnpackingOfOutput === false) {
|
|
const unpacked = this.unpackTensor(output);
|
|
this.disposeIntermediateTensorInfo(output);
|
|
return unpacked;
|
|
}
|
|
return output;
|
|
}
|
|
compileAndRun(program, inputs, outputDtype, customUniformValues, preventEagerUnpackingOfOutput = false) {
|
|
outputDtype = outputDtype || inputs[0].dtype;
|
|
const outInfo = this.runWebGLProgram(program, inputs, outputDtype, customUniformValues, preventEagerUnpackingOfOutput);
|
|
return outInfo;
|
|
}
|
|
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 (!(0, _tfjsCore.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 = (0, _tfjsCore.tidy)(()=>{
|
|
if (!(0, _tfjsCore.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 = (0, _tfjsCore.env)().getBool("DEBUG");
|
|
(0, _tfjsCore.env)().set("DEBUG", false);
|
|
const underflowCheckValue = this.abs((0, _tfjsCore.scalar)(1e-8)).dataSync()[0];
|
|
(0, _tfjsCore.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 = (0, _tfjsCore.util).now();
|
|
let texShape = texData.texShape;
|
|
if (texShape == null) {
|
|
// This texShape may not be the final texture shape. For packed or dense
|
|
// textures, the texShape will be changed when textures are created.
|
|
texShape = _webglUtil.getTextureShapeFromLogicalShape(shape, isPacked);
|
|
texData.texShape = texShape;
|
|
}
|
|
if (values != null) {
|
|
const shapeAs3D = _webglUtil.getShapeAs3D(shape);
|
|
let program;
|
|
let width = texShape[1], height = texShape[0];
|
|
const isByteArray = values instanceof Uint8Array || values instanceof Uint8ClampedArray;
|
|
// texture for float array is PhysicalTextureType.PACKED_2X2_FLOAT32, we
|
|
// need to make sure the upload uses the same packed size
|
|
if (isPacked || !isByteArray) [width, height] = _texUtil.getPackedMatrixTextureShapeWidthHeight(texShape[0], texShape[1]);
|
|
if (isPacked) program = new (0, _encodeMatrixPackedGpu.EncodeMatrixPackedProgram)(shapeAs3D, isByteArray);
|
|
else program = new (0, _encodeMatrixGpu.EncodeMatrixProgram)(shapeAs3D, isByteArray);
|
|
// TexShape for float array needs to be the original shape, which byte
|
|
// array needs to be packed size. This allow the data upload shape to be
|
|
// matched with texture creation logic.
|
|
const tempDenseInputTexShape = isByteArray ? [
|
|
height,
|
|
width
|
|
] : texShape;
|
|
const tempDenseInputHandle = this.makeTensorInfo(tempDenseInputTexShape, dtype);
|
|
const tempDenseInputTexData = this.texData.get(tempDenseInputHandle.dataId);
|
|
if (isByteArray) tempDenseInputTexData.usage = (0, _texUtil.TextureUsage).PIXELS;
|
|
else tempDenseInputTexData.usage = (0, _texUtil.TextureUsage).UPLOAD;
|
|
tempDenseInputTexData.texShape = tempDenseInputTexShape;
|
|
this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(tempDenseInputHandle.dataId), width, height, values);
|
|
const customValues = [
|
|
[
|
|
height,
|
|
width
|
|
]
|
|
];
|
|
// We want the output to remain packed regardless of the value of
|
|
// WEBGL_PACK.
|
|
const preventEagerUnpacking = true;
|
|
const encodedOutputTarget = this.runWebGLProgram(program, [
|
|
tempDenseInputHandle
|
|
], dtype, customValues, preventEagerUnpacking);
|
|
// Have the original texture assume the identity of the encoded output.
|
|
const outputTexData = this.texData.get(encodedOutputTarget.dataId);
|
|
texData.texShape = outputTexData.texShape;
|
|
texData.isPacked = outputTexData.isPacked;
|
|
texData.usage = outputTexData.usage;
|
|
if (!(0, _tfjsCore.env)().get("ENGINE_COMPILE_ONLY")) {
|
|
texData.texture = outputTexData.texture;
|
|
// Once uploaded, don't store the values on cpu.
|
|
texData.values = null;
|
|
this.texData.delete(encodedOutputTarget.dataId);
|
|
} else this.disposeData(encodedOutputTarget.dataId);
|
|
this.disposeIntermediateTensorInfo(tempDenseInputHandle);
|
|
if (shouldTimeProgram) this.uploadWaitMs += (0, _tfjsCore.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;
|
|
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 * 1048576) {
|
|
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] * (0, _tfjsCore.util).bytesPerElement(dtype);
|
|
}
|
|
checkCompileCompletion() {
|
|
for (const [, binary] of Object.entries(this.binaryCache))this.checkCompletion_(binary);
|
|
}
|
|
async checkCompileCompletionAsync() {
|
|
const ps = [];
|
|
if (this.gpgpu.parallelCompilationExtension) {
|
|
for (const [, binary] of Object.entries(this.binaryCache))ps.push(this.checkCompletionAsync_(binary));
|
|
return Promise.all(ps);
|
|
} else {
|
|
for (const [, binary] of Object.entries(this.binaryCache)){
|
|
const p = new Promise((resolve)=>{
|
|
try {
|
|
this.checkCompletion_(binary);
|
|
resolve(true);
|
|
} catch (error) {
|
|
throw error;
|
|
}
|
|
});
|
|
ps.push(p);
|
|
}
|
|
return Promise.all(ps);
|
|
}
|
|
}
|
|
async checkCompletionAsync_(binary) {
|
|
if (this.gpgpu.gl.getProgramParameter(binary.webGLProgram, this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)) return this.checkCompletion_(binary);
|
|
else {
|
|
await (0, _tfjsCore.nextFrame)();
|
|
return this.checkCompletionAsync_(binary);
|
|
}
|
|
}
|
|
checkCompletion_(binary) {
|
|
if (this.gpgpu.gl.getProgramParameter(binary.webGLProgram, this.gpgpu.gl.LINK_STATUS) === false) {
|
|
console.log(this.gpgpu.gl.getProgramInfoLog(binary.webGLProgram));
|
|
if (this.gpgpu.gl.getShaderParameter(binary.fragmentShader, this.gpgpu.gl.COMPILE_STATUS) === false) {
|
|
_webglUtil.logShaderSourceAndInfoLog(binary.source, this.gpgpu.gl.getShaderInfoLog(binary.fragmentShader));
|
|
throw new Error("Failed to compile fragment shader.");
|
|
}
|
|
throw new Error("Failed to link vertex and fragment shaders.");
|
|
}
|
|
return true;
|
|
}
|
|
getUniformLocations() {
|
|
for (const binary of Object.values(this.binaryCache)){
|
|
// TODO: Iterating through all binaries to build VAOs is supposed to be in
|
|
// a seperate function, like 'setVaos'. However, to avoid breaking changes
|
|
// for the users using parallel compile feature now, buildVao is silently
|
|
// added here.
|
|
this.gpgpu.buildVao(binary.webGLProgram);
|
|
const { variablesLocations, customUniformLocations, infLoc, nanLoc, outShapeLocation, outShapeStridesLocation, outTexShapeLocation } = (0, _gpgpuMath.getUniformLocations)(this.gpgpu, binary.program, binary.webGLProgram);
|
|
binary.variablesLocations = variablesLocations;
|
|
binary.customUniformLocations = customUniformLocations;
|
|
binary.infLoc = infLoc;
|
|
binary.nanLoc = nanLoc;
|
|
binary.outShapeLocation = outShapeLocation;
|
|
binary.outShapeStridesLocation = outShapeStridesLocation;
|
|
binary.outTexShapeLocation = outTexShapeLocation;
|
|
}
|
|
}
|
|
/**
|
|
* Create a TF.js tensor out of an existing WebGL texture. A new texture will
|
|
* be created.
|
|
*/ createTensorFromGPUData(values, shape, dtype) {
|
|
values.channels = values.channels || "RGBA";
|
|
const { texture, height, width, channels } = values;
|
|
const backend = (0, _tfjsCore.engine)().backend;
|
|
// Have to throw an error, otherwise WebGL just warns and returns wrong
|
|
// values.
|
|
if (!backend.gpgpu.gl.isTexture(texture)) throw new Error(`The texture is invalid. Also, please make sure the texture and ` + `the TFJS WebGL backend are using the same canvas. If you want to ` + `use your own custom canvas, you have to create and use the custom ` + `TFJS WebGL backend created from the canvas through ` + `'new tf.MathBackendWebGL(customCanvas)'.`);
|
|
const dataId = backend.writeTexture(texture, shape, dtype, height, width, channels);
|
|
return (0, _tfjsCore.engine)().makeTensorFromDataId(dataId, shape, dtype, backend);
|
|
}
|
|
}
|
|
MathBackendWebGL.nextDataId = 0;
|
|
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}`);
|
|
}
|
|
|
|
},{"./flags_webgl":"fXPM4","@tensorflow/tfjs-core":"21Ftl","./canvas_util":"1tNGf","./decode_matrix_gpu":"b07CY","./decode_matrix_packed_gpu":"gZFiF","./encode_float_gpu":"g6NXt","./encode_float_packed_gpu":"8lMpY","./encode_matrix_gpu":"4fC2J","./encode_matrix_packed_gpu":"aBUBT","./gpgpu_context":"9nvvF","./gpgpu_math":"btJo5","./kernel_utils/shared":"e4M7v","./pack_gpu":"1FCRm","./reshape_packed_gpu":"6lTtb","./tex_util":"1oYRe","./texture_manager":"72VRa","./unaryop_gpu":"gIMrR","./unaryop_packed_gpu":"c4D5K","./unpack_gpu":"6fxgJ","./webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fXPM4":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _webglUtil = require("./webgl_util");
|
|
const ENV = (0, _tfjsCore.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 ((0, _webglUtil.isWebGLVersionEnabled)(2)) return 2;
|
|
else if ((0, _webglUtil.isWebGLVersionEnabled)(1)) return 1;
|
|
return 0;
|
|
});
|
|
/** Whether to check for numerical representation problems. */ ENV.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS", ()=>false);
|
|
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. */ ENV.registerFlag("WEBGL_PACK_DEPTHWISECONV", ()=>ENV.getBool("WEBGL_PACK"));
|
|
/** 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"));
|
|
/** Whether we will pack conv2dTranspose op. */ ENV.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE", ()=>ENV.getBool("WEBGL_PACK"));
|
|
/** The maximum texture dimension. */ ENV.registerFlag("WEBGL_MAX_TEXTURE_SIZE", ()=>(0, _webglUtil.getWebGLMaxTextureSize)(ENV.getNumber("WEBGL_VERSION")));
|
|
/** The maximum texture dimension. */ ENV.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER", ()=>(0, _webglUtil.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 (0, _webglUtil.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 && !(0, _tfjsCore.device_util).isMobile());
|
|
/**
|
|
* Whether the device is physically capable of rendering to float32 textures.
|
|
*/ ENV.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE", ()=>(0, _webglUtil.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", ()=>(0, _webglUtil.isDownloadFloatTextureEnabled)(ENV.getNumber("WEBGL_VERSION")));
|
|
/** Whether the fence API is available. */ ENV.registerFlag("WEBGL_FENCE_API_ENABLED", ()=>(0, _webglUtil.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;
|
|
});
|
|
/**
|
|
* If the total number of bytes allocated on the GPU is greater than this
|
|
* number, we will aggressively delete textures upon disposal with
|
|
* gl.deleteMatrixTexture, rather than making them available for reuse.
|
|
*
|
|
* Default value -1 indicates that we will never aggressively delete textures.
|
|
*/ ENV.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD", ()=>{
|
|
return -1;
|
|
}, (threshold)=>{
|
|
if (!(typeof threshold === "number")) throw new Error("WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but " + `got ${threshold}.`);
|
|
if (threshold < 0 && threshold !== -1) throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never ` + `delete) or at least 0, but got ${threshold}.`);
|
|
});
|
|
/**
|
|
* Trigger a manual GL command flush if the threshold of time has passed since
|
|
* previous Kernel execution. This can be useful for Andorid device where GL
|
|
* command flush are delayed un til the end of javascript task. This value is
|
|
* measured in millisecond. Typically you want to set this value to close to 1.
|
|
*
|
|
* Default value 1 for mobile chrome, and -1 for rest cases. -1 indicates that
|
|
* we will not enforce manual flush and depend on system default flush schedule.
|
|
*/ ENV.registerFlag("WEBGL_FLUSH_THRESHOLD", ()=>{
|
|
return (0, _tfjsCore.device_util).isMobile() ? 1 : -1;
|
|
}, (threshold)=>{
|
|
if (!(typeof threshold === "number")) throw new Error("WEBGL_FLUSH_THRESHOLD must be a number but got " + `${threshold}.`);
|
|
if (threshold < 0 && threshold !== -1) throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never ` + `manual flush) or at least 0, but got ${threshold}.`);
|
|
});
|
|
/**
|
|
* Threshold for input tensor size that determines whether WebGL backend will
|
|
* delegate computation to CPU.
|
|
*
|
|
* Default value is 128.
|
|
*/ ENV.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD", ()=>128);
|
|
/** Whether we will use shapes uniforms. */ ENV.registerFlag("WEBGL_USE_SHAPES_UNIFORMS", ()=>false);
|
|
/**
|
|
* Threshold for last dimension of input tensor that determines whether
|
|
* WebGL backend for the Top K op will delegate computation to CPU. If input
|
|
* is smaller than threshold then CPU will be used
|
|
*
|
|
* Default value is 100000.
|
|
*/ ENV.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD", ()=>100000);
|
|
/**
|
|
* Threshold for K that determines whether
|
|
* WebGL backend for the Top K op will delegate computation to CPU. If k
|
|
* is larger than threshold then CPU will be used
|
|
*
|
|
* Default value is 128.
|
|
*/ ENV.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD", ()=>128);
|
|
/** Whether we will use the experimental conv op. */ ENV.registerFlag("WEBGL_EXP_CONV", ()=>false);
|
|
/**
|
|
* If the device performance is low or if no hardware GPU is available, whether
|
|
* software WebGL will be used.
|
|
*/ ENV.registerFlag("SOFTWARE_WEBGL_ENABLED", ()=>ENV.getBool("IS_TEST"));
|
|
/**
|
|
* For narrow texture (physical height or physical width is 1), if the length of
|
|
* any texture edges exceed the threshold, the texture will be reshaped to be
|
|
* more squarish.
|
|
*
|
|
* This flag is used to help some GPUs that could not provide correct
|
|
* interpolations for long skinny triangles. We found Mali GPU probably has this
|
|
* problem: https://github.com/tensorflow/tfjs/issues/6775.
|
|
*/ ENV.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE", ()=>Infinity);
|
|
/**
|
|
* If the flag is set to true, the max size of the narrow texture will be auto
|
|
* computed and it will be considerred as a threshold to reshape the narrow
|
|
* texture to be more squarish.
|
|
*
|
|
* This flag is used to help some GPUs that could not provide correct
|
|
* interpolations for long skinny triangles. We found Mali GPU probably has this
|
|
* problem: https://github.com/tensorflow/tfjs/issues/6775.
|
|
*/ ENV.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE", ()=>false);
|
|
/**
|
|
* Whether to use the customized isnan. It's only useful for webgl2 since webgl1
|
|
* doesn't have the builtin isnan.
|
|
*/ ENV.registerFlag("WEBGL2_ISNAN_CUSTOM", ()=>false);
|
|
/** Experimental flag, whether enter compile only phase. */ ENV.registerFlag("ENGINE_COMPILE_ONLY", ()=>false);
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./webgl_util":"fjf7t"}],"fjf7t":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "callAndCheck", ()=>callAndCheck);
|
|
parcelHelpers.export(exports, "canBeRepresented", ()=>canBeRepresented);
|
|
parcelHelpers.export(exports, "getWebGLErrorMessage", ()=>getWebGLErrorMessage);
|
|
parcelHelpers.export(exports, "getExtensionOrThrow", ()=>getExtensionOrThrow);
|
|
parcelHelpers.export(exports, "createVertexShader", ()=>createVertexShader);
|
|
parcelHelpers.export(exports, "createFragmentShader", ()=>createFragmentShader);
|
|
parcelHelpers.export(exports, "logShaderSourceAndInfoLog", ()=>logShaderSourceAndInfoLog);
|
|
parcelHelpers.export(exports, "createProgram", ()=>createProgram);
|
|
parcelHelpers.export(exports, "linkProgram", ()=>linkProgram);
|
|
/// validateProgram is effectively "If we `useProgram(program); drawArrays();`,
|
|
/// give feedback in log about perf/correctness warnings or errors that would
|
|
/// occur."
|
|
/// So make sure we set up all vertex/texture/sampler/uniform data before
|
|
/// calling validateProgram!
|
|
parcelHelpers.export(exports, "validateProgram", ()=>validateProgram);
|
|
parcelHelpers.export(exports, "createStaticVertexBuffer", ()=>createStaticVertexBuffer);
|
|
parcelHelpers.export(exports, "createStaticIndexBuffer", ()=>createStaticIndexBuffer);
|
|
parcelHelpers.export(exports, "getNumChannels", ()=>getNumChannels);
|
|
parcelHelpers.export(exports, "createTexture", ()=>createTexture);
|
|
parcelHelpers.export(exports, "validateTextureSize", ()=>validateTextureSize);
|
|
parcelHelpers.export(exports, "createFramebuffer", ()=>createFramebuffer);
|
|
parcelHelpers.export(exports, "bindVertexBufferToProgramAttribute", ()=>bindVertexBufferToProgramAttribute);
|
|
parcelHelpers.export(exports, "bindTextureUnit", ()=>bindTextureUnit);
|
|
parcelHelpers.export(exports, "unbindTextureUnit", ()=>unbindTextureUnit);
|
|
parcelHelpers.export(exports, "getProgramUniformLocationOrThrow", ()=>getProgramUniformLocationOrThrow);
|
|
parcelHelpers.export(exports, "getProgramUniformLocation", ()=>getProgramUniformLocation);
|
|
parcelHelpers.export(exports, "bindTextureToProgramUniformSampler", ()=>bindTextureToProgramUniformSampler);
|
|
parcelHelpers.export(exports, "bindCanvasToFramebuffer", ()=>bindCanvasToFramebuffer);
|
|
parcelHelpers.export(exports, "bindColorTextureToFramebuffer", ()=>bindColorTextureToFramebuffer);
|
|
parcelHelpers.export(exports, "unbindColorTextureFromFramebuffer", ()=>unbindColorTextureFromFramebuffer);
|
|
parcelHelpers.export(exports, "validateFramebuffer", ()=>validateFramebuffer);
|
|
parcelHelpers.export(exports, "getFramebufferErrorMessage", ()=>getFramebufferErrorMessage);
|
|
parcelHelpers.export(exports, "getBatchDim", ()=>getBatchDim);
|
|
parcelHelpers.export(exports, "getRowsCols", ()=>getRowsCols);
|
|
parcelHelpers.export(exports, "getShapeAs3D", ()=>getShapeAs3D);
|
|
parcelHelpers.export(exports, "getTextureShapeFromLogicalShape", ()=>getTextureShapeFromLogicalShape);
|
|
/**
|
|
* This determines whether reshaping a packed texture requires rearranging
|
|
* the data within the texture, assuming 2x2 packing.
|
|
*/ parcelHelpers.export(exports, "isReshapeFree", ()=>isReshapeFree);
|
|
parcelHelpers.export(exports, "getWebGLMaxTextureSize", ()=>getWebGLMaxTextureSize);
|
|
parcelHelpers.export(exports, "resetMaxTextureSize", ()=>resetMaxTextureSize);
|
|
parcelHelpers.export(exports, "resetMaxTexturesInShader", ()=>resetMaxTexturesInShader);
|
|
parcelHelpers.export(exports, "getMaxTexturesInShader", ()=>getMaxTexturesInShader);
|
|
parcelHelpers.export(exports, "getWebGLDisjointQueryTimerVersion", ()=>getWebGLDisjointQueryTimerVersion);
|
|
parcelHelpers.export(exports, "hasExtension", ()=>hasExtension);
|
|
parcelHelpers.export(exports, "isWebGLVersionEnabled", ()=>isWebGLVersionEnabled);
|
|
parcelHelpers.export(exports, "isCapableOfRenderingToFloatTexture", ()=>isCapableOfRenderingToFloatTexture);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "isDownloadFloatTextureEnabled", ()=>isDownloadFloatTextureEnabled);
|
|
parcelHelpers.export(exports, "isWebGLFenceEnabled", ()=>isWebGLFenceEnabled);
|
|
parcelHelpers.export(exports, "assertNotComplex", ()=>assertNotComplex);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _canvasUtil = require("./canvas_util");
|
|
var _texUtil = require("./tex_util");
|
|
function callAndCheck(gl, func) {
|
|
const returnValue = func();
|
|
if ((0, _tfjsCore.env)().getBool("DEBUG")) 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 ((0, _tfjsCore.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, extensionName) {
|
|
return throwIfNull(gl, ()=>gl.getExtension(extensionName), 'Extension "' + extensionName + '" not supported on this browser.');
|
|
}
|
|
function createVertexShader(gl, vertexShaderSource) {
|
|
const vertexShader = throwIfNull(gl, ()=>gl.createShader(gl.VERTEX_SHADER), "Unable to create vertex WebGLShader.");
|
|
callAndCheck(gl, ()=>gl.shaderSource(vertexShader, vertexShaderSource));
|
|
callAndCheck(gl, ()=>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, fragmentShaderSource) {
|
|
const fragmentShader = throwIfNull(gl, ()=>gl.createShader(gl.FRAGMENT_SHADER), "Unable to create fragment WebGLShader.");
|
|
callAndCheck(gl, ()=>gl.shaderSource(fragmentShader, fragmentShaderSource));
|
|
callAndCheck(gl, ()=>gl.compileShader(fragmentShader));
|
|
if ((0, _tfjsCore.env)().get("ENGINE_COMPILE_ONLY")) return 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)=>(0, _tfjsCore.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 ${(0, _tfjsCore.util).rightPad(errorLine[0], maxLineLength)}`, "border:1px solid red; background-color:#e3d2d2; color:#a61717");
|
|
console.log(afterErrorLines.join("\n"));
|
|
}
|
|
function createProgram(gl) {
|
|
return throwIfNull(gl, ()=>gl.createProgram(), "Unable to create WebGLProgram.");
|
|
}
|
|
function linkProgram(gl, program) {
|
|
callAndCheck(gl, ()=>gl.linkProgram(program));
|
|
if ((0, _tfjsCore.env)().get("ENGINE_COMPILE_ONLY")) return;
|
|
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, program) {
|
|
callAndCheck(gl, ()=>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, data) {
|
|
const buffer = throwIfNull(gl, ()=>gl.createBuffer(), "Unable to create WebGLBuffer");
|
|
callAndCheck(gl, ()=>gl.bindBuffer(gl.ARRAY_BUFFER, buffer));
|
|
callAndCheck(gl, ()=>gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW));
|
|
return buffer;
|
|
}
|
|
function createStaticIndexBuffer(gl, data) {
|
|
const buffer = throwIfNull(gl, ()=>gl.createBuffer(), "Unable to create WebGLBuffer");
|
|
callAndCheck(gl, ()=>gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer));
|
|
callAndCheck(gl, ()=>gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW));
|
|
return buffer;
|
|
}
|
|
function getNumChannels() {
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 2) return 1;
|
|
return 4;
|
|
}
|
|
function createTexture(gl) {
|
|
return throwIfNull(gl, ()=>gl.createTexture(), "Unable to create WebGLTexture.");
|
|
}
|
|
function validateTextureSize(width, height) {
|
|
const maxTextureSize = (0, _tfjsCore.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) {
|
|
return throwIfNull(gl, ()=>gl.createFramebuffer(), "Unable to create WebGLFramebuffer.");
|
|
}
|
|
function bindVertexBufferToProgramAttribute(gl, 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, ()=>gl.bindBuffer(gl.ARRAY_BUFFER, buffer));
|
|
callAndCheck(gl, ()=>gl.vertexAttribPointer(loc, arrayEntriesPerItem, gl.FLOAT, false, itemStrideInBytes, itemOffsetInBytes));
|
|
callAndCheck(gl, ()=>gl.enableVertexAttribArray(loc));
|
|
return true;
|
|
}
|
|
function bindTextureUnit(gl, texture, textureUnit) {
|
|
validateTextureUnit(gl, textureUnit);
|
|
callAndCheck(gl, ()=>gl.activeTexture(gl.TEXTURE0 + textureUnit));
|
|
callAndCheck(gl, ()=>gl.bindTexture(gl.TEXTURE_2D, texture));
|
|
}
|
|
function unbindTextureUnit(gl, textureUnit) {
|
|
validateTextureUnit(gl, textureUnit);
|
|
callAndCheck(gl, ()=>gl.activeTexture(gl.TEXTURE0 + textureUnit));
|
|
callAndCheck(gl, ()=>gl.bindTexture(gl.TEXTURE_2D, null));
|
|
}
|
|
function getProgramUniformLocationOrThrow(gl, program, uniformName) {
|
|
return throwIfNull(gl, ()=>gl.getUniformLocation(program, uniformName), 'uniform "' + uniformName + '" not present in program.');
|
|
}
|
|
function getProgramUniformLocation(gl, program, uniformName) {
|
|
return gl.getUniformLocation(program, uniformName);
|
|
}
|
|
function bindTextureToProgramUniformSampler(gl, texture, uniformSamplerLocation, textureUnit) {
|
|
callAndCheck(gl, ()=>bindTextureUnit(gl, texture, textureUnit));
|
|
callAndCheck(gl, ()=>gl.uniform1i(uniformSamplerLocation, textureUnit));
|
|
}
|
|
function bindCanvasToFramebuffer(gl) {
|
|
callAndCheck(gl, ()=>gl.bindFramebuffer(gl.FRAMEBUFFER, null));
|
|
callAndCheck(gl, ()=>gl.viewport(0, 0, gl.canvas.width, gl.canvas.height));
|
|
callAndCheck(gl, ()=>gl.scissor(0, 0, gl.canvas.width, gl.canvas.height));
|
|
}
|
|
function bindColorTextureToFramebuffer(gl, texture, framebuffer) {
|
|
callAndCheck(gl, ()=>gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer));
|
|
callAndCheck(gl, ()=>gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0));
|
|
}
|
|
function unbindColorTextureFromFramebuffer(gl, framebuffer) {
|
|
callAndCheck(gl, ()=>gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer));
|
|
callAndCheck(gl, ()=>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, returnTOrNull, failureMessage) {
|
|
const tOrNull = callAndCheck(gl, ()=>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 (0, _tfjsCore.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 = (0, _tfjsCore.env)().getNumber("WEBGL_MAX_TEXTURE_SIZE");
|
|
let maxSizeForNarrowTex = (0, _tfjsCore.env)().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");
|
|
if (maxSizeForNarrowTex === Infinity && (0, _tfjsCore.env)().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")) maxSizeForNarrowTex = maxTexSize / 2;
|
|
if (isPacked) {
|
|
maxTexSize = maxTexSize * 2;
|
|
maxSizeForNarrowTex = maxSizeForNarrowTex * 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 ? (0, _tfjsCore.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 = (0, _tfjsCore.util).squeezeShape(logShape);
|
|
logShape = squeezeResult.newShape;
|
|
}
|
|
let size = (0, _tfjsCore.util).sizeFromShape(logShape);
|
|
let textureShape = null;
|
|
if (logShape.length <= 1 && size <= maxTexSize) textureShape = [
|
|
1,
|
|
size
|
|
];
|
|
else if (logShape.length === 2 && logShape[0] <= maxTexSize && logShape[1] <= maxTexSize) textureShape = logShape;
|
|
else if (logShape.length === 3 && logShape[0] * logShape[1] <= maxTexSize && logShape[2] <= maxTexSize) textureShape = [
|
|
logShape[0] * logShape[1],
|
|
logShape[2]
|
|
];
|
|
else if (logShape.length === 3 && logShape[0] <= maxTexSize && logShape[1] * logShape[2] <= maxTexSize) textureShape = [
|
|
logShape[0],
|
|
logShape[1] * logShape[2]
|
|
];
|
|
else if (logShape.length === 4 && logShape[0] * logShape[1] * logShape[2] <= maxTexSize && logShape[3] <= maxTexSize) textureShape = [
|
|
logShape[0] * logShape[1] * logShape[2],
|
|
logShape[3]
|
|
];
|
|
else if (logShape.length === 4 && logShape[0] <= maxTexSize && logShape[1] * logShape[2] * logShape[3] <= maxTexSize) textureShape = [
|
|
logShape[0],
|
|
logShape[1] * logShape[2] * logShape[3]
|
|
];
|
|
// true if one edge length is 1 (1 or 2, if packed), while another edge
|
|
// length exceeds maxSizeForNarrowTex.
|
|
const isLongNarrowTex = textureShape != null && Math.max(...textureShape) > maxSizeForNarrowTex && Math.min(...textureShape) <= (isPacked ? 2 : 1) && Math.min(...textureShape) > 0;
|
|
if (textureShape == null || isLongNarrowTex) {
|
|
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);
|
|
textureShape = (0, _tfjsCore.util).sizeToSquarishShape(size).map((d)=>d * 2);
|
|
} else textureShape = (0, _tfjsCore.util).sizeToSquarishShape(size);
|
|
}
|
|
return textureShape;
|
|
}
|
|
function isEven(n) {
|
|
return n % 2 === 0;
|
|
}
|
|
function isReshapeFree(shape1, shape2) {
|
|
shape1 = shape1.slice(-2);
|
|
shape2 = shape2.slice(-2);
|
|
if ((0, _tfjsCore.util).arraysEqual(shape1, shape2)) return true;
|
|
if (!shape1.length || !shape2.length) return true;
|
|
if (shape1[0] === 0 || shape1[1] === 0 || shape2[0] === 0 || shape2[1] === 0) return true;
|
|
if (shape1.length !== shape2.length) {
|
|
const shape1Cols = shape1[shape1.length - 1];
|
|
const shape2Cols = shape2[shape2.length - 1];
|
|
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 = (0, _canvasUtil.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 = (0, _canvasUtil.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 = (0, _canvasUtil.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 = (0, _canvasUtil.getWebGLContext)(webGLVersion);
|
|
if (gl != null) return true;
|
|
} catch (e) {
|
|
console.log("Error when getting WebGL context: ", e);
|
|
return false;
|
|
}
|
|
return false;
|
|
}
|
|
function isCapableOfRenderingToFloatTexture(webGLVersion) {
|
|
if (webGLVersion === 0) return false;
|
|
const gl = (0, _canvasUtil.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;
|
|
}
|
|
function isDownloadFloatTextureEnabled(webGLVersion) {
|
|
if (webGLVersion === 0) return false;
|
|
const gl = (0, _canvasUtil.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 = (0, _texUtil.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 = (0, _texUtil.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 = (0, _canvasUtil.getWebGLContext)(webGLVersion);
|
|
// tslint:disable-next-line:no-any
|
|
const isEnabled = gl.fenceSync != null;
|
|
return isEnabled;
|
|
}
|
|
function assertNotComplex(tensor, opName) {
|
|
if (!Array.isArray(tensor)) tensor = [
|
|
tensor
|
|
];
|
|
tensor.forEach((t)=>{
|
|
if (t != null) (0, _tfjsCore.util).assert(t.dtype !== "complex64", ()=>`${opName} does not support complex64 tensors ` + "in the WebGL backend.");
|
|
});
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./canvas_util":"1tNGf","./tex_util":"1oYRe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1tNGf":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "clearWebGLContext", ()=>clearWebGLContext);
|
|
parcelHelpers.export(exports, "setWebGLContext", ()=>setWebGLContext);
|
|
parcelHelpers.export(exports, "getWebGLContext", ()=>getWebGLContext);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const contexts = {};
|
|
const WEBGL_ATTRIBUTES = {
|
|
alpha: false,
|
|
antialias: false,
|
|
premultipliedAlpha: false,
|
|
preserveDrawingBuffer: false,
|
|
depth: false,
|
|
stencil: false,
|
|
failIfMajorPerformanceCaveat: true
|
|
};
|
|
function clearWebGLContext(webGLVersion) {
|
|
delete contexts[webGLVersion];
|
|
}
|
|
function setWebGLContext(webGLVersion, gl) {
|
|
contexts[webGLVersion] = gl;
|
|
}
|
|
function getWebGLContext(webGLVersion, customCanvas) {
|
|
if (!(webGLVersion in contexts) || customCanvas != null) {
|
|
const newCtx = getWebGLRenderingContext(webGLVersion, customCanvas);
|
|
if (newCtx !== null) contexts[webGLVersion] = newCtx;
|
|
else {
|
|
console.log("Could not get context for WebGL version", webGLVersion);
|
|
return null;
|
|
}
|
|
}
|
|
const gl = contexts[webGLVersion];
|
|
if (gl == null || 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) {
|
|
// Use canvas element for Safari, since its offscreen canvas does not support
|
|
// fencing.
|
|
if (!(0, _tfjsCore.env)().getBool("IS_SAFARI") && 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, customCanvas) {
|
|
if (webGLVersion !== 1 && webGLVersion !== 2) throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");
|
|
const canvas = customCanvas == null ? createCanvas(webGLVersion) : customCanvas;
|
|
canvas.addEventListener("webglcontextlost", (ev)=>{
|
|
ev.preventDefault();
|
|
delete contexts[webGLVersion];
|
|
}, false);
|
|
if ((0, _tfjsCore.env)().getBool("SOFTWARE_WEBGL_ENABLED")) WEBGL_ATTRIBUTES.failIfMajorPerformanceCaveat = false;
|
|
if (webGLVersion === 1) return(// tslint:disable-next-line
|
|
canvas.getContext("webgl", WEBGL_ATTRIBUTES) || canvas.getContext("experimental-webgl", WEBGL_ATTRIBUTES));
|
|
return canvas.getContext("webgl2", WEBGL_ATTRIBUTES);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1oYRe":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "PackingScheme", ()=>PackingScheme);
|
|
parcelHelpers.export(exports, "TextureUsage", ()=>TextureUsage);
|
|
parcelHelpers.export(exports, "PhysicalTextureType", ()=>PhysicalTextureType);
|
|
parcelHelpers.export(exports, "getUnpackedMatrixTextureShapeWidthHeight", ()=>getUnpackedMatrixTextureShapeWidthHeight);
|
|
parcelHelpers.export(exports, "getUnpackedArraySizeFromMatrixSize", ()=>getUnpackedArraySizeFromMatrixSize);
|
|
parcelHelpers.export(exports, "getColorMatrixTextureShapeWidthHeight", ()=>getColorMatrixTextureShapeWidthHeight);
|
|
/**
|
|
* Get shape for densely packed RGBA texture.
|
|
*/ parcelHelpers.export(exports, "getDenseTexShape", ()=>getDenseTexShape);
|
|
parcelHelpers.export(exports, "getMatrixSizeFromUnpackedArraySize", ()=>getMatrixSizeFromUnpackedArraySize);
|
|
parcelHelpers.export(exports, "decodeMatrixFromUnpackedColorRGBAArray", ()=>decodeMatrixFromUnpackedColorRGBAArray);
|
|
parcelHelpers.export(exports, "getPackedMatrixTextureShapeWidthHeight", ()=>getPackedMatrixTextureShapeWidthHeight);
|
|
parcelHelpers.export(exports, "getPackedRGBAArraySizeFromMatrixShape", ()=>getPackedRGBAArraySizeFromMatrixShape);
|
|
parcelHelpers.export(exports, "getTextureConfig", ()=>getTextureConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
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
|
|
];
|
|
}
|
|
function getDenseTexShape(shape) {
|
|
const size = (0, _tfjsCore.util).sizeFromShape(shape);
|
|
const texelsNeeded = Math.ceil(size / 4);
|
|
return (0, _tfjsCore.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 ((0, _tfjsCore.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;
|
|
downloadTextureFormat = glany.RGBA8;
|
|
} 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
|
|
};
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b07CY":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DecodeMatrixProgram", ()=>DecodeMatrixProgram);
|
|
var _glslVersion = require("./glsl_version");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _shaderCompilerUtil = require("./shader_compiler_util");
|
|
var _texUtil = require("./tex_util");
|
|
class DecodeMatrixProgram {
|
|
constructor(outputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = false;
|
|
this.packedOutput = true;
|
|
this.outPackingScheme = (0, _texUtil.PackingScheme).DENSE;
|
|
this.customUniforms = [
|
|
{
|
|
name: "texShape",
|
|
type: "ivec2"
|
|
}
|
|
];
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
this.outputShape = outputShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
this.userCode = `
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms ? _shaderCompilerUtil.getOutputLogicalCoordinatesFromFlatIndexByUniform([
|
|
"r",
|
|
"c",
|
|
"d"
|
|
], outputShape) : _shaderCompilerUtil.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;
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./glsl_version":"kG2vE","./gpgpu_math":"btJo5","./shader_compiler_util":"4ROqF","./tex_util":"1oYRe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kG2vE":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getGlslDifferences", ()=>getGlslDifferences);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function getGlslDifferences() {
|
|
let version;
|
|
let attribute;
|
|
let varyingVs;
|
|
let varyingFs;
|
|
let texture2D;
|
|
let output;
|
|
let defineOutput;
|
|
let defineSpecialNaN;
|
|
let defineSpecialInf;
|
|
let defineRound;
|
|
if ((0, _tfjsCore.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. Since WebGL2 supports uint type and
|
|
// floatBitsToUinT built-in function, we could implment isnan following
|
|
// IEEE 754 rules.
|
|
// NaN defination in IEEE 754-1985 is :
|
|
// - sign = either 0 or 1.
|
|
// - biased exponent = all 1 bits.
|
|
// - fraction = anything except all 0 bits (since all 0 bits represents
|
|
// infinity).
|
|
// https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers
|
|
defineSpecialNaN = (0, _tfjsCore.env)().getBool("WEBGL2_ISNAN_CUSTOM") ? `
|
|
bool isnan_custom(float val) {
|
|
uint floatToUint = floatBitsToUint(val);
|
|
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
|
|
}
|
|
|
|
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
|
|
};
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"btJo5":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "compileProgram", ()=>compileProgram);
|
|
parcelHelpers.export(exports, "getUniformLocations", ()=>getUniformLocations);
|
|
parcelHelpers.export(exports, "runProgram", ()=>runProgram);
|
|
parcelHelpers.export(exports, "makeShaderKey", ()=>makeShaderKey);
|
|
parcelHelpers.export(exports, "useShapeUniforms", ()=>useShapeUniforms);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
var _webglUtil = require("./webgl_util");
|
|
function compileProgram(gpgpu, program, inputs, output) {
|
|
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 = _shaderCompiler.makeShader(inputInfos, outShapeInfo, program);
|
|
const fragmentShader = (0, _webglUtil.createFragmentShader)(gpgpu.gl, source);
|
|
const webGLProgram = gpgpu.createProgram(fragmentShader);
|
|
if (!(0, _tfjsCore.env)().get("ENGINE_COMPILE_ONLY")) {
|
|
gpgpu.buildVao(webGLProgram);
|
|
return Object.assign({
|
|
program,
|
|
fragmentShader,
|
|
source,
|
|
webGLProgram,
|
|
inShapeInfos,
|
|
outShapeInfo
|
|
}, getUniformLocations(gpgpu, program, webGLProgram));
|
|
} else return {
|
|
program,
|
|
fragmentShader,
|
|
source,
|
|
webGLProgram,
|
|
inShapeInfos,
|
|
outShapeInfo,
|
|
variablesLocations: null,
|
|
customUniformLocations: null,
|
|
infLoc: null,
|
|
nanLoc: null,
|
|
outShapeLocation: null,
|
|
outShapeStridesLocation: null,
|
|
outTexShapeLocation: null
|
|
};
|
|
}
|
|
function getUniformLocations(gpgpu, program, webGLProgram) {
|
|
const variablesLocations = [];
|
|
const customUniformLocations = [];
|
|
let outShapeLocation;
|
|
let outTexShapeLocation;
|
|
let outShapeStridesLocation;
|
|
let infLoc = null;
|
|
let nanLoc = null;
|
|
// Add special uniforms (NAN, INFINITY)
|
|
nanLoc = gpgpu.getUniformLocation(webGLProgram, "NAN", false);
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 1) infLoc = gpgpu.getUniformLocation(webGLProgram, "INFINITY", false);
|
|
// Add user-defined uniforms
|
|
const shouldThrow = false;
|
|
for (const varName of program.variableNames){
|
|
const varLocs = {
|
|
name: varName,
|
|
uniform: gpgpu.getUniformLocation(webGLProgram, varName, shouldThrow),
|
|
offset: gpgpu.getUniformLocation(webGLProgram, `offset${varName}`, shouldThrow)
|
|
};
|
|
if (program.enableShapeUniforms) {
|
|
varLocs.shape = gpgpu.getUniformLocation(webGLProgram, `${varName}Shape`, shouldThrow);
|
|
varLocs.texShape = gpgpu.getUniformLocation(webGLProgram, `${varName}TexShape`, shouldThrow);
|
|
}
|
|
variablesLocations.push(varLocs);
|
|
}
|
|
if (program.enableShapeUniforms) {
|
|
outShapeLocation = gpgpu.getUniformLocation(webGLProgram, "outShape", shouldThrow);
|
|
outShapeStridesLocation = gpgpu.getUniformLocation(webGLProgram, "outShapeStrides", shouldThrow);
|
|
outTexShapeLocation = gpgpu.getUniformLocation(webGLProgram, "outTexShape", shouldThrow);
|
|
}
|
|
if (program.customUniforms) for (const d of program.customUniforms)customUniformLocations.push(gpgpu.getUniformLocation(webGLProgram, d.name, shouldThrow));
|
|
return {
|
|
variablesLocations,
|
|
customUniformLocations,
|
|
infLoc,
|
|
nanLoc,
|
|
outShapeLocation,
|
|
outShapeStridesLocation,
|
|
outTexShapeLocation
|
|
};
|
|
}
|
|
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 (!(0, _tfjsCore.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 (!(0, _tfjsCore.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, customUniformValues) {
|
|
if (!binary.program.enableShapeUniforms) {
|
|
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.texture, outTexShape[0], outTexShape[1]);
|
|
else gpgpu.setOutputMatrixTexture(outTex.texture, outTexShape[0], outTexShape[1]);
|
|
gpgpu.setProgram(binary.webGLProgram);
|
|
gpgpu.bindVertexArray(binary.webGLProgram.vao);
|
|
// Set special uniforms (NAN, INFINITY)
|
|
if ((0, _tfjsCore.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
|
|
for(let i = 0; i < inputs.length; ++i){
|
|
const input = inputs[i];
|
|
const { uniform: varLoc, offset: varOffsetLoc, shape: varShapeLoc, texShape: varTexShapeLoc } = binary.variablesLocations[i];
|
|
if (varShapeLoc) {
|
|
const { uniformShape } = _shaderCompiler.getUniformInfoFromShape(binary.program.packedInputs, input.shape, input.texData.texShape);
|
|
switch(uniformShape.length){
|
|
case 1:
|
|
gpgpu.gl.uniform1iv(varShapeLoc, new Int32Array(uniformShape));
|
|
break;
|
|
case 2:
|
|
gpgpu.gl.uniform2iv(varShapeLoc, new Int32Array(uniformShape));
|
|
break;
|
|
case 3:
|
|
gpgpu.gl.uniform3iv(varShapeLoc, new Int32Array(uniformShape));
|
|
break;
|
|
case 4:
|
|
gpgpu.gl.uniform4iv(varShapeLoc, new Int32Array(uniformShape));
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
if (varTexShapeLoc) gpgpu.gl.uniform2i(varTexShapeLoc, input.texData.texShape[0], input.texData.texShape[1]);
|
|
if (varLoc == null) continue;
|
|
if (input.isUniform) {
|
|
// Upload the values of the tensor as uniform.
|
|
if ((0, _tfjsCore.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);
|
|
}
|
|
continue;
|
|
}
|
|
// 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.texture, varLoc, i);
|
|
}
|
|
const outShapeLoc = binary.outShapeLocation;
|
|
if (outShapeLoc) switch(output.shape.length){
|
|
case 1:
|
|
gpgpu.gl.uniform1iv(outShapeLoc, new Int32Array(output.shape));
|
|
break;
|
|
case 2:
|
|
gpgpu.gl.uniform2iv(outShapeLoc, new Int32Array(output.shape));
|
|
break;
|
|
case 3:
|
|
gpgpu.gl.uniform3iv(outShapeLoc, new Int32Array(output.shape));
|
|
break;
|
|
case 4:
|
|
gpgpu.gl.uniform4iv(outShapeLoc, new Int32Array(output.shape));
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
if (binary.outShapeStridesLocation) {
|
|
const strides = (0, _tfjsCore.util).computeStrides(output.shape);
|
|
switch(output.shape.length){
|
|
case 2:
|
|
gpgpu.gl.uniform1iv(binary.outShapeStridesLocation, new Int32Array(strides));
|
|
break;
|
|
case 3:
|
|
gpgpu.gl.uniform2iv(binary.outShapeStridesLocation, new Int32Array(strides));
|
|
break;
|
|
case 4:
|
|
gpgpu.gl.uniform3iv(binary.outShapeStridesLocation, new Int32Array(strides));
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
if (binary.outTexShapeLocation) gpgpu.gl.uniform2i(binary.outTexShapeLocation, output.texData.texShape[0], output.texData.texShape[1]);
|
|
if (binary.program.customUniforms && customUniformValues) for(let i = 0; i < binary.program.customUniforms.length; ++i){
|
|
const d = binary.program.customUniforms[i];
|
|
const customLoc = binary.customUniformLocations[i];
|
|
const customValue = customUniformValues[i];
|
|
if (d.type === "float") gpgpu.gl.uniform1fv(customLoc, customValue);
|
|
else if (d.type === "vec2") gpgpu.gl.uniform2fv(customLoc, customValue);
|
|
else if (d.type === "vec3") gpgpu.gl.uniform3fv(customLoc, customValue);
|
|
else if (d.type === "vec4") gpgpu.gl.uniform4fv(customLoc, customValue);
|
|
else if (d.type === "int") gpgpu.gl.uniform1iv(customLoc, customValue);
|
|
else if (d.type === "ivec2") gpgpu.gl.uniform2iv(customLoc, customValue);
|
|
else if (d.type === "ivec3") gpgpu.gl.uniform3iv(customLoc, customValue);
|
|
else if (d.type === "ivec4") gpgpu.gl.uniform4iv(customLoc, customValue);
|
|
else throw Error(`uniform type ${d.type} is not supported yet.`);
|
|
}
|
|
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;
|
|
// TODO: Remove the condition of !x.isUniform.
|
|
if (program.enableShapeUniforms && !x.isUniform) {
|
|
const xTexShape = x.texData.texShape;
|
|
const { useSqueezeShape, uniformShape, keptDims } = _shaderCompiler.getUniformInfoFromShape(program.packedInputs, x.shape, xTexShape);
|
|
let rank1 = "", rank2 = "", rank34 = "";
|
|
if (uniformShape.length === 1 && program.packedInputs) {
|
|
const packedTexShape = [
|
|
Math.ceil(xTexShape[0] / 2),
|
|
Math.ceil(xTexShape[1] / 2)
|
|
];
|
|
rank1 = `${packedTexShape[0] > 1}_${packedTexShape[1] > 1}`;
|
|
} else if (uniformShape.length === 2 && !program.packedInputs) rank2 = `${uniformShape[0] > 1}_${uniformShape[1] > 1}`;
|
|
else if (uniformShape.length > 2 && !program.packedInputs) {
|
|
const strides = (0, _tfjsCore.util).computeStrides(uniformShape);
|
|
rank34 = `${strides[0] === xTexShape[1]}_${strides[strides.length - 1] === xTexShape[1]}`;
|
|
}
|
|
const xRank = x.shape.length;
|
|
const isLogicalShapTexShapeEqual = uniformShape.length === 2 && (0, _tfjsCore.util).arraysEqual(x.shape, xTexShape);
|
|
const isScalar = (0, _tfjsCore.util).sizeFromShape(x.shape) === 1;
|
|
const broadcastDims = (0, _tfjsCore.backend_util).getBroadcastDims(x.shape, output.shape);
|
|
const isInOutTexShapeEqual = !program.packedInputs && xRank === output.shape.length && (0, _tfjsCore.util).arraysEqual(xTexShape, output.texData.texShape);
|
|
const isTexShapeGreaterThanOne = program.packedInputs || uniformShape.length > 2 ? "" : `${xTexShape[0] > 1}_${xTexShape[1] > 1}`;
|
|
// These key components are needed due to shader_compiler is embedding
|
|
// them in the shader.
|
|
// |xRank| is used to determine the coords length. See
|
|
// get[Packed]SamplerAtOutputCoords.
|
|
// |isInOutTexShapeEqual| is used to determine whether going to an
|
|
// optimization path in getSamplerAtOutputCoords.
|
|
// |useSqueezeShape| is extracted from squeezeInputInfo of
|
|
// getSampler[2|3|4]D/getPackedSampler3D.
|
|
// |isScalar| is extracted from isInputScalar/isOutputScalar in
|
|
// getPackedSamplerAtOutputCoords.
|
|
// |broadcastDims| is extracted from get[Packed]SamplerAtOutputCoords.
|
|
// |isLogicalShapTexShapeEqual| is used in
|
|
// getOutput[Packed]2DCoords/get[Packed]Sampler2D.
|
|
// |rank1| is used in getOutputPacked1DCoords.
|
|
// |rank2| is used in getOutput2DCoords.
|
|
// |rank34| is used in getSampler3D/getSampler4D.
|
|
// |isTexShapeGreaterThanOne| are used in
|
|
// getSampler[Scalar|1D|2D]/getOutput1DCoords.
|
|
keyInputs += `${xRank}_${isInOutTexShapeEqual}_${useSqueezeShape ? keptDims : ""}_${uniformShape.length}_${isScalar}_${broadcastDims}_${isLogicalShapTexShapeEqual}_${rank1}_${rank2}_${rank34}_${isTexShapeGreaterThanOne}_${hasOffset}`;
|
|
} else {
|
|
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 + `${(0, _tfjsCore.env)().getNumber("WEBGL_VERSION")}`;
|
|
return key;
|
|
}
|
|
function useShapeUniforms(rank) {
|
|
// TODO: Remove the limitaion of rank <= 4.
|
|
return (0, _tfjsCore.env)().getBool("WEBGL_USE_SHAPES_UNIFORMS") && rank <= 4;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./shader_compiler":"5uusa","./webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5uusa":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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.
|
|
* =============================================================================
|
|
*/ // Please make sure the shaker key in makeShaderKey in gpgpu_math.ts is well
|
|
// mapped if any shader source code is changed in this file.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "makeShader", ()=>makeShader);
|
|
parcelHelpers.export(exports, "getCoordsDataType", ()=>getCoordsDataType);
|
|
parcelHelpers.export(exports, "getUniformInfoFromShape", ()=>getUniformInfoFromShape);
|
|
/** Returns a new input info (a copy) that has a squeezed logical shape. */ parcelHelpers.export(exports, "squeezeInputInfo", ()=>squeezeInputInfo);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _glslVersion = require("./glsl_version");
|
|
var _shaderCompilerUtil = require("./shader_compiler_util");
|
|
const { getBroadcastDims } = (0, _tfjsCore.backend_util);
|
|
function makeShader(inputsInfo, outputShape, program) {
|
|
const prefixSnippets = [];
|
|
inputsInfo.forEach((x)=>{
|
|
const size = (0, _tfjsCore.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};`);
|
|
}
|
|
if (program.enableShapeUniforms) {
|
|
const { uniformShape } = getUniformInfoFromShape(program.packedInputs, x.shapeInfo.logicalShape, x.shapeInfo.texShape);
|
|
switch(uniformShape.length){
|
|
case 1:
|
|
prefixSnippets.push(`uniform int ${x.name}Shape;`);
|
|
break;
|
|
case 2:
|
|
prefixSnippets.push(`uniform ivec2 ${x.name}Shape;`);
|
|
break;
|
|
case 3:
|
|
prefixSnippets.push(`uniform ivec3 ${x.name}Shape;`);
|
|
break;
|
|
case 4:
|
|
prefixSnippets.push(`uniform ivec4 ${x.name}Shape;`);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
prefixSnippets.push(`uniform ivec2 ${x.name}TexShape;`);
|
|
}
|
|
});
|
|
if (program.enableShapeUniforms) {
|
|
switch(outputShape.logicalShape.length){
|
|
case 1:
|
|
prefixSnippets.push(`uniform int outShape;`);
|
|
break;
|
|
case 2:
|
|
prefixSnippets.push(`uniform ivec2 outShape;`);
|
|
prefixSnippets.push(`uniform int outShapeStrides;`);
|
|
break;
|
|
case 3:
|
|
prefixSnippets.push(`uniform ivec3 outShape;`);
|
|
prefixSnippets.push(`uniform ivec2 outShapeStrides;`);
|
|
break;
|
|
case 4:
|
|
prefixSnippets.push(`uniform ivec4 outShape;`);
|
|
prefixSnippets.push(`uniform ivec3 outShapeStrides;`);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
prefixSnippets.push(`uniform ivec2 outTexShape;`);
|
|
}
|
|
if (program.customUniforms) program.customUniforms.forEach((d)=>{
|
|
prefixSnippets.push(`uniform ${d.type} ${d.name}${d.arrayIndex ? `[${d.arrayIndex}]` : ""};`);
|
|
});
|
|
const inputPrefixSnippet = prefixSnippets.join("\n");
|
|
const inputSamplingSnippet = inputsInfo.map((x)=>getInputSamplingSnippet(x, outputShape, program.packedInputs, program.enableShapeUniforms)).join("\n");
|
|
const outTexShape = outputShape.texShape;
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
const floatTextureSampleSnippet = getFloatTextureSampleSnippet(glsl);
|
|
let outputSamplingSnippet;
|
|
let floatTextureSetOutputSnippet;
|
|
let shaderPrefix = getShaderPrefix(glsl);
|
|
if (outputShape.isPacked) {
|
|
outputSamplingSnippet = getPackedOutputSamplingSnippet(outputShape.logicalShape, outTexShape, program.enableShapeUniforms);
|
|
floatTextureSetOutputSnippet = getFloatTextureSetRGBASnippet(glsl);
|
|
} else {
|
|
outputSamplingSnippet = getOutputSamplingSnippet(outputShape.logicalShape, outTexShape, program.enableShapeUniforms);
|
|
floatTextureSetOutputSnippet = getFloatTextureSetRSnippet(glsl);
|
|
}
|
|
if (program.packedInputs) shaderPrefix += SHADER_PACKED_PREFIX;
|
|
const source = [
|
|
shaderPrefix,
|
|
floatTextureSampleSnippet,
|
|
floatTextureSetOutputSnippet,
|
|
inputPrefixSnippet,
|
|
outputSamplingSnippet,
|
|
inputSamplingSnippet,
|
|
program.userCode
|
|
].join("\n");
|
|
return source;
|
|
}
|
|
function getSamplerFromInInfo(inInfo, enableShapeUniforms = false) {
|
|
const shape = inInfo.shapeInfo.logicalShape;
|
|
switch(shape.length){
|
|
case 0:
|
|
return getSamplerScalar(inInfo, enableShapeUniforms);
|
|
case 1:
|
|
return getSampler1D(inInfo, enableShapeUniforms);
|
|
case 2:
|
|
return getSampler2D(inInfo, enableShapeUniforms);
|
|
case 3:
|
|
return getSampler3D(inInfo, enableShapeUniforms);
|
|
case 4:
|
|
return getSampler4D(inInfo, enableShapeUniforms);
|
|
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, enableShapeUniforms) {
|
|
const shape = inInfo.shapeInfo.logicalShape;
|
|
switch(shape.length){
|
|
case 0:
|
|
return getPackedSamplerScalar(inInfo);
|
|
case 1:
|
|
return getPackedSampler1D(inInfo, enableShapeUniforms);
|
|
case 2:
|
|
return getPackedSampler2D(inInfo, enableShapeUniforms);
|
|
case 3:
|
|
return getPackedSampler3D(inInfo, enableShapeUniforms);
|
|
default:
|
|
return getPackedSamplerND(inInfo, enableShapeUniforms);
|
|
}
|
|
}
|
|
function getInputSamplingSnippet(inInfo, outShapeInfo, usesPackedTextures = false, enableShapeUniforms) {
|
|
let res = "";
|
|
if (usesPackedTextures) res += getPackedSamplerFromInInfo(inInfo, enableShapeUniforms);
|
|
else res += getSamplerFromInInfo(inInfo, enableShapeUniforms);
|
|
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, enableShapeUniforms) {
|
|
switch(outShape.length){
|
|
case 0:
|
|
return getOutputScalarCoords();
|
|
case 1:
|
|
return getOutputPacked1DCoords(outShape, outTexShape, enableShapeUniforms);
|
|
case 2:
|
|
return getOutputPacked2DCoords(outShape, outTexShape, enableShapeUniforms);
|
|
case 3:
|
|
return getOutputPacked3DCoords(outShape, outTexShape, enableShapeUniforms);
|
|
default:
|
|
return getOutputPackedNDCoords(outShape, outTexShape, enableShapeUniforms);
|
|
}
|
|
}
|
|
function getOutputSamplingSnippet(outShape, outTexShape, enableShapeUniforms) {
|
|
switch(outShape.length){
|
|
case 0:
|
|
return getOutputScalarCoords();
|
|
case 1:
|
|
return getOutput1DCoords(outShape, outTexShape, enableShapeUniforms);
|
|
case 2:
|
|
return getOutput2DCoords(outShape, outTexShape, enableShapeUniforms);
|
|
case 3:
|
|
return getOutput3DCoords(outShape, outTexShape, enableShapeUniforms);
|
|
case 4:
|
|
return getOutput4DCoords(outShape, outTexShape, enableShapeUniforms);
|
|
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, enableShapeUniforms) {
|
|
const packedTexShape = [
|
|
Math.ceil(texShape[0] / 2),
|
|
Math.ceil(texShape[1] / 2)
|
|
];
|
|
if (packedTexShape[0] === 1) {
|
|
if (enableShapeUniforms) return `
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
|
|
}
|
|
`;
|
|
return `
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${packedTexShape[1]}.0);
|
|
}
|
|
`;
|
|
}
|
|
if (packedTexShape[1] === 1) {
|
|
if (enableShapeUniforms) return `
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
|
|
}
|
|
`;
|
|
return `
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${packedTexShape[0]}.0);
|
|
}
|
|
`;
|
|
}
|
|
if (enableShapeUniforms) return `
|
|
int getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
|
|
}
|
|
`;
|
|
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, enableShapeUniforms) {
|
|
if (texShape[0] === 1) {
|
|
if (enableShapeUniforms) return `
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * float(outTexShape[1]));
|
|
}
|
|
`;
|
|
return `
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * ${texShape[1]}.0);
|
|
}
|
|
`;
|
|
}
|
|
if (texShape[1] === 1) {
|
|
if (enableShapeUniforms) return `
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * float(outTexShape[0]));
|
|
}
|
|
`;
|
|
return `
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * ${texShape[0]}.0);
|
|
}
|
|
`;
|
|
}
|
|
if (enableShapeUniforms) return `
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
return resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
}
|
|
`;
|
|
return `
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${texShape[0]}, ${texShape[1]}));
|
|
return resTexRC.x * ${texShape[1]} + resTexRC.y;
|
|
}
|
|
`;
|
|
}
|
|
function getOutputPacked3DCoords(shape, texShape, enableShapeUniforms) {
|
|
if (enableShapeUniforms) return `
|
|
ivec3 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
|
|
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
|
|
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);
|
|
}
|
|
`;
|
|
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, enableShapeUniforms) {
|
|
if (enableShapeUniforms) {
|
|
const coordsFromIndexSnippet = _shaderCompilerUtil.getOutputLogicalCoordinatesFromFlatIndexByUniform([
|
|
"r",
|
|
"c",
|
|
"d"
|
|
], shape);
|
|
return `
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${coordsFromIndexSnippet}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;
|
|
}
|
|
const coordsFromIndexSnippet = _shaderCompilerUtil.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, enableShapeUniforms) {
|
|
if (enableShapeUniforms) // TODO: support 5d and 6d
|
|
return `
|
|
ivec4 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
|
|
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
|
|
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
|
|
int texelsInBatchN = texelsInBatch * outShape[1];
|
|
|
|
int b2 = index / texelsInBatchN;
|
|
index -= b2 * texelsInBatchN;
|
|
|
|
int b = index / texelsInBatch;
|
|
index -= b * texelsInBatch;
|
|
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec4(b2, b, r, c);
|
|
}
|
|
`;
|
|
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, enableShapeUniforms) {
|
|
if (enableShapeUniforms) {
|
|
const coordsFromIndexSnippet = _shaderCompilerUtil.getOutputLogicalCoordinatesFromFlatIndexByUniform([
|
|
"r",
|
|
"c",
|
|
"d",
|
|
"d2"
|
|
], shape);
|
|
return `
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${coordsFromIndexSnippet}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;
|
|
}
|
|
const coordsFromIndexSnippet = _shaderCompilerUtil.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 = _shaderCompilerUtil.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 = _shaderCompilerUtil.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, enableShapeUniforms) {
|
|
const packedTexShape = [
|
|
Math.ceil(texShape[0] / 2),
|
|
Math.ceil(texShape[1] / 2)
|
|
];
|
|
if ((0, _tfjsCore.util).arraysEqual(shape, texShape)) {
|
|
if (enableShapeUniforms) return `
|
|
ivec2 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
|
|
}
|
|
`;
|
|
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
|
|
*/ if (enableShapeUniforms) return `
|
|
ivec2 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
|
|
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);
|
|
}
|
|
`;
|
|
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, enableShapeUniforms) {
|
|
if ((0, _tfjsCore.util).arraysEqual(shape, texShape)) {
|
|
if (enableShapeUniforms) return `
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
|
|
}
|
|
`;
|
|
return `
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(${texShape[0]}, ${texShape[1]}));
|
|
}
|
|
`;
|
|
}
|
|
if (shape[1] === 1) {
|
|
if (enableShapeUniforms) return `
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`;
|
|
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) {
|
|
if (enableShapeUniforms) return `
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[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;
|
|
return ivec2(0, index);
|
|
}
|
|
`;
|
|
}
|
|
if (enableShapeUniforms) return `
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
int r = index / outShape[1];
|
|
int c = index - r * outShape[1];
|
|
return ivec2(r, c);
|
|
}
|
|
`;
|
|
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 = (0, _glslVersion.getGlslDifferences)();
|
|
return `
|
|
vec4 ${funcName}() {
|
|
return ${glsl.texture2D}(${texName}, halfCR);
|
|
}
|
|
`;
|
|
}
|
|
function getSamplerScalar(inputInfo, enableShapeUniforms) {
|
|
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 offset = getFlatOffsetUniformName(texName);
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}() {
|
|
vec2 uv = uvFromFlat(${texName}TexShape[0], ${texName}TexShape[1], ${offset});
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
const [tNumR, tNumC] = inputInfo.shapeInfo.texShape;
|
|
return `
|
|
float ${funcName}() {
|
|
vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, ${offset});
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
}
|
|
function getPackedSampler1D(inputInfo, enableShapeUniforms) {
|
|
const texName = inputInfo.name;
|
|
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
|
|
const texShape = inputInfo.shapeInfo.texShape;
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
if (enableShapeUniforms) return `
|
|
vec4 ${funcName}(int index) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${texName}TexShape[0]) / 2.0), ceil(float(${texName}TexShape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom1D(
|
|
packedTexShape[0], packedTexShape[1], index);
|
|
return ${glsl.texture2D}(${texName}, uv);
|
|
}
|
|
`;
|
|
const packedTexShape = [
|
|
Math.ceil(texShape[0] / 2),
|
|
Math.ceil(texShape[1] / 2)
|
|
];
|
|
return `
|
|
vec4 ${funcName}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${packedTexShape[0]}, ${packedTexShape[1]}, index);
|
|
return ${glsl.texture2D}(${texName}, uv);
|
|
}
|
|
`;
|
|
}
|
|
function getSampler1D(inputInfo, enableShapeUniforms) {
|
|
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) {
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${offset}) + 0.5) / float(${texName}TexShape[0]));
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
return `
|
|
float ${funcName}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${offset}) + 0.5) / ${tNumR}.0);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
}
|
|
if (tNumR === 1) {
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int index) {
|
|
vec2 uv = vec2((float(index + ${offset}) + 0.5) / float(${texName}TexShape[1]), 0.5);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
return `
|
|
float ${funcName}(int index) {
|
|
vec2 uv = vec2((float(index + ${offset}) + 0.5) / ${tNumC}.0, 0.5);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
}
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int index) {
|
|
vec2 uv = uvFromFlat(${texName}TexShape[0], ${texName}TexShape[1], index + ${offset});
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
return `
|
|
float ${funcName}(int index) {
|
|
vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, index + ${offset});
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
}
|
|
function getPackedSampler2D(inputInfo, enableShapeUniforms) {
|
|
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 = (0, _glslVersion.getGlslDifferences)();
|
|
if (texShape != null && (0, _tfjsCore.util).arraysEqual(shape, texShape)) {
|
|
if (enableShapeUniforms) return `
|
|
vec4 ${funcName}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${texName}TexShape[1], ${texName}TexShape[0]);
|
|
|
|
return ${glsl.texture2D}(${texName}, uv);
|
|
}
|
|
`;
|
|
return `
|
|
vec4 ${funcName}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
|
|
|
|
return ${glsl.texture2D}(${texName}, uv);
|
|
}
|
|
`;
|
|
}
|
|
if (enableShapeUniforms) return `
|
|
vec4 ${funcName}(int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${texName}TexShape[0]) / 2.0), ceil(float(${texName}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${texName}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
|
|
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, enableShapeUniforms) {
|
|
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 && (0, _tfjsCore.util).arraysEqual(shape, texShape)) {
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${texName}TexShape[1], ${texName}TexShape[0]);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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 } = (0, _tfjsCore.util).squeezeShape(shape);
|
|
const squeezedShape = newShape;
|
|
if (squeezedShape.length < shape.length) {
|
|
const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
|
|
const params = [
|
|
"row",
|
|
"col"
|
|
];
|
|
return `
|
|
${getSamplerFromInInfo(newInputInfo, enableShapeUniforms)}
|
|
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).
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${offset}), vec3(${texName}Shape[1], 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / float(${texName}TexShape[0]));
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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).
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${offset}), vec3(${texName}Shape[1], 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / float(${texName}TexShape[1]), 0.5);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${texName}Shape[1] + col + ${offset};
|
|
vec2 uv = uvFromFlat(${texName}TexShape[0], ${texName}TexShape[1], index);
|
|
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, enableShapeUniforms) {
|
|
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, enableShapeUniforms)}
|
|
vec4 ${funcName}(int b, int row, int col) {
|
|
return ${funcName}(${getSqueezedParams(params, keptDims)});
|
|
}
|
|
`;
|
|
}
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
if (enableShapeUniforms) return `
|
|
vec4 ${funcName}(int b, int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${texName}TexShape[0]) / 2.0), ceil(float(${texName}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${texName}Shape[2]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${texName}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom3D(
|
|
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
|
|
return ${glsl.texture2D}(${texName}, uv);
|
|
}
|
|
`;
|
|
const texNumR = packedTexShape[0];
|
|
const texNumC = packedTexShape[1];
|
|
const valuesPerRow = Math.ceil(shape[2] / 2);
|
|
const texelsInBatch = valuesPerRow * Math.ceil(shape[1] / 2);
|
|
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, enableShapeUniforms) {
|
|
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 } = (0, _tfjsCore.util).squeezeShape(shape);
|
|
const squeezedShape = newShape;
|
|
if (squeezedShape.length < shape.length) {
|
|
const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
|
|
const params = [
|
|
"row",
|
|
"col",
|
|
"depth"
|
|
];
|
|
return `
|
|
${getSamplerFromInInfo(newInputInfo, enableShapeUniforms)}
|
|
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).
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col, int depth) {
|
|
int stride1 = ${texName}Shape[2];
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(stride1, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${texName}TexShape[1], ${texName}TexShape[0]);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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).
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${texName}Shape[1], 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texName}TexShape[1], ${texName}TexShape[0]);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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);
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int stride0 = ${texName}Shape[1] * ${texName}Shape[2];
|
|
int stride1 = ${texName}Shape[2];
|
|
int index = row * stride0 + col * stride1 + depth + ${offset};
|
|
vec2 uv = uvFromFlat(${texName}TexShape[0], ${texName}TexShape[1], index);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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, enableShapeUniforms) {
|
|
const texName = inputInfo.name;
|
|
const funcName = "get" + texName.charAt(0).toUpperCase() + texName.slice(1);
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
if (enableShapeUniforms) // TODO: support 5d and 6d
|
|
return `
|
|
vec4 ${funcName}(int b2, int b, int row, int col) {
|
|
int valuesPerRow = int(ceil(float(${texName}Shape[3]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${texName}Shape[2]) / 2.0));
|
|
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
|
|
texelsInBatch *= ${texName}Shape[1];
|
|
index = b2 * texelsInBatch + index;
|
|
ivec2 packedTexShape = ivec2(ceil(float(${texName}TexShape[0]) / 2.0), ceil(float(${texName}TexShape[1]) / 2.0));
|
|
int texR = index / packedTexShape[1];
|
|
int texC = index - texR * packedTexShape[1];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${glsl.texture2D}(${texName}, uv);
|
|
}
|
|
`;
|
|
const shape = inputInfo.shapeInfo.logicalShape;
|
|
const rank = shape.length;
|
|
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;
|
|
}
|
|
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, enableShapeUniforms) {
|
|
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 } = (0, _tfjsCore.util).squeezeShape(shape);
|
|
if (newShape.length < shape.length) {
|
|
const newInputInfo = squeezeInputInfo(inputInfo, newShape);
|
|
const params = [
|
|
"row",
|
|
"col",
|
|
"depth",
|
|
"depth2"
|
|
];
|
|
return `
|
|
${getSamplerFromInInfo(newInputInfo, enableShapeUniforms)}
|
|
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];
|
|
const stride2Str = `int stride2 = ${texName}Shape[3];`;
|
|
const stride1Str = `int stride1 = ${texName}Shape[2] * stride2;`;
|
|
const stride0Str = `int stride0 = ${texName}Shape[1] * stride1;`;
|
|
if (texNumC === stride0 && flatOffset == null) {
|
|
// texC is used directly as physical (no risk of float16 overflow).
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col, int depth, int depth2) {
|
|
${stride2Str}
|
|
${stride1Str}
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(stride1, stride2, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${texName}TexShape[1], ${texName}TexShape[0]);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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).
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${texName}Shape[1] * ${texName}Shape[2], ${texName}Shape[2], 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${texName}TexShape[1], ${texName}TexShape[0]);
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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);
|
|
if (enableShapeUniforms) return `
|
|
float ${funcName}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
${stride2Str}
|
|
${stride1Str}
|
|
${stride0Str}
|
|
int index = row * stride0 + col * stride1 +
|
|
depth * stride2 + depth2;
|
|
vec2 uv = uvFromFlat(${texName}TexShape[0], ${texName}TexShape[1], index + ${offset});
|
|
return sampleTexture(${texName}, uv);
|
|
}
|
|
`;
|
|
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 } = (0, _tfjsCore.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 } = (0, _tfjsCore.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 = (0, _tfjsCore.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 = (0, _tfjsCore.util).sizeFromShape(inputInfo.shapeInfo.logicalShape);
|
|
const isInputScalar = inSize === 1;
|
|
const outSize = (0, _tfjsCore.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 && (0, _tfjsCore.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`);
|
|
}
|
|
function getUniformInfoFromShape(isPacked, shape, texShape) {
|
|
const { newShape, keptDims } = (0, _tfjsCore.util).squeezeShape(shape);
|
|
const rank = shape.length;
|
|
const useSqueezePackedShape = isPacked && rank === 3 && shape[0] === 1;
|
|
const squeezeShape = useSqueezePackedShape ? shape.slice(1) : newShape;
|
|
const useSqueezeShape = !isPacked && rank > 1 && !(0, _tfjsCore.util).arraysEqual(shape, texShape) && newShape.length < rank || useSqueezePackedShape;
|
|
const uniformShape = useSqueezeShape ? squeezeShape : shape;
|
|
return {
|
|
useSqueezeShape,
|
|
uniformShape,
|
|
keptDims
|
|
};
|
|
}
|
|
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(", ");
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./glsl_version":"kG2vE","./shader_compiler_util":"4ROqF","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4ROqF":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getLogicalCoordinatesFromFlatIndex", ()=>getLogicalCoordinatesFromFlatIndex);
|
|
parcelHelpers.export(exports, "getOutputLogicalCoordinatesFromFlatIndexByUniform", ()=>getOutputLogicalCoordinatesFromFlatIndexByUniform);
|
|
parcelHelpers.export(exports, "getLogicalCoordinatesFromFlatIndexByUniform", ()=>getLogicalCoordinatesFromFlatIndexByUniform);
|
|
/**
|
|
* Produces GLSL code that computes the dot product of the input x and y
|
|
* vectors. Handles splitting inputs into increments of vec4s when necessary.
|
|
*/ parcelHelpers.export(exports, "dotify", ()=>dotify);
|
|
/**
|
|
* Produces GLSL that computes the flat index from 3D coordinates.
|
|
*/ parcelHelpers.export(exports, "getFlatIndexFrom3D", ()=>getFlatIndexFrom3D);
|
|
parcelHelpers.export(exports, "getFlatIndexFrom3DOutput", ()=>getFlatIndexFrom3DOutput);
|
|
parcelHelpers.export(exports, "ENCODE_FLOAT_SNIPPET", ()=>ENCODE_FLOAT_SNIPPET);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function getLogicalCoordinatesFromFlatIndex(coords, shape, index = "index") {
|
|
const strides = (0, _tfjsCore.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 getOutputLogicalCoordinatesFromFlatIndexByUniform(coords, shape, index = "index") {
|
|
const strides = (0, _tfjsCore.util).computeStrides(shape);
|
|
return strides.map((_, i)=>{
|
|
const line1 = `int ${coords[i]} = ${index} / outShapeStrides[${i}]`;
|
|
const line2 = i === strides.length - 1 ? `int ${coords[i + 1]} = ${index} - ${coords[i]} * outShapeStrides[${i}]` : `index -= ${coords[i]} * outShapeStrides[${i}]`;
|
|
return `${line1}; ${line2};`;
|
|
}).join("");
|
|
}
|
|
// Produces GLSL code that computes strides.
|
|
function symbolicallyComputeStrides(indicesArr, variableName) {
|
|
const numCoords = indicesArr.length;
|
|
const shape = indicesArr.map((d)=>`${variableName}[${d}]`);
|
|
const strides = new Array(numCoords - 1);
|
|
strides[numCoords - 2] = shape[numCoords - 1];
|
|
for(let i = numCoords - 3; i >= 0; --i)strides[i] = `(${strides[i + 1]} * ${shape[i + 1]})`;
|
|
return strides;
|
|
}
|
|
function getLogicalCoordinatesFromFlatIndexByUniform(coords, variableName, index = "index") {
|
|
const indicesArray = coords.map((_, i)=>i);
|
|
const strides = symbolicallyComputeStrides(indicesArray, variableName);
|
|
return strides.map((_, i)=>{
|
|
const line1 = `int ${coords[i]} = ${index} / ${strides[i]}`;
|
|
const line2 = i === strides.length - 1 ? `int ${coords[i + 1]} = ${index} - ${coords[i]} * ${strides[i]}` : `index -= ${coords[i]} * ${strides[i]}`;
|
|
return `${line1}; ${line2};`;
|
|
}).join("");
|
|
}
|
|
function buildVec(x) {
|
|
if (x.length === 1) return `${x[0]}`;
|
|
return `vec${x.length}(${x.join(",")})`;
|
|
}
|
|
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("+");
|
|
}
|
|
function getFlatIndexFrom3D(shape) {
|
|
const strides = (0, _tfjsCore.util).computeStrides(shape).map((d)=>d.toString());
|
|
return `
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${strides[0]} + coords.y * ${strides[1]} + coords.z;
|
|
}
|
|
`;
|
|
}
|
|
function getFlatIndexFrom3DOutput() {
|
|
return `
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[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;
|
|
}
|
|
`;
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gZFiF":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DecodeMatrixPackedProgram", ()=>DecodeMatrixPackedProgram);
|
|
var _glslVersion = require("./glsl_version");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _shaderCompilerUtil = require("./shader_compiler_util");
|
|
var _texUtil = require("./tex_util");
|
|
class DecodeMatrixPackedProgram {
|
|
constructor(outputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.outPackingScheme = (0, _texUtil.PackingScheme).DENSE;
|
|
this.customUniforms = [
|
|
{
|
|
name: "texShape",
|
|
type: "ivec2"
|
|
}
|
|
];
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
this.outputShape = outputShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
this.userCode = `
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms ? _shaderCompilerUtil.getOutputLogicalCoordinatesFromFlatIndexByUniform([
|
|
"r",
|
|
"c",
|
|
"d"
|
|
], outputShape) : _shaderCompilerUtil.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;
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./glsl_version":"kG2vE","./gpgpu_math":"btJo5","./shader_compiler_util":"4ROqF","./tex_util":"1oYRe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g6NXt":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "EncodeFloatProgram", ()=>EncodeFloatProgram);
|
|
var _glslVersion = require("./glsl_version");
|
|
var _shaderCompilerUtil = require("./shader_compiler_util");
|
|
var _texUtil = require("./tex_util");
|
|
class EncodeFloatProgram {
|
|
constructor(outputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.outTexUsage = (0, _texUtil.TextureUsage).DOWNLOAD;
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
this.outputShape = outputShape;
|
|
this.userCode = `
|
|
${0, _shaderCompilerUtil.ENCODE_FLOAT_SNIPPET}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${glsl.output} = encode_float(x);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./glsl_version":"kG2vE","./shader_compiler_util":"4ROqF","./tex_util":"1oYRe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8lMpY":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "EncodeFloatPackedProgram", ()=>EncodeFloatPackedProgram);
|
|
var _glslVersion = require("./glsl_version");
|
|
var _shaderCompilerUtil = require("./shader_compiler_util");
|
|
var _texUtil = require("./tex_util");
|
|
class EncodeFloatPackedProgram {
|
|
constructor(outputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = false;
|
|
this.outTexUsage = (0, _texUtil.TextureUsage).DOWNLOAD;
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
this.outputShape = outputShape;
|
|
this.userCode = `
|
|
${0, _shaderCompilerUtil.ENCODE_FLOAT_SNIPPET}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${glsl.output} = encode_float(x);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./glsl_version":"kG2vE","./shader_compiler_util":"4ROqF","./tex_util":"1oYRe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4fC2J":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "EncodeMatrixProgram", ()=>EncodeMatrixProgram);
|
|
var _glslVersion = require("./glsl_version");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _shaderCompilerUtil = require("./shader_compiler_util");
|
|
const CHANNEL_CHAR_TO_INDEX_MAP = {
|
|
"R": 0,
|
|
"G": 1,
|
|
"B": 2,
|
|
"A": 3
|
|
};
|
|
class EncodeMatrixProgram {
|
|
constructor(outputShape, inputIsUnsignedByte = false, usedChannels = "RGBA"){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.customUniforms = [
|
|
{
|
|
name: "texShape",
|
|
type: "ivec2"
|
|
}
|
|
];
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
this.outputShape = outputShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
let output = `result`;
|
|
if (inputIsUnsignedByte) output = `floor(result * 255. + 0.5)`;
|
|
let mainLoop = "";
|
|
for(let usedChannelIndex = 0; usedChannelIndex < usedChannels.length; usedChannelIndex++){
|
|
const curChannel = usedChannels[usedChannelIndex];
|
|
mainLoop += `
|
|
if(offset == ${usedChannelIndex}) {
|
|
result = values[${CHANNEL_CHAR_TO_INDEX_MAP[curChannel]}];
|
|
}`;
|
|
}
|
|
this.userCode = `
|
|
${this.enableShapeUniforms ? _shaderCompilerUtil.getFlatIndexFrom3DOutput() : _shaderCompilerUtil.getFlatIndexFrom3D(outputShape)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int flatIndex = getFlatIndex(coords);
|
|
float result = 0.;
|
|
int offset = imod(flatIndex, ${usedChannels.length});
|
|
|
|
flatIndex = idiv(flatIndex, ${usedChannels.length}, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
if (r < texShape[0]) {
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
vec4 values = ${glsl.texture2D}(A, uv);
|
|
${mainLoop}
|
|
}
|
|
${glsl.output} = vec4(${output}, 0., 0., 0.);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./glsl_version":"kG2vE","./gpgpu_math":"btJo5","./shader_compiler_util":"4ROqF","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aBUBT":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/*
|
|
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.
|
|
*/ parcelHelpers.export(exports, "EncodeMatrixPackedProgram", ()=>EncodeMatrixPackedProgram);
|
|
var _glslVersion = require("./glsl_version");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _shaderCompilerUtil = require("./shader_compiler_util");
|
|
class EncodeMatrixPackedProgram {
|
|
constructor(outputShape, inputIsUnsignedByte = false){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = false;
|
|
this.packedOutput = true;
|
|
this.customUniforms = [
|
|
{
|
|
name: "texShape",
|
|
type: "ivec2"
|
|
}
|
|
];
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
this.outputShape = outputShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
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} < ${this.enableShapeUniforms ? "outShape[2]" : `${outputShape[2]}`}) {
|
|
localCoords[2] += ${col};
|
|
if (localCoords[1] + ${row} < ${this.enableShapeUniforms ? "outShape[1]" : `${outputShape[1]}`}) {
|
|
localCoords[1] += ${row};
|
|
|
|
flatIndex = getFlatIndex(localCoords);
|
|
offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[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 = `
|
|
${this.enableShapeUniforms ? _shaderCompilerUtil.getFlatIndexFrom3DOutput() : _shaderCompilerUtil.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};
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./glsl_version":"kG2vE","./gpgpu_math":"btJo5","./shader_compiler_util":"4ROqF","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9nvvF":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "GPGPUContext", ()=>GPGPUContext);
|
|
/**
|
|
* 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
|
|
*/ parcelHelpers.export(exports, "linearSearchLastTrue", ()=>linearSearchLastTrue);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _canvasUtil = require("./canvas_util");
|
|
var _gpgpuUtil = require("./gpgpu_util");
|
|
var _texUtil = require("./tex_util");
|
|
var _webglUtil = require("./webgl_util");
|
|
class GPGPUContext {
|
|
constructor(gl){
|
|
this.outputTexture = null;
|
|
this.program = null;
|
|
this.disposed = false;
|
|
this.itemsToPoll = [];
|
|
const glVersion = (0, _tfjsCore.env)().getNumber("WEBGL_VERSION");
|
|
if (gl != null) {
|
|
this.gl = gl;
|
|
(0, _canvasUtil.setWebGLContext)(glVersion, gl);
|
|
} else this.gl = (0, _canvasUtil.getWebGLContext)(glVersion);
|
|
gl = this.gl;
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 2) {
|
|
const gl2 = gl;
|
|
this.createVertexArray = ()=>{
|
|
return _webglUtil.callAndCheck(gl2, ()=>gl2.createVertexArray());
|
|
};
|
|
this.bindVertexArray = (vao)=>{
|
|
return _webglUtil.callAndCheck(gl2, ()=>gl2.bindVertexArray(vao));
|
|
};
|
|
this.deleteVertexArray = (vao)=>{
|
|
return _webglUtil.callAndCheck(gl2, ()=>gl2.deleteVertexArray(vao));
|
|
};
|
|
this.getVertexArray = ()=>{
|
|
return _webglUtil.callAndCheck(gl2, ()=>gl2.getParameter(gl2.VERTEX_ARRAY_BINDING));
|
|
};
|
|
} else if (gl != null) {
|
|
const ext = gl.getExtension("OES_vertex_array_object");
|
|
if (ext == null) throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");
|
|
this.createVertexArray = ()=>{
|
|
return _webglUtil.callAndCheck(gl, ()=>ext.createVertexArrayOES());
|
|
};
|
|
this.bindVertexArray = (vao)=>{
|
|
return _webglUtil.callAndCheck(gl, ()=>ext.bindVertexArrayOES(vao));
|
|
};
|
|
this.deleteVertexArray = (vao)=>{
|
|
return _webglUtil.callAndCheck(gl, ()=>ext.deleteVertexArrayOES(vao));
|
|
};
|
|
this.getVertexArray = ()=>{
|
|
return _webglUtil.callAndCheck(gl, ()=>gl.getParameter(ext.VERTEX_ARRAY_BINDING_OES));
|
|
};
|
|
}
|
|
// 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";
|
|
this.parallelCompilationExtension = this.gl.getExtension("KHR_parallel_shader_compile");
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 1) {
|
|
const TEXTURE_FLOAT = "OES_texture_float";
|
|
const TEXTURE_HALF_FLOAT = "OES_texture_half_float";
|
|
this.textureFloatExtension = _webglUtil.getExtensionOrThrow(this.gl, TEXTURE_FLOAT);
|
|
if (_webglUtil.hasExtension(this.gl, TEXTURE_HALF_FLOAT)) this.textureHalfFloatExtension = _webglUtil.getExtensionOrThrow(this.gl, TEXTURE_HALF_FLOAT);
|
|
else if ((0, _tfjsCore.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 (_webglUtil.hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) this.colorBufferHalfFloatExtension = _webglUtil.getExtensionOrThrow(this.gl, COLOR_BUFFER_HALF_FLOAT);
|
|
else if ((0, _tfjsCore.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 (_webglUtil.hasExtension(this.gl, COLOR_BUFFER_FLOAT)) this.colorBufferFloatExtension = this.gl.getExtension(COLOR_BUFFER_FLOAT);
|
|
else if (_webglUtil.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 = _gpgpuUtil.createVertexBuffer(this.gl);
|
|
this.indexBuffer = _gpgpuUtil.createIndexBuffer(this.gl);
|
|
this.framebuffer = _webglUtil.createFramebuffer(this.gl);
|
|
this.textureConfig = _texUtil.getTextureConfig(this.gl, this.textureHalfFloatExtension);
|
|
}
|
|
get debug() {
|
|
return (0, _tfjsCore.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;
|
|
_webglUtil.callAndCheck(gl, ()=>gl.finish());
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindFramebuffer(gl.FRAMEBUFFER, null));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.deleteFramebuffer(this.framebuffer));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindBuffer(gl.ARRAY_BUFFER, null));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.deleteBuffer(this.indexBuffer));
|
|
this.disposed = true;
|
|
}
|
|
createFloat32MatrixTexture(rows, columns) {
|
|
this.throwIfDisposed();
|
|
return _gpgpuUtil.createFloat32MatrixTexture(this.gl, rows, columns, this.textureConfig);
|
|
}
|
|
createFloat16MatrixTexture(rows, columns) {
|
|
this.throwIfDisposed();
|
|
return _gpgpuUtil.createFloat16MatrixTexture(this.gl, rows, columns, this.textureConfig);
|
|
}
|
|
createUnsignedBytesMatrixTexture(rows, columns) {
|
|
this.throwIfDisposed();
|
|
return _gpgpuUtil.createUnsignedBytesMatrixTexture(this.gl, rows, columns, this.textureConfig);
|
|
}
|
|
uploadPixelDataToTexture(texture, pixels) {
|
|
this.throwIfDisposed();
|
|
_gpgpuUtil.uploadPixelDataToTexture(this.gl, texture, pixels);
|
|
}
|
|
uploadDenseMatrixToTexture(texture, width, height, data) {
|
|
this.throwIfDisposed();
|
|
_gpgpuUtil.uploadDenseMatrixToTexture(this.gl, texture, width, height, data, this.textureConfig);
|
|
}
|
|
createFloat16PackedMatrixTexture(rows, columns) {
|
|
this.throwIfDisposed();
|
|
return _gpgpuUtil.createFloat16PackedMatrixTexture(this.gl, rows, columns, this.textureConfig);
|
|
}
|
|
createPackedMatrixTexture(rows, columns) {
|
|
this.throwIfDisposed();
|
|
return _gpgpuUtil.createPackedMatrixTexture(this.gl, rows, columns, this.textureConfig);
|
|
}
|
|
deleteMatrixTexture(texture) {
|
|
this.throwIfDisposed();
|
|
if (this.outputTexture === texture) {
|
|
_webglUtil.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
|
|
this.outputTexture = null;
|
|
}
|
|
_webglUtil.callAndCheck(this.gl, ()=>this.gl.deleteTexture(texture));
|
|
}
|
|
downloadByteEncodedFloatMatrixFromOutputTexture(texture, rows, columns) {
|
|
return this.downloadMatrixDriver(texture, ()=>_gpgpuUtil.downloadByteEncodedFloatMatrixFromOutputTexture(this.gl, rows, columns, this.textureConfig));
|
|
}
|
|
downloadPackedMatrixFromBuffer(buffer, batch, rows, columns, physicalRows, physicalCols) {
|
|
return _gpgpuUtil.downloadPackedMatrixFromBuffer(this.gl, buffer, batch, rows, columns, physicalRows, physicalCols, this.textureConfig);
|
|
}
|
|
downloadFloat32MatrixFromBuffer(buffer, size) {
|
|
return _gpgpuUtil.downloadFloat32MatrixFromBuffer(this.gl, buffer, size);
|
|
}
|
|
createBufferFromTexture(texture, rows, columns) {
|
|
this.bindTextureToFrameBuffer(texture);
|
|
const result = _gpgpuUtil.createBufferFromOutputTexture(this.gl, 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 ((0, _tfjsCore.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 ((0, _tfjsCore.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0) {
|
|
query = this.beginQuery();
|
|
this.endQuery();
|
|
isFencePassed = ()=>this.isQueryAvailable(query, (0, _tfjsCore.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, ()=>_gpgpuUtil.downloadMatrixFromPackedOutputTexture(this.gl, physicalRows, physicalCols));
|
|
}
|
|
createProgram(fragmentShader) {
|
|
this.throwIfDisposed();
|
|
const gl = this.gl;
|
|
if (this.vertexShader == null) this.vertexShader = _gpgpuUtil.createVertexShader(gl);
|
|
const program = _webglUtil.createProgram(gl);
|
|
_webglUtil.callAndCheck(gl, ()=>gl.attachShader(program, this.vertexShader));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.attachShader(program, fragmentShader));
|
|
_webglUtil.linkProgram(gl, program);
|
|
const program2 = Object.assign(program, {
|
|
vao: this.createVertexArray()
|
|
});
|
|
if (this.debug) _webglUtil.validateProgram(gl, program2);
|
|
return program2;
|
|
}
|
|
buildVao(program) {
|
|
this.setProgram(program);
|
|
this.bindVertexArray(program.vao);
|
|
const gl = this.gl;
|
|
// Bind index buffer, and vertex buffers based on program attrib
|
|
// locations.
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer));
|
|
_gpgpuUtil.bindVertexProgramAttributeStreams(gl, program, this.vertexBuffer);
|
|
}
|
|
deleteProgram(program) {
|
|
this.throwIfDisposed();
|
|
if (program === this.program) this.program = null;
|
|
if (program != null) {
|
|
_webglUtil.callAndCheck(this.gl, ()=>this.gl.deleteProgram(program));
|
|
this.deleteVertexArray(program.vao);
|
|
}
|
|
}
|
|
setProgram(program) {
|
|
this.throwIfDisposed();
|
|
this.program = program;
|
|
if (this.program != null) {
|
|
if (this.debug) _webglUtil.validateProgram(this.gl, this.program);
|
|
}
|
|
_webglUtil.callAndCheck(this.gl, ()=>this.gl.useProgram(program));
|
|
}
|
|
getUniformLocation(program, uniformName, shouldThrow = true) {
|
|
this.throwIfDisposed();
|
|
if (shouldThrow) return _webglUtil.getProgramUniformLocationOrThrow(this.gl, program, uniformName);
|
|
else return _webglUtil.getProgramUniformLocation(this.gl, program, uniformName);
|
|
}
|
|
getAttributeLocation(program, attribute) {
|
|
this.throwIfDisposed();
|
|
return _webglUtil.callAndCheck(this.gl, ()=>this.gl.getAttribLocation(program, attribute));
|
|
}
|
|
getUniformLocationNoThrow(program, uniformName) {
|
|
this.throwIfDisposed();
|
|
return this.gl.getUniformLocation(program, uniformName);
|
|
}
|
|
setInputMatrixTexture(inputMatrixTexture, uniformLocation, textureUnit) {
|
|
this.throwIfDisposed();
|
|
this.throwIfNoProgram();
|
|
_webglUtil.bindTextureToProgramUniformSampler(this.gl, inputMatrixTexture, uniformLocation, textureUnit);
|
|
}
|
|
setOutputMatrixTexture(outputMatrixTexture, rows, columns) {
|
|
this.setOutputMatrixTextureDriver(outputMatrixTexture, columns, rows);
|
|
}
|
|
setOutputPackedMatrixTexture(outputPackedMatrixTexture, rows, columns) {
|
|
this.throwIfDisposed();
|
|
const [width, height] = _texUtil.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) _webglUtil.validateProgram(this.gl, this.program);
|
|
_webglUtil.validateFramebuffer(this.gl);
|
|
}
|
|
executeProgram() {
|
|
this.throwIfDisposed();
|
|
this.throwIfNoProgram();
|
|
const gl = this.gl;
|
|
if (this.debug) {
|
|
const boundVao = this.getVertexArray();
|
|
console.assert(boundVao === this.program.vao, "VAO changed between setProgram and executeProgram!");
|
|
this.debugValidate();
|
|
}
|
|
_webglUtil.callAndCheck(gl, ()=>gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0));
|
|
}
|
|
blockUntilAllProgramsCompleted() {
|
|
this.throwIfDisposed();
|
|
_webglUtil.callAndCheck(this.gl, ()=>this.gl.finish());
|
|
}
|
|
getQueryTimerExtension() {
|
|
if (this.disjointQueryTimerExtension == null) this.disjointQueryTimerExtension = _webglUtil.getExtensionOrThrow(this.gl, (0, _tfjsCore.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 ((0, _tfjsCore.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 ((0, _tfjsCore.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 (0, _tfjsCore.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, (0, _tfjsCore.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")));
|
|
return this.getQueryTime(query, (0, _tfjsCore.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.
|
|
let scheduleFn = undefined;
|
|
if ("setTimeoutCustom" in (0, _tfjsCore.env)().platform) scheduleFn = (0, _tfjsCore.env)().platform.setTimeoutCustom.bind((0, _tfjsCore.env)().platform);
|
|
(0, _tfjsCore.util).repeatedTry(()=>{
|
|
this.pollItems();
|
|
// End the loop if no more items to poll.
|
|
return this.itemsToPoll.length === 0;
|
|
}, ()=>0, null, scheduleFn);
|
|
}
|
|
bindTextureToFrameBuffer(texture) {
|
|
this.throwIfDisposed();
|
|
_webglUtil.bindColorTextureToFramebuffer(this.gl, texture, this.framebuffer);
|
|
if (this.debug) _webglUtil.validateFramebuffer(this.gl);
|
|
}
|
|
unbindTextureToFrameBuffer() {
|
|
if (this.outputTexture != null) {
|
|
_webglUtil.bindColorTextureToFramebuffer(this.gl, this.outputTexture, this.framebuffer);
|
|
if (this.debug) _webglUtil.validateFramebuffer(this.gl);
|
|
} else _webglUtil.unbindColorTextureFromFramebuffer(this.gl, 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;
|
|
_webglUtil.bindColorTextureToFramebuffer(gl, outputMatrixTextureMaybePacked, this.framebuffer);
|
|
if (this.debug) _webglUtil.validateFramebuffer(gl);
|
|
this.outputTexture = outputMatrixTextureMaybePacked;
|
|
_webglUtil.callAndCheck(gl, ()=>gl.viewport(0, 0, width, height));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.scissor(0, 0, width, height));
|
|
}
|
|
setOutputMatrixWriteRegionDriver(x, y, width, height) {
|
|
this.throwIfDisposed();
|
|
_webglUtil.callAndCheck(this.gl, ()=>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.");
|
|
}
|
|
}
|
|
function linearSearchLastTrue(arr) {
|
|
let i = 0;
|
|
for(; i < arr.length; ++i){
|
|
const isDone = arr[i]();
|
|
if (!isDone) break;
|
|
}
|
|
return i - 1;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./canvas_util":"1tNGf","./gpgpu_util":"ezSrp","./tex_util":"1oYRe","./webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ezSrp":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "createVertexShader", ()=>createVertexShader);
|
|
parcelHelpers.export(exports, "createVertexBuffer", ()=>createVertexBuffer);
|
|
parcelHelpers.export(exports, "createIndexBuffer", ()=>createIndexBuffer);
|
|
parcelHelpers.export(exports, "getInternalFormatForFloat32MatrixTexture", ()=>getInternalFormatForFloat32MatrixTexture);
|
|
parcelHelpers.export(exports, "createFloat32MatrixTexture", ()=>createFloat32MatrixTexture);
|
|
parcelHelpers.export(exports, "getInternalFormatForFloat16MatrixTexture", ()=>getInternalFormatForFloat16MatrixTexture);
|
|
parcelHelpers.export(exports, "createFloat16MatrixTexture", ()=>createFloat16MatrixTexture);
|
|
parcelHelpers.export(exports, "getInternalFormatForUnsignedBytesMatrixTexture", ()=>getInternalFormatForUnsignedBytesMatrixTexture);
|
|
parcelHelpers.export(exports, "createUnsignedBytesMatrixTexture", ()=>createUnsignedBytesMatrixTexture);
|
|
parcelHelpers.export(exports, "getInternalFormatForPackedMatrixTexture", ()=>getInternalFormatForPackedMatrixTexture);
|
|
parcelHelpers.export(exports, "createPackedMatrixTexture", ()=>createPackedMatrixTexture);
|
|
parcelHelpers.export(exports, "getInternalFormatForFloat16PackedMatrixTexture", ()=>getInternalFormatForFloat16PackedMatrixTexture);
|
|
parcelHelpers.export(exports, "createFloat16PackedMatrixTexture", ()=>createFloat16PackedMatrixTexture);
|
|
parcelHelpers.export(exports, "bindVertexProgramAttributeStreams", ()=>bindVertexProgramAttributeStreams);
|
|
parcelHelpers.export(exports, "uploadDenseMatrixToTexture", ()=>uploadDenseMatrixToTexture);
|
|
parcelHelpers.export(exports, "uploadPixelDataToTexture", ()=>uploadPixelDataToTexture);
|
|
parcelHelpers.export(exports, "createBufferFromOutputTexture", ()=>createBufferFromOutputTexture);
|
|
parcelHelpers.export(exports, "downloadFloat32MatrixFromBuffer", ()=>downloadFloat32MatrixFromBuffer);
|
|
parcelHelpers.export(exports, "downloadByteEncodedFloatMatrixFromOutputTexture", ()=>downloadByteEncodedFloatMatrixFromOutputTexture);
|
|
parcelHelpers.export(exports, "downloadPackedMatrixFromBuffer", ()=>downloadPackedMatrixFromBuffer);
|
|
parcelHelpers.export(exports, "downloadMatrixFromPackedOutputTexture", ()=>downloadMatrixFromPackedOutputTexture);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _glslVersion = require("./glsl_version");
|
|
var _texUtil = require("./tex_util");
|
|
var _webglUtil = require("./webgl_util");
|
|
function createVertexShader(gl) {
|
|
const glsl = (0, _glslVersion.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 _webglUtil.createVertexShader(gl, vertexShaderSource);
|
|
}
|
|
function createVertexBuffer(gl) {
|
|
// [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 _webglUtil.createStaticVertexBuffer(gl, vertexArray);
|
|
}
|
|
function createIndexBuffer(gl) {
|
|
// OpenGL (and WebGL) have "CCW == front" winding
|
|
const triangleVertexIndices = new Uint16Array([
|
|
0,
|
|
1,
|
|
2,
|
|
2,
|
|
1,
|
|
3
|
|
]);
|
|
return _webglUtil.createStaticIndexBuffer(gl, triangleVertexIndices);
|
|
}
|
|
function createAndConfigureTexture(gl, width, height, internalFormat, textureFormat, textureType) {
|
|
_webglUtil.validateTextureSize(width, height);
|
|
const texture = _webglUtil.createTexture(gl);
|
|
const tex2d = gl.TEXTURE_2D;
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindTexture(tex2d, texture));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST));
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 1) _webglUtil.callAndCheck(gl, ()=>gl.texImage2D(tex2d, 0, internalFormat, width, height, 0, textureFormat, textureType, null));
|
|
else _webglUtil.callAndCheck(gl, ()=>gl.texStorage2D(tex2d, 1, internalFormat, width, height));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindTexture(gl.TEXTURE_2D, null));
|
|
return {
|
|
texture,
|
|
texShape: [
|
|
height,
|
|
width
|
|
]
|
|
};
|
|
}
|
|
function getInternalFormatForFloat32MatrixTexture(textureConfig) {
|
|
return textureConfig.internalFormatFloat;
|
|
}
|
|
function createFloat32MatrixTexture(gl, rows, columns, textureConfig) {
|
|
const [width, height] = _texUtil.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);
|
|
return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat32MatrixTexture(textureConfig), textureConfig.textureFormatFloat, gl.FLOAT);
|
|
}
|
|
function getInternalFormatForFloat16MatrixTexture(textureConfig) {
|
|
return textureConfig.internalFormatHalfFloat;
|
|
}
|
|
function createFloat16MatrixTexture(gl, rows, columns, textureConfig) {
|
|
const [width, height] = _texUtil.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);
|
|
return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat16MatrixTexture(textureConfig), textureConfig.textureFormatFloat, textureConfig.textureTypeHalfFloat);
|
|
}
|
|
function getInternalFormatForUnsignedBytesMatrixTexture(textureConfig) {
|
|
return textureConfig.downloadTextureFormat;
|
|
}
|
|
function createUnsignedBytesMatrixTexture(gl, rows, columns, textureConfig) {
|
|
const [width, height] = _texUtil.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);
|
|
return createAndConfigureTexture(gl, width, height, getInternalFormatForUnsignedBytesMatrixTexture(textureConfig), gl.RGBA, gl.UNSIGNED_BYTE);
|
|
}
|
|
function getInternalFormatForPackedMatrixTexture(textureConfig) {
|
|
return textureConfig.internalFormatPackedFloat;
|
|
}
|
|
function createPackedMatrixTexture(gl, rows, columns, textureConfig) {
|
|
const [width, height] = _texUtil.getPackedMatrixTextureShapeWidthHeight(rows, columns);
|
|
return createAndConfigureTexture(gl, width, height, getInternalFormatForPackedMatrixTexture(textureConfig), gl.RGBA, gl.FLOAT);
|
|
}
|
|
function getInternalFormatForFloat16PackedMatrixTexture(textureConfig) {
|
|
return textureConfig.internalFormatPackedHalfFloat;
|
|
}
|
|
function createFloat16PackedMatrixTexture(gl, rows, columns, textureConfig) {
|
|
const [width, height] = _texUtil.getPackedMatrixTextureShapeWidthHeight(rows, columns);
|
|
return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat16PackedMatrixTexture(textureConfig), gl.RGBA, textureConfig.textureTypeHalfFloat);
|
|
}
|
|
function bindVertexProgramAttributeStreams(gl, program, vertexBuffer) {
|
|
const posOffset = 0; // x is the first buffer element
|
|
const uvOffset = 12; // uv comes after [x y z]
|
|
const stride = 20; // xyz + uv, each entry is 4-byte float.
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer));
|
|
const success = _webglUtil.bindVertexBufferToProgramAttribute(gl, program, "clipSpacePos", vertexBuffer, 3, stride, posOffset);
|
|
return success && _webglUtil.bindVertexBufferToProgramAttribute(gl, program, "uv", vertexBuffer, 2, stride, uvOffset);
|
|
}
|
|
function uploadDenseMatrixToTexture(gl, texture, width, height, data, textureConfig) {
|
|
_webglUtil.callAndCheck(gl, ()=>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);
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 2) _webglUtil.callAndCheck(gl, ()=>gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, gl.RGBA, texelDataType, dataForUpload));
|
|
else _webglUtil.callAndCheck(gl, ()=>gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA, texelDataType, dataForUpload));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindTexture(gl.TEXTURE_2D, null));
|
|
}
|
|
function uploadPixelDataToTexture(gl, texture, pixels) {
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindTexture(gl.TEXTURE_2D, texture));
|
|
if (pixels.data instanceof Uint8Array) {
|
|
if ((0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 2) _webglUtil.callAndCheck(gl, ()=>gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, pixels.width, pixels.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels.data));
|
|
else _webglUtil.callAndCheck(gl, ()=>gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixels.width, pixels.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixels.data));
|
|
} else if ((0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 2) _webglUtil.callAndCheck(gl, ()=>gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixels));
|
|
else _webglUtil.callAndCheck(gl, ()=>gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, pixels));
|
|
_webglUtil.callAndCheck(gl, ()=>gl.bindTexture(gl.TEXTURE_2D, null));
|
|
}
|
|
function createBufferFromOutputTexture(gl2, rows, columns, textureConfig) {
|
|
// Create and bind the buffer.
|
|
const buffer = gl2.createBuffer();
|
|
_webglUtil.callAndCheck(gl2, ()=>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;
|
|
_webglUtil.callAndCheck(gl2, ()=>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.
|
|
_webglUtil.callAndCheck(gl2, ()=>gl2.readPixels(0, 0, columns, rows, gl2.RGBA, gl2.FLOAT, 0));
|
|
_webglUtil.callAndCheck(gl2, ()=>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, rows, columns, textureConfig) {
|
|
const [w, h] = _texUtil.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);
|
|
const numChannels = 4;
|
|
const downloadTarget = new Uint8Array(_texUtil.getUnpackedArraySizeFromMatrixSize(rows * columns, numChannels));
|
|
_webglUtil.callAndCheck(gl, ()=>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(_texUtil.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, physicalRows, physicalCols) {
|
|
const packedRGBA = new Float32Array(physicalRows * physicalCols * 4);
|
|
_webglUtil.callAndCheck(gl, ()=>gl.readPixels(0, 0, physicalCols, physicalRows, gl.RGBA, gl.FLOAT, packedRGBA));
|
|
return packedRGBA;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./glsl_version":"kG2vE","./tex_util":"1oYRe","./webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"e4M7v":[function(require,module,exports) {
|
|
/**
|
|
* @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
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "addImplCPU", ()=>addImplCPU);
|
|
parcelHelpers.export(exports, "bincountImplCPU", ()=>bincountImplCPU);
|
|
parcelHelpers.export(exports, "bincountReduceImplCPU", ()=>bincountReduceImplCPU);
|
|
parcelHelpers.export(exports, "bitwiseAndImplCPU", ()=>bitwiseAndImplCPU);
|
|
parcelHelpers.export(exports, "castImplCPU", ()=>castImplCPU);
|
|
parcelHelpers.export(exports, "ceilImplCPU", ()=>ceilImplCPU);
|
|
parcelHelpers.export(exports, "concatImplCPU", ()=>concatImplCPU);
|
|
parcelHelpers.export(exports, "equalImplCPU", ()=>equalImplCPU);
|
|
parcelHelpers.export(exports, "expImplCPU", ()=>expImplCPU);
|
|
parcelHelpers.export(exports, "expm1ImplCPU", ()=>expm1ImplCPU);
|
|
parcelHelpers.export(exports, "floorImplCPU", ()=>floorImplCPU);
|
|
parcelHelpers.export(exports, "gatherNdImplCPU", ()=>gatherNdImplCPU);
|
|
parcelHelpers.export(exports, "gatherV2ImplCPU", ()=>gatherV2ImplCPU);
|
|
parcelHelpers.export(exports, "greaterEqualImplCPU", ()=>greaterEqualImplCPU);
|
|
parcelHelpers.export(exports, "greaterImplCPU", ()=>greaterImplCPU);
|
|
parcelHelpers.export(exports, "lessEqualImplCPU", ()=>lessEqualImplCPU);
|
|
parcelHelpers.export(exports, "lessImplCPU", ()=>lessImplCPU);
|
|
parcelHelpers.export(exports, "linSpaceImplCPU", ()=>linSpaceImplCPU);
|
|
parcelHelpers.export(exports, "logImplCPU", ()=>logImplCPU);
|
|
parcelHelpers.export(exports, "maxImplCPU", ()=>maxImplCPU);
|
|
parcelHelpers.export(exports, "maximumImplCPU", ()=>maximumImplCPU);
|
|
parcelHelpers.export(exports, "minimumImplCPU", ()=>minimumImplCPU);
|
|
parcelHelpers.export(exports, "multiplyImplCPU", ()=>multiplyImplCPU);
|
|
parcelHelpers.export(exports, "negImplCPU", ()=>negImplCPU);
|
|
parcelHelpers.export(exports, "notEqualImplCPU", ()=>notEqualImplCPU);
|
|
parcelHelpers.export(exports, "prodImplCPU", ()=>prodImplCPU);
|
|
parcelHelpers.export(exports, "raggedGatherImplCPU", ()=>raggedGatherImplCPU);
|
|
parcelHelpers.export(exports, "raggedRangeImplCPU", ()=>raggedRangeImplCPU);
|
|
parcelHelpers.export(exports, "raggedTensorToTensorImplCPU", ()=>raggedTensorToTensorImplCPU);
|
|
parcelHelpers.export(exports, "scatterImplCPU", ()=>scatterImplCPU);
|
|
parcelHelpers.export(exports, "sigmoidImplCPU", ()=>sigmoidImplCPU);
|
|
parcelHelpers.export(exports, "simpleAbsImplCPU", ()=>simpleAbsImplCPU);
|
|
parcelHelpers.export(exports, "sliceImplCPU", ()=>sliceImplCPU);
|
|
parcelHelpers.export(exports, "sparseFillEmptyRowsImplCPU", ()=>sparseFillEmptyRowsImplCPU);
|
|
parcelHelpers.export(exports, "sparseReshapeImplCPU", ()=>sparseReshapeImplCPU);
|
|
parcelHelpers.export(exports, "sparseSegmentReductionImplCPU", ()=>sparseSegmentReductionImplCPU);
|
|
parcelHelpers.export(exports, "sqrtImplCPU", ()=>sqrtImplCPU);
|
|
parcelHelpers.export(exports, "staticRegexReplaceImplCPU", ()=>staticRegexReplaceImplCPU);
|
|
parcelHelpers.export(exports, "stridedSliceImplCPU", ()=>stridedSliceImplCPU);
|
|
parcelHelpers.export(exports, "stringNGramsImplCPU", ()=>stringNGramsImplCPU);
|
|
parcelHelpers.export(exports, "stringSplitImplCPU", ()=>stringSplitImplCPU);
|
|
parcelHelpers.export(exports, "stringToHashBucketFastImplCPU", ()=>stringToHashBucketFastImplCPU);
|
|
parcelHelpers.export(exports, "subImplCPU", ()=>subImplCPU);
|
|
parcelHelpers.export(exports, "rangeImplCPU", ()=>rangeImplCPU);
|
|
parcelHelpers.export(exports, "rsqrtImplCPU", ()=>rsqrtImplCPU);
|
|
parcelHelpers.export(exports, "tileImplCPU", ()=>tileImplCPU);
|
|
parcelHelpers.export(exports, "topKImplCPU", ()=>topKImplCPU);
|
|
parcelHelpers.export(exports, "transposeImplCPU", ()=>transposeImplCPU);
|
|
parcelHelpers.export(exports, "uniqueImplCPU", ()=>uniqueImplCPU);
|
|
var _shared = require("@tensorflow/tfjs-backend-cpu/dist/shared");
|
|
const { addImpl: addImplCPU, bincountImpl: bincountImplCPU, bincountReduceImpl: bincountReduceImplCPU, bitwiseAndImpl: bitwiseAndImplCPU, castImpl: castImplCPU, ceilImpl: ceilImplCPU, concatImpl: concatImplCPU, equalImpl: equalImplCPU, expImpl: expImplCPU, expm1Impl: expm1ImplCPU, floorImpl: floorImplCPU, gatherNdImpl: gatherNdImplCPU, gatherV2Impl: gatherV2ImplCPU, greaterImpl: greaterImplCPU, greaterEqualImpl: greaterEqualImplCPU, lessImpl: lessImplCPU, lessEqualImpl: lessEqualImplCPU, linSpaceImpl: linSpaceImplCPU, logImpl: logImplCPU, maxImpl: maxImplCPU, maximumImpl: maximumImplCPU, minimumImpl: minimumImplCPU, multiplyImpl: multiplyImplCPU, negImpl: negImplCPU, notEqualImpl: notEqualImplCPU, prodImpl: prodImplCPU, raggedGatherImpl: raggedGatherImplCPU, raggedRangeImpl: raggedRangeImplCPU, raggedTensorToTensorImpl: raggedTensorToTensorImplCPU, rangeImpl: rangeImplCPU, rsqrtImpl: rsqrtImplCPU, scatterImpl: scatterImplCPU, sigmoidImpl: sigmoidImplCPU, simpleAbsImpl: simpleAbsImplCPU, sliceImpl: sliceImplCPU, sparseFillEmptyRowsImpl: sparseFillEmptyRowsImplCPU, sparseReshapeImpl: sparseReshapeImplCPU, sparseSegmentReductionImpl: sparseSegmentReductionImplCPU, sqrtImpl: sqrtImplCPU, staticRegexReplaceImpl: staticRegexReplaceImplCPU, stridedSliceImpl: stridedSliceImplCPU, stringNGramsImpl: stringNGramsImplCPU, stringSplitImpl: stringSplitImplCPU, stringToHashBucketFastImpl: stringToHashBucketFastImplCPU, subImpl: subImplCPU, tileImpl: tileImplCPU, topKImpl: topKImplCPU, transposeImpl: transposeImplCPU, uniqueImpl: uniqueImplCPU } = _shared;
|
|
|
|
},{"@tensorflow/tfjs-backend-cpu/dist/shared":"YbUp7","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"YbUp7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // Shared functionality among backends.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "simpleAbsImpl", ()=>(0, _abs.simpleAbsImpl));
|
|
parcelHelpers.export(exports, "addImpl", ()=>(0, _add.addImpl));
|
|
parcelHelpers.export(exports, "bincountImpl", ()=>(0, _bincountImpl.bincountImpl));
|
|
parcelHelpers.export(exports, "bincountReduceImpl", ()=>(0, _bincountImpl.bincountReduceImpl));
|
|
parcelHelpers.export(exports, "bitwiseAndImpl", ()=>(0, _bitwiseAnd.bitwiseAndImpl));
|
|
parcelHelpers.export(exports, "castImpl", ()=>(0, _cast.castImpl));
|
|
parcelHelpers.export(exports, "ceilImpl", ()=>(0, _ceil.ceilImpl));
|
|
parcelHelpers.export(exports, "concatImpl", ()=>(0, _concatImpl.concatImpl));
|
|
parcelHelpers.export(exports, "equalImpl", ()=>(0, _equal.equalImpl));
|
|
parcelHelpers.export(exports, "expImpl", ()=>(0, _exp.expImpl));
|
|
parcelHelpers.export(exports, "expm1Impl", ()=>(0, _expm1.expm1Impl));
|
|
parcelHelpers.export(exports, "floorImpl", ()=>(0, _floor.floorImpl));
|
|
parcelHelpers.export(exports, "floorDivImpl", ()=>(0, _floorDiv.floorDivImpl));
|
|
parcelHelpers.export(exports, "gatherNdImpl", ()=>(0, _gatherNdImpl.gatherNdImpl));
|
|
parcelHelpers.export(exports, "gatherV2Impl", ()=>(0, _gatherV2Impl.gatherV2Impl));
|
|
parcelHelpers.export(exports, "greaterImpl", ()=>(0, _greater.greaterImpl));
|
|
parcelHelpers.export(exports, "greaterEqualImpl", ()=>(0, _greaterEqual.greaterEqualImpl));
|
|
parcelHelpers.export(exports, "lessImpl", ()=>(0, _less.lessImpl));
|
|
parcelHelpers.export(exports, "lessEqualImpl", ()=>(0, _lessEqual.lessEqualImpl));
|
|
parcelHelpers.export(exports, "linSpaceImpl", ()=>(0, _linSpaceImpl.linSpaceImpl));
|
|
parcelHelpers.export(exports, "logImpl", ()=>(0, _log.logImpl));
|
|
parcelHelpers.export(exports, "maxImpl", ()=>(0, _maxImpl.maxImpl));
|
|
parcelHelpers.export(exports, "maximumImpl", ()=>(0, _maximum.maximumImpl));
|
|
parcelHelpers.export(exports, "minimumImpl", ()=>(0, _minimum.minimumImpl));
|
|
parcelHelpers.export(exports, "multiplyImpl", ()=>(0, _multiply.multiplyImpl));
|
|
parcelHelpers.export(exports, "negImpl", ()=>(0, _neg.negImpl));
|
|
parcelHelpers.export(exports, "notEqualImpl", ()=>(0, _notEqual.notEqualImpl));
|
|
parcelHelpers.export(exports, "prodImpl", ()=>(0, _prod.prodImpl));
|
|
parcelHelpers.export(exports, "raggedGatherImpl", ()=>(0, _raggedGatherImpl.raggedGatherImpl));
|
|
parcelHelpers.export(exports, "raggedRangeImpl", ()=>(0, _raggedRangeImpl.raggedRangeImpl));
|
|
parcelHelpers.export(exports, "raggedTensorToTensorImpl", ()=>(0, _raggedTensorToTensorImpl.raggedTensorToTensorImpl));
|
|
parcelHelpers.export(exports, "rangeImpl", ()=>(0, _rangeImpl.rangeImpl));
|
|
parcelHelpers.export(exports, "rsqrtImpl", ()=>(0, _rsqrt.rsqrtImpl));
|
|
parcelHelpers.export(exports, "scatterImpl", ()=>(0, _scatterImpl.scatterImpl));
|
|
parcelHelpers.export(exports, "sigmoidImpl", ()=>(0, _sigmoid.sigmoidImpl));
|
|
parcelHelpers.export(exports, "sliceImpl", ()=>(0, _slice.sliceImpl));
|
|
parcelHelpers.export(exports, "sparseFillEmptyRowsImpl", ()=>(0, _sparseFillEmptyRowsImpl.sparseFillEmptyRowsImpl));
|
|
parcelHelpers.export(exports, "sparseReshapeImpl", ()=>(0, _sparseReshapeImpl.sparseReshapeImpl));
|
|
parcelHelpers.export(exports, "sparseSegmentReductionImpl", ()=>(0, _sparseSegmentReductionImpl.sparseSegmentReductionImpl));
|
|
parcelHelpers.export(exports, "sqrtImpl", ()=>(0, _sqrt.sqrtImpl));
|
|
parcelHelpers.export(exports, "squaredDifferenceImpl", ()=>(0, _squaredDifference.squaredDifferenceImpl));
|
|
parcelHelpers.export(exports, "staticRegexReplaceImpl", ()=>(0, _staticRegexReplace.staticRegexReplaceImpl));
|
|
parcelHelpers.export(exports, "stridedSliceImpl", ()=>(0, _stridedSliceImpl.stridedSliceImpl));
|
|
parcelHelpers.export(exports, "stringNGramsImpl", ()=>(0, _stringNGramsImpl.stringNGramsImpl));
|
|
parcelHelpers.export(exports, "stringSplitImpl", ()=>(0, _stringSplitImpl.stringSplitImpl));
|
|
parcelHelpers.export(exports, "stringToHashBucketFastImpl", ()=>(0, _stringToHashBucketFastImpl.stringToHashBucketFastImpl));
|
|
parcelHelpers.export(exports, "subImpl", ()=>(0, _sub.subImpl));
|
|
parcelHelpers.export(exports, "tileImpl", ()=>(0, _tileImpl.tileImpl));
|
|
parcelHelpers.export(exports, "topKImpl", ()=>(0, _topKImpl.topKImpl));
|
|
parcelHelpers.export(exports, "transposeImpl", ()=>(0, _transposeImpl.transposeImpl));
|
|
parcelHelpers.export(exports, "uniqueImpl", ()=>(0, _uniqueImpl.uniqueImpl));
|
|
var _abs = require("./kernels/Abs");
|
|
var _add = require("./kernels/Add");
|
|
var _bincountImpl = require("./kernels/Bincount_impl");
|
|
var _bitwiseAnd = require("./kernels/BitwiseAnd");
|
|
var _cast = require("./kernels/Cast");
|
|
var _ceil = require("./kernels/Ceil");
|
|
var _concatImpl = require("./kernels/Concat_impl");
|
|
var _equal = require("./kernels/Equal");
|
|
var _exp = require("./kernels/Exp");
|
|
var _expm1 = require("./kernels/Expm1");
|
|
var _floor = require("./kernels/Floor");
|
|
var _floorDiv = require("./kernels/FloorDiv");
|
|
var _gatherNdImpl = require("./kernels/GatherNd_Impl");
|
|
var _gatherV2Impl = require("./kernels/GatherV2_impl");
|
|
var _greater = require("./kernels/Greater");
|
|
var _greaterEqual = require("./kernels/GreaterEqual");
|
|
var _less = require("./kernels/Less");
|
|
var _lessEqual = require("./kernels/LessEqual");
|
|
var _linSpaceImpl = require("./kernels/LinSpace_impl");
|
|
var _log = require("./kernels/Log");
|
|
var _maxImpl = require("./kernels/Max_impl");
|
|
var _maximum = require("./kernels/Maximum");
|
|
var _minimum = require("./kernels/Minimum");
|
|
var _multiply = require("./kernels/Multiply");
|
|
var _neg = require("./kernels/Neg");
|
|
var _notEqual = require("./kernels/NotEqual");
|
|
var _prod = require("./kernels/Prod");
|
|
var _raggedGatherImpl = require("./kernels/RaggedGather_impl");
|
|
var _raggedRangeImpl = require("./kernels/RaggedRange_impl");
|
|
var _raggedTensorToTensorImpl = require("./kernels/RaggedTensorToTensor_impl");
|
|
var _rangeImpl = require("./kernels/Range_impl");
|
|
var _rsqrt = require("./kernels/Rsqrt");
|
|
var _scatterImpl = require("./kernels/Scatter_impl");
|
|
var _sigmoid = require("./kernels/Sigmoid");
|
|
var _slice = require("./kernels/Slice");
|
|
var _sparseFillEmptyRowsImpl = require("./kernels/SparseFillEmptyRows_impl");
|
|
var _sparseReshapeImpl = require("./kernels/SparseReshape_impl");
|
|
var _sparseSegmentReductionImpl = require("./kernels/SparseSegmentReduction_impl");
|
|
var _sqrt = require("./kernels/Sqrt");
|
|
var _squaredDifference = require("./kernels/SquaredDifference");
|
|
var _staticRegexReplace = require("./kernels/StaticRegexReplace");
|
|
var _stridedSliceImpl = require("./kernels/StridedSlice_impl");
|
|
var _stringNGramsImpl = require("./kernels/StringNGrams_impl");
|
|
var _stringSplitImpl = require("./kernels/StringSplit_impl");
|
|
var _stringToHashBucketFastImpl = require("./kernels/StringToHashBucketFast_impl");
|
|
var _sub = require("./kernels/Sub");
|
|
var _tileImpl = require("./kernels/Tile_impl");
|
|
var _topKImpl = require("./kernels/TopK_impl");
|
|
var _transposeImpl = require("./kernels/Transpose_impl");
|
|
var _uniqueImpl = require("./kernels/Unique_impl");
|
|
|
|
},{"./kernels/Abs":"2vVaE","./kernels/Add":"dippY","./kernels/Bincount_impl":"4EF2S","./kernels/BitwiseAnd":"lFHUr","./kernels/Cast":"fAtIw","./kernels/Ceil":"dPS5d","./kernels/Concat_impl":"50NO7","./kernels/Equal":"jK2O7","./kernels/Exp":"6eexr","./kernels/Expm1":"pXtet","./kernels/Floor":"ftFzk","./kernels/FloorDiv":"kMZnS","./kernels/GatherNd_Impl":"klZow","./kernels/GatherV2_impl":"5y26k","./kernels/Greater":"94zPb","./kernels/GreaterEqual":"a9aqR","./kernels/Less":"anwWy","./kernels/LessEqual":"nFlBF","./kernels/LinSpace_impl":"4tRcP","./kernels/Log":"dNlq0","./kernels/Max_impl":"6BNe1","./kernels/Maximum":"73P1X","./kernels/Minimum":"2gO4x","./kernels/Multiply":"FrRi2","./kernels/Neg":"4sfM4","./kernels/NotEqual":"i62sj","./kernels/Prod":"8NwGT","./kernels/RaggedGather_impl":"59HGn","./kernels/RaggedRange_impl":"l2R3s","./kernels/RaggedTensorToTensor_impl":"jDwSG","./kernels/Range_impl":"gJNJp","./kernels/Rsqrt":"gcVCI","./kernels/Scatter_impl":"kMt6f","./kernels/Sigmoid":"1a9v3","./kernels/Slice":"9L9GN","./kernels/SparseFillEmptyRows_impl":"72f9e","./kernels/SparseReshape_impl":"ecdf6","./kernels/SparseSegmentReduction_impl":"ie2pQ","./kernels/Sqrt":"cnnoj","./kernels/SquaredDifference":"77Ql7","./kernels/StaticRegexReplace":"9G2f2","./kernels/StridedSlice_impl":"kCJo9","./kernels/StringNGrams_impl":"3rAXp","./kernels/StringSplit_impl":"8xmpZ","./kernels/StringToHashBucketFast_impl":"6jwLv","./kernels/Sub":"4DByI","./kernels/Tile_impl":"7g2re","./kernels/TopK_impl":"dl1sf","./kernels/Transpose_impl":"2fFZe","./kernels/Unique_impl":"gLexL","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2vVaE":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "simpleAbsImpl", ()=>simpleAbsImpl);
|
|
parcelHelpers.export(exports, "abs", ()=>abs);
|
|
parcelHelpers.export(exports, "absConfig", ()=>absConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function simpleAbsImpl(vals) {
|
|
const resultValues = new Float32Array(vals.length);
|
|
for(let i = 0; i < vals.length; ++i)resultValues[i] = Math.abs(vals[i]);
|
|
return resultValues;
|
|
}
|
|
const abs = (args)=>{
|
|
const { x } = args.inputs;
|
|
const cpuBackend = args.backend;
|
|
(0, _cpuUtil.assertNotComplex)(x, "abs");
|
|
let resultValues = new Float32Array((0, _tfjsCore.util).sizeFromShape(x.shape));
|
|
const values = cpuBackend.data.get(x.dataId).values;
|
|
resultValues = simpleAbsImpl(values);
|
|
return cpuBackend.makeOutput(resultValues, x.shape, x.dtype);
|
|
};
|
|
const absConfig = {
|
|
kernelName: (0, _tfjsCore.Abs),
|
|
backendName: "cpu",
|
|
kernelFunc: abs
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1l037":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "assertNotComplex", ()=>assertNotComplex);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function assertNotComplex(tensor, opName) {
|
|
if (!Array.isArray(tensor)) tensor = [
|
|
tensor
|
|
];
|
|
tensor.forEach((t)=>{
|
|
if (t != null) (0, _tfjsCore.util).assert(t.dtype !== "complex64", ()=>`${opName} does not support complex64 tensors in the CPU backend.`);
|
|
});
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dippY":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "addImpl", ()=>addImpl);
|
|
parcelHelpers.export(exports, "addComplexImpl", ()=>addComplexImpl);
|
|
parcelHelpers.export(exports, "add", ()=>add);
|
|
parcelHelpers.export(exports, "addConfig", ()=>addConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const addImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a + b);
|
|
const addComplexImpl = (0, _binaryUtils.createComplexBinaryKernelImpl)((aReal, aImag, bReal, bImag)=>{
|
|
return {
|
|
real: aReal + bReal,
|
|
imag: aImag + bImag
|
|
};
|
|
});
|
|
const add = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Add), addImpl, addComplexImpl);
|
|
const addConfig = {
|
|
kernelName: (0, _tfjsCore.Add),
|
|
backendName: "cpu",
|
|
kernelFunc: add
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7WPlP":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Template that creates implementation for binary ops. Supports broadcast.
|
|
*/ parcelHelpers.export(exports, "createSimpleBinaryKernelImpl", ()=>createSimpleBinaryKernelImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function createSimpleBinaryKernelImpl(op) {
|
|
return (aShape, bShape, aVals, bVals, dtype)=>{
|
|
const newShape = (0, _tfjsCore.backend_util).assertAndGetBroadcastShape(aShape, bShape);
|
|
const resultRank = newShape.length;
|
|
const resultStrides = (0, _tfjsCore.util).computeStrides(newShape);
|
|
const resultSize = (0, _tfjsCore.util).sizeFromShape(newShape);
|
|
const result = (0, _tfjsCore.util).getTypedArrayFromDType(dtype, resultSize);
|
|
const aRank = aShape.length;
|
|
const bRank = bShape.length;
|
|
const aStrides = (0, _tfjsCore.util).computeStrides(aShape);
|
|
const bStrides = (0, _tfjsCore.util).computeStrides(bShape);
|
|
const aBroadcastDims = (0, _tfjsCore.backend_util).getBroadcastDims(aShape, newShape);
|
|
const bBroadcastDims = (0, _tfjsCore.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 = (0, _tfjsCore.util).indexToLoc(i, resultRank, resultStrides);
|
|
const aLoc = loc.slice(-aRank);
|
|
aBroadcastDims.forEach((d)=>aLoc[d] = 0);
|
|
const aIndex = (0, _tfjsCore.util).locToIndex(aLoc, aRank, aStrides);
|
|
const bLoc = loc.slice(-bRank);
|
|
bBroadcastDims.forEach((d)=>bLoc[d] = 0);
|
|
const bIndex = (0, _tfjsCore.util).locToIndex(bLoc, bRank, bStrides);
|
|
result[i] = op(aVals[aIndex], bVals[bIndex]);
|
|
}
|
|
return [
|
|
result,
|
|
newShape
|
|
];
|
|
};
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dUQGx":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Template that creates a `KernelFunc` for binary ops.
|
|
* @param name Kernel name.
|
|
* @param binaryKernelImpl A `SimpleBinaryKernelImpl` for the kernel.
|
|
* @param binaryKernelComplexImpl Optional. If exists, represents a
|
|
* `ComplexBinaryKernelImpl` for the kernel, will be used when input dtype
|
|
* is `complex64`.
|
|
* @param dtype Optional. If set, the result has this dtype. Otherwise, the
|
|
* result has the same dtype as the first input. This is mainly used in
|
|
* comparison kernels, such as Equal, Less, Greater, etc.
|
|
*/ parcelHelpers.export(exports, "binaryKernelFunc", ()=>binaryKernelFunc);
|
|
/**
|
|
* Template that creates the complex type implementation for binary ops.
|
|
* Supports broadcast.
|
|
*/ parcelHelpers.export(exports, "createComplexBinaryKernelImpl", ()=>createComplexBinaryKernelImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _cast = require("../kernels/Cast");
|
|
var _complex = require("../kernels/Complex");
|
|
function binaryKernelFunc(name, simpleImpl, complexImpl, dtype) {
|
|
if (complexImpl == null) return ({ inputs, backend })=>{
|
|
const { a, b } = inputs;
|
|
const cpuBackend = backend;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
a,
|
|
b
|
|
], name);
|
|
const aVals = cpuBackend.data.get(a.dataId).values;
|
|
const bVals = cpuBackend.data.get(b.dataId).values;
|
|
const decodedAVals = a.dtype === "string" ? // tslint:disable-next-line: no-any
|
|
(0, _tfjsCore.backend_util).fromUint8ToStringArray(aVals) : aVals;
|
|
const decodedBVals = a.dtype === "string" ? // tslint:disable-next-line: no-any
|
|
(0, _tfjsCore.backend_util).fromUint8ToStringArray(bVals) : bVals;
|
|
const $dtype = dtype || a.dtype;
|
|
const [resultData, resultShape] = simpleImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype);
|
|
return cpuBackend.makeTensorInfo(resultShape, $dtype, resultData);
|
|
};
|
|
return ({ inputs, backend })=>{
|
|
const { a, b } = inputs;
|
|
const cpuBackend = backend;
|
|
if (a.dtype === "complex64" || b.dtype === "complex64") {
|
|
const $aComplex = (0, _cast.cast)({
|
|
inputs: {
|
|
x: a
|
|
},
|
|
backend: cpuBackend,
|
|
attrs: {
|
|
dtype: "complex64"
|
|
}
|
|
});
|
|
const $aComplexVals = cpuBackend.data.get($aComplex.dataId);
|
|
const aReal = $aComplexVals.complexTensorInfos.real;
|
|
const aImag = $aComplexVals.complexTensorInfos.imag;
|
|
const aRealVals = cpuBackend.data.get(aReal.dataId).values;
|
|
const aImagVals = cpuBackend.data.get(aImag.dataId).values;
|
|
const $bComplex = (0, _cast.cast)({
|
|
inputs: {
|
|
x: b
|
|
},
|
|
backend: cpuBackend,
|
|
attrs: {
|
|
dtype: "complex64"
|
|
}
|
|
});
|
|
const $bComplexVals = cpuBackend.data.get($bComplex.dataId);
|
|
const bReal = $bComplexVals.complexTensorInfos.real;
|
|
const bImag = $bComplexVals.complexTensorInfos.imag;
|
|
const bRealVals = cpuBackend.data.get(bReal.dataId).values;
|
|
const bImagVals = cpuBackend.data.get(bImag.dataId).values;
|
|
const [resultRealData, resultImagData, resultShape] = complexImpl(a.shape, b.shape, aRealVals, aImagVals, bRealVals, bImagVals);
|
|
const resultReal = cpuBackend.makeTensorInfo(resultShape, "float32", resultRealData);
|
|
const resultImag = cpuBackend.makeTensorInfo(resultShape, "float32", resultImagData);
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: resultReal,
|
|
imag: resultImag
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
cpuBackend.disposeIntermediateTensorInfo($aComplex);
|
|
cpuBackend.disposeIntermediateTensorInfo($bComplex);
|
|
cpuBackend.disposeIntermediateTensorInfo(resultReal);
|
|
cpuBackend.disposeIntermediateTensorInfo(resultImag);
|
|
return result;
|
|
} else {
|
|
const aVals = cpuBackend.data.get(a.dataId).values;
|
|
const bVals = cpuBackend.data.get(b.dataId).values;
|
|
const $dtype = dtype || a.dtype;
|
|
const [resultData, resultShape] = simpleImpl(a.shape, b.shape, aVals, bVals, $dtype);
|
|
return cpuBackend.makeTensorInfo(resultShape, $dtype, resultData);
|
|
}
|
|
};
|
|
}
|
|
function createComplexBinaryKernelImpl(op) {
|
|
return (aShape, bShape, aRealVals, aImagVals, bRealVals, bImagVals)=>{
|
|
const resultShape = (0, _tfjsCore.backend_util).assertAndGetBroadcastShape(aShape, bShape);
|
|
const resultSize = (0, _tfjsCore.util).sizeFromShape(resultShape);
|
|
const resultRank = resultShape.length;
|
|
const resultStrides = (0, _tfjsCore.util).computeStrides(resultShape);
|
|
const resultRealVals = (0, _tfjsCore.util).getTypedArrayFromDType("float32", resultSize);
|
|
const resultImagVals = (0, _tfjsCore.util).getTypedArrayFromDType("float32", resultSize);
|
|
const aBroadcastDims = (0, _tfjsCore.backend_util).getBroadcastDims(aShape, resultShape);
|
|
const bBroadcastDims = (0, _tfjsCore.backend_util).getBroadcastDims(bShape, resultShape);
|
|
const aVals = (0, _tfjsCore.backend_util).mergeRealAndImagArrays(aRealVals, aImagVals);
|
|
const bVals = (0, _tfjsCore.backend_util).mergeRealAndImagArrays(bRealVals, bImagVals);
|
|
const aRank = aShape.length;
|
|
const aStrides = (0, _tfjsCore.util).computeStrides(aShape);
|
|
const bRank = bShape.length;
|
|
const bStrides = (0, _tfjsCore.util).computeStrides(bShape);
|
|
if (aBroadcastDims.length + bBroadcastDims.length === 0) for(let i = 0; i < resultRealVals.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]);
|
|
resultRealVals[i] = result.real;
|
|
resultImagVals[i] = result.imag;
|
|
}
|
|
else for(let i = 0; i < resultRealVals.length; i++){
|
|
const loc = (0, _tfjsCore.util).indexToLoc(i, resultRank, resultStrides);
|
|
const aLoc = loc.slice(-aRank);
|
|
aBroadcastDims.forEach((d)=>aLoc[d] = 0);
|
|
const aIndex = (0, _tfjsCore.util).locToIndex(aLoc, aRank, aStrides);
|
|
const bLoc = loc.slice(-bRank);
|
|
bBroadcastDims.forEach((d)=>bLoc[d] = 0);
|
|
const bIndex = (0, _tfjsCore.util).locToIndex(bLoc, bRank, bStrides);
|
|
const opResult = op(aVals[aIndex * 2], aVals[aIndex * 2 + 1], bVals[bIndex * 2], bVals[bIndex * 2 + 1]);
|
|
resultRealVals[i] = opResult.real;
|
|
resultImagVals[i] = opResult.imag;
|
|
}
|
|
return [
|
|
resultRealVals,
|
|
resultImagVals,
|
|
resultShape
|
|
];
|
|
};
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../kernels/Cast":"fAtIw","../kernels/Complex":"3DPmh","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fAtIw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "castImpl", ()=>castImpl);
|
|
parcelHelpers.export(exports, "cast", ()=>cast);
|
|
parcelHelpers.export(exports, "castConfig", ()=>castConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _zerosImpl = require("../utils/zeros_impl");
|
|
var _complex = require("./Complex");
|
|
var _identity = require("./Identity");
|
|
var _real = require("./Real");
|
|
function castImpl(values, shape, inputType, dtype) {
|
|
if (dtype === "int32") {
|
|
const resultValues = Int32Array.from(values);
|
|
return [
|
|
shape,
|
|
"int32",
|
|
resultValues
|
|
];
|
|
}
|
|
if (dtype === "bool") {
|
|
// This is essentially the result of notEqual(x, 0). We avoid using
|
|
// kernel notEqual to avoid circular dependency, i.e. binary_utils ->
|
|
// cast -> notEqual -> binary_utils.
|
|
const zero = (0, _tfjsCore.util).toTypedArray([
|
|
0
|
|
], inputType);
|
|
const [resultData, resultShape] = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a !== b ? 1 : 0)(shape, [], values, zero, "bool");
|
|
return [
|
|
resultShape,
|
|
"bool",
|
|
resultData
|
|
];
|
|
}
|
|
throw new Error(`Error in Cast: failed to cast ${inputType} to ${dtype}`);
|
|
}
|
|
function cast(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { dtype } = attrs;
|
|
// Casting to complex64.
|
|
if (dtype === "complex64") {
|
|
if (x.dtype === "complex64") return (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
const zerosTensorInfo = (0, _zerosImpl.zeros)(backend, x.shape, x.dtype);
|
|
const floatX = cast({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dtype: "float32"
|
|
}
|
|
});
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: floatX,
|
|
imag: zerosTensorInfo
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(zerosTensorInfo);
|
|
backend.disposeIntermediateTensorInfo(floatX);
|
|
return result;
|
|
}
|
|
// Casting from complex64
|
|
if (x.dtype === "complex64") {
|
|
const realPart = (0, _real.real)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const result = cast({
|
|
inputs: {
|
|
x: realPart
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dtype
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(realPart);
|
|
return result;
|
|
}
|
|
if (!(0, _tfjsCore.util).hasEncodingLoss(x.dtype, dtype)) {
|
|
// We don't change the underlying data, since we cast to higher
|
|
// precision.
|
|
const result = (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
return {
|
|
dataId: result.dataId,
|
|
shape: result.shape,
|
|
dtype
|
|
};
|
|
}
|
|
const values = backend.data.get(x.dataId).values;
|
|
const [resultShape, resultType, resultData] = castImpl(values, x.shape, x.dtype, dtype);
|
|
return backend.makeTensorInfo(resultShape, resultType, resultData);
|
|
}
|
|
const castConfig = {
|
|
kernelName: (0, _tfjsCore.Cast),
|
|
backendName: "cpu",
|
|
kernelFunc: cast
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/zeros_impl":"6us7T","./Complex":"3DPmh","./Identity":"btREJ","./Real":"eZ7aJ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6us7T":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Generates a tensorInfo with all zeros value.
|
|
* @param backend cpu backend.
|
|
* @param shape Shape for the zeros tensor.
|
|
* @param dtype Optional. If set, the result has this dtype.
|
|
*/ parcelHelpers.export(exports, "zeros", ()=>zeros);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _complex = require("../kernels/Complex");
|
|
function zeros(backend, shape, dtype = "float32") {
|
|
if (dtype === "complex64") {
|
|
const real = zeros(backend, shape, "float32");
|
|
const imag = zeros(backend, shape, "float32");
|
|
return (0, _complex.complex)({
|
|
inputs: {
|
|
real,
|
|
imag
|
|
},
|
|
backend
|
|
});
|
|
}
|
|
const values = (0, _tfjsCore.util).makeZerosTypedArray((0, _tfjsCore.util).sizeFromShape(shape), dtype);
|
|
return backend.makeTensorInfo(shape, dtype, values);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernels/Complex":"3DPmh","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3DPmh":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "complex", ()=>complex);
|
|
parcelHelpers.export(exports, "complexConfig", ()=>complexConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function complex(args) {
|
|
const { inputs, backend } = args;
|
|
const { real, imag } = inputs;
|
|
const realVals = backend.data.get(real.dataId).values;
|
|
const imagVals = backend.data.get(imag.dataId).values;
|
|
const complexInfo = backend.makeTensorInfo(real.shape, "complex64");
|
|
const complex = backend.data.get(complexInfo.dataId);
|
|
// The complex tensor owns the underlying real and imag tensorInfos, only the
|
|
// complex tensor tracks refCount, when complexData is disposed the
|
|
// underlying tensorData will be disposed.
|
|
complex.complexTensorInfos = {
|
|
real: backend.makeTensorInfo(real.shape, "float32", realVals),
|
|
imag: backend.makeTensorInfo(imag.shape, "float32", imagVals)
|
|
};
|
|
return complexInfo;
|
|
}
|
|
const complexConfig = {
|
|
kernelName: (0, _tfjsCore.Complex),
|
|
backendName: "cpu",
|
|
kernelFunc: complex
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"btREJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "identity", ()=>identity);
|
|
parcelHelpers.export(exports, "identityConfig", ()=>identityConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function identity(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
backend.incRef(x.dataId);
|
|
return {
|
|
dataId: x.dataId,
|
|
shape: x.shape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
const identityConfig = {
|
|
kernelName: (0, _tfjsCore.Identity),
|
|
backendName: "cpu",
|
|
kernelFunc: identity
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eZ7aJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "real", ()=>real);
|
|
parcelHelpers.export(exports, "realConfig", ()=>realConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function real(args) {
|
|
const { inputs, backend } = args;
|
|
const { input } = inputs;
|
|
const real = backend.data.get(input.dataId).complexTensorInfos.real;
|
|
const realVal = backend.data.get(real.dataId).values;
|
|
// When complex tensor is disposed, its underlying parts will be disposed too.
|
|
// Make new tensor out of the real value of the complex. This makes sure the
|
|
// value is still accessible even if complex tensor is disposed.
|
|
return backend.makeTensorInfo(real.shape, real.dtype, realVal);
|
|
}
|
|
const realConfig = {
|
|
kernelName: (0, _tfjsCore.Real),
|
|
backendName: "cpu",
|
|
kernelFunc: real
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4EF2S":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "bincountImpl", ()=>bincountImpl);
|
|
parcelHelpers.export(exports, "bincountReduceImpl", ()=>bincountReduceImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function bincountImpl(xVals, weightsVals, weightsDtype, weightsShape, size) {
|
|
const weightsSize = (0, _tfjsCore.util).sizeFromShape(weightsShape);
|
|
const outVals = (0, _tfjsCore.util).makeZerosTypedArray(size, weightsDtype);
|
|
for(let i = 0; i < xVals.length; i++){
|
|
const value = xVals[i];
|
|
if (value < 0) throw new Error("Input x must be non-negative!");
|
|
if (value >= size) continue;
|
|
if (weightsSize > 0) outVals[value] += weightsVals[i];
|
|
else outVals[value] += 1;
|
|
}
|
|
return outVals;
|
|
}
|
|
function bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput = false) {
|
|
const numRows = xBuf.shape[0];
|
|
const numCols = xBuf.shape[1];
|
|
const outBuf = (0, _tfjsCore.buffer)([
|
|
numRows,
|
|
size
|
|
], weightsBuf.dtype);
|
|
for(let i = 0; i < numRows; i++)for(let j = 0; j < numCols; j++){
|
|
const value = xBuf.get(i, j);
|
|
if (value < 0) throw new Error("Input x must be non-negative!");
|
|
if (value >= size) continue;
|
|
if (binaryOutput) outBuf.set(1, i, value);
|
|
else if (weightsBuf.size > 0) outBuf.set(outBuf.get(i, value) + weightsBuf.get(i, j), i, value);
|
|
else outBuf.set(outBuf.get(i, value) + 1, i, value);
|
|
}
|
|
return outBuf;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lFHUr":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "bitwiseAndImpl", ()=>bitwiseAndImpl);
|
|
parcelHelpers.export(exports, "bitwiseAnd", ()=>bitwiseAnd);
|
|
parcelHelpers.export(exports, "bitwiseAndConfig", ()=>bitwiseAndConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const bitwiseAndImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a & b);
|
|
const bitwiseAnd = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.BitwiseAnd), bitwiseAndImpl);
|
|
const bitwiseAndConfig = {
|
|
kernelName: (0, _tfjsCore.BitwiseAnd),
|
|
backendName: "cpu",
|
|
kernelFunc: bitwiseAnd
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dPS5d":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ceilImpl", ()=>ceilImpl);
|
|
parcelHelpers.export(exports, "ceil", ()=>ceil);
|
|
parcelHelpers.export(exports, "ceilConfig", ()=>ceilConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const ceilImpl = (0, _unaryImpl.createSimpleUnaryImpl)((xi)=>Math.ceil(xi));
|
|
const ceil = (0, _unaryUtils.unaryKernelFuncFromImpl)((0, _tfjsCore.Ceil), ceilImpl);
|
|
const ceilConfig = {
|
|
kernelName: (0, _tfjsCore.Ceil),
|
|
backendName: "cpu",
|
|
kernelFunc: ceil
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jdtAN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Template that creates implementation for unary op.
|
|
*/ parcelHelpers.export(exports, "createSimpleUnaryImpl", ()=>createSimpleUnaryImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function createSimpleUnaryImpl(op) {
|
|
return (values, dtype, attrs)=>{
|
|
const newValues = (0, _tfjsCore.util).getArrayFromDType(dtype, values.length);
|
|
for(let i = 0; i < values.length; ++i)newValues[i] = op(values[i], attrs);
|
|
return newValues;
|
|
};
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5johK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Template that creates a `KernelFunc` for unary ops.
|
|
* @param name Kernel name.
|
|
* @param op A `SimpleUnaryOperation` for the kernel.
|
|
* @param dtype Optional. If set, the result has this dtype. Otherwise, the
|
|
* result has the same dtype as the input. This is mainly used in certain
|
|
* kernels that return bool type, such as isFinite, isInf, etc.
|
|
*/ parcelHelpers.export(exports, "unaryKernelFunc", ()=>unaryKernelFunc);
|
|
/**
|
|
* Template that creates a `KernelFunc` for unary ops from the given
|
|
* `SimpleUnaryImpl`..
|
|
* @param name Kernel name.
|
|
* @param unaryImpl A `SimpleUnaryImpl` that implements the op.
|
|
* @param dtype Optional. If set, the result has this dtype. Otherwise, the
|
|
* result has the same dtype as the input. This is mainly used in certain
|
|
* kernels that return bool type, such as isFinite, isInf, etc.
|
|
*/ parcelHelpers.export(exports, "unaryKernelFuncFromImpl", ()=>unaryKernelFuncFromImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _unaryImpl = require("./unary_impl");
|
|
function unaryKernelFunc(name, op, dtype) {
|
|
const impl = (0, _unaryImpl.createSimpleUnaryImpl)(op);
|
|
return unaryKernelFuncFromImpl(name, impl, dtype);
|
|
}
|
|
function unaryKernelFuncFromImpl(name, unaryImpl, dtype) {
|
|
return ({ inputs, attrs, backend })=>{
|
|
const { x } = inputs;
|
|
(0, _cpuUtil.assertNotComplex)(x, name);
|
|
const cpuBackend = backend;
|
|
const values = cpuBackend.data.get(x.dataId).values;
|
|
let decoded;
|
|
if (x.dtype === "string") {
|
|
if (!Array.isArray(values)) throw new Error("String tensor's value was not an instance of Array");
|
|
decoded = (0, _tfjsCore.backend_util).fromUint8ToStringArray(values);
|
|
} else decoded = values;
|
|
const $dtype = dtype || x.dtype;
|
|
const newValues = unaryImpl(decoded, $dtype, attrs);
|
|
return cpuBackend.makeTensorInfo(x.shape, $dtype, newValues);
|
|
};
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./unary_impl":"jdtAN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"50NO7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concatImpl", ()=>concatImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function concatImpl(inputs, outShape, dtype, simplyConcat) {
|
|
const outVals = (0, _tfjsCore.util).getArrayFromDType(dtype, (0, _tfjsCore.util).sizeFromShape(outShape));
|
|
if (simplyConcat && dtype !== "string") {
|
|
// Use built-in TypedArray.set() method for speed.
|
|
let offset = 0;
|
|
inputs.forEach((input)=>{
|
|
const size = (0, _tfjsCore.util).sizeFromShape(input.shape);
|
|
outVals.set(input.vals, offset);
|
|
offset += size;
|
|
});
|
|
} else {
|
|
let colOffset = 0;
|
|
inputs.forEach((input)=>{
|
|
const decodedData = dtype === "string" ? (0, _tfjsCore.backend_util).fromUint8ToStringArray(input.vals) : input.vals;
|
|
let tIdx = 0;
|
|
for(let row = 0; row < input.shape[0]; ++row){
|
|
const resIdx = row * outShape[1] + colOffset;
|
|
for(let col = 0; col < input.shape[1]; ++col)outVals[resIdx + col] = decodedData[tIdx++];
|
|
}
|
|
colOffset += input.shape[1];
|
|
});
|
|
}
|
|
return outVals;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jK2O7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "equalImpl", ()=>equalImpl);
|
|
parcelHelpers.export(exports, "equal", ()=>equal);
|
|
parcelHelpers.export(exports, "equalConfig", ()=>equalConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const equalImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a === b ? 1 : 0);
|
|
const equal = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Equal), equalImpl, null, "bool");
|
|
const equalConfig = {
|
|
kernelName: (0, _tfjsCore.Equal),
|
|
backendName: "cpu",
|
|
kernelFunc: equal
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6eexr":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "expImpl", ()=>expImpl);
|
|
parcelHelpers.export(exports, "exp", ()=>exp);
|
|
parcelHelpers.export(exports, "expConfig", ()=>expConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const expImpl = (0, _unaryImpl.createSimpleUnaryImpl)((xi)=>Math.exp(xi));
|
|
const exp = (0, _unaryUtils.unaryKernelFuncFromImpl)((0, _tfjsCore.Exp), expImpl, "float32");
|
|
const expConfig = {
|
|
kernelName: (0, _tfjsCore.Exp),
|
|
backendName: "cpu",
|
|
kernelFunc: exp
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"pXtet":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "expm1Impl", ()=>expm1Impl);
|
|
parcelHelpers.export(exports, "expm1", ()=>expm1);
|
|
parcelHelpers.export(exports, "expm1Config", ()=>expm1Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const expm1Impl = (0, _unaryImpl.createSimpleUnaryImpl)((xi)=>Math.expm1(xi));
|
|
const expm1 = (0, _unaryUtils.unaryKernelFuncFromImpl)((0, _tfjsCore.Expm1), expm1Impl);
|
|
const expm1Config = {
|
|
kernelName: (0, _tfjsCore.Expm1),
|
|
backendName: "cpu",
|
|
kernelFunc: expm1
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ftFzk":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "floorImpl", ()=>floorImpl);
|
|
parcelHelpers.export(exports, "floor", ()=>floor);
|
|
parcelHelpers.export(exports, "floorConfig", ()=>floorConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const floorImpl = (0, _unaryImpl.createSimpleUnaryImpl)((xi)=>Math.floor(xi));
|
|
const floor = (0, _unaryUtils.unaryKernelFuncFromImpl)((0, _tfjsCore.Floor), floorImpl);
|
|
const floorConfig = {
|
|
kernelName: (0, _tfjsCore.Floor),
|
|
backendName: "cpu",
|
|
kernelFunc: floor
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kMZnS":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "floorDivImpl", ()=>floorDivImpl);
|
|
parcelHelpers.export(exports, "floorDiv", ()=>floorDiv);
|
|
parcelHelpers.export(exports, "floorDivConfig", ()=>floorDivConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const floorDivImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>Math.floor(a / b));
|
|
const floorDiv = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.FloorDiv), floorDivImpl, null, "int32");
|
|
const floorDivConfig = {
|
|
kernelName: (0, _tfjsCore.FloorDiv),
|
|
backendName: "cpu",
|
|
kernelFunc: floorDiv
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"klZow":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gatherNdImpl", ()=>gatherNdImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function gatherNdImpl(indicesData, paramsBuf, dtype, numSlices, sliceRank, sliceSize, strides, paramsShape, paramsSize) {
|
|
const outBuf = (0, _tfjsCore.buffer)([
|
|
numSlices,
|
|
sliceSize
|
|
], dtype);
|
|
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 >= paramsSize / sliceSize) throw new Error(`Invalid indices: ${index} does not index into ${paramsShape}`);
|
|
for(let k = 0; k < sliceSize; k++)outBuf.values[i * sliceSize + k] = paramsBuf.get(...paramsBuf.indexToLoc(flattenIndex * sliceSize + k));
|
|
}
|
|
return outBuf;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5y26k":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gatherV2Impl", ()=>gatherV2Impl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function gatherV2Impl(xBuf, indicesBuf, flattenOutputShape) {
|
|
const outBuf = (0, _tfjsCore.buffer)(flattenOutputShape, xBuf.dtype);
|
|
for(let i = 0; i < outBuf.size; ++i){
|
|
const newLoc = outBuf.indexToLoc(i);
|
|
const originalLoc = newLoc.slice();
|
|
const batchIdx = originalLoc[0];
|
|
const indicesIdx = originalLoc[2];
|
|
const indicesIndex = indicesBuf.locToIndex([
|
|
batchIdx,
|
|
indicesIdx
|
|
]);
|
|
originalLoc[2] = indicesBuf.values[indicesIndex];
|
|
const originalIndex = xBuf.locToIndex(originalLoc);
|
|
if (0 <= originalIndex && originalIndex < xBuf.values.length) outBuf.values[i] = xBuf.values[originalIndex];
|
|
// Else, index is out of bounds, so leave the default zero val in outBuf.
|
|
}
|
|
return outBuf;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"94zPb":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "greaterImpl", ()=>greaterImpl);
|
|
parcelHelpers.export(exports, "greater", ()=>greater);
|
|
parcelHelpers.export(exports, "greaterConfig", ()=>greaterConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const greaterImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a > b ? 1 : 0);
|
|
const greater = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Greater), greaterImpl, null, "bool");
|
|
const greaterConfig = {
|
|
kernelName: (0, _tfjsCore.Greater),
|
|
backendName: "cpu",
|
|
kernelFunc: greater
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a9aqR":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "greaterEqualImpl", ()=>greaterEqualImpl);
|
|
parcelHelpers.export(exports, "greaterEqual", ()=>greaterEqual);
|
|
parcelHelpers.export(exports, "greaterEqualConfig", ()=>greaterEqualConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const greaterEqualImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a >= b ? 1 : 0);
|
|
const greaterEqual = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.GreaterEqual), greaterEqualImpl, null, "bool");
|
|
const greaterEqualConfig = {
|
|
kernelName: (0, _tfjsCore.GreaterEqual),
|
|
backendName: "cpu",
|
|
kernelFunc: greaterEqual
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"anwWy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "lessImpl", ()=>lessImpl);
|
|
parcelHelpers.export(exports, "less", ()=>less);
|
|
parcelHelpers.export(exports, "lessConfig", ()=>lessConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const lessImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a < b ? 1 : 0);
|
|
const less = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Less), lessImpl, null, "bool");
|
|
const lessConfig = {
|
|
kernelName: (0, _tfjsCore.Less),
|
|
backendName: "cpu",
|
|
kernelFunc: less
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"nFlBF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "lessEqualImpl", ()=>lessEqualImpl);
|
|
parcelHelpers.export(exports, "lessEqual", ()=>lessEqual);
|
|
parcelHelpers.export(exports, "lessEqualConfig", ()=>lessEqualConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const lessEqualImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a <= b ? 1 : 0);
|
|
const lessEqual = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.LessEqual), lessEqualImpl, null, "bool");
|
|
const lessEqualConfig = {
|
|
kernelName: (0, _tfjsCore.LessEqual),
|
|
backendName: "cpu",
|
|
kernelFunc: lessEqual
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4tRcP":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "linSpaceImpl", ()=>linSpaceImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function linSpaceImpl(start, stop, num) {
|
|
const step = (stop - start) / (num - 1);
|
|
const values = (0, _tfjsCore.util).makeZerosTypedArray(num, "float32");
|
|
values[0] = start;
|
|
for(let i = 1; i < values.length; i++)values[i] = values[i - 1] + step;
|
|
return values;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dNlq0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logImpl", ()=>logImpl);
|
|
parcelHelpers.export(exports, "log", ()=>log);
|
|
parcelHelpers.export(exports, "logConfig", ()=>logConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const logImpl = (0, _unaryImpl.createSimpleUnaryImpl)((xi)=>Math.log(xi));
|
|
const log = (0, _unaryUtils.unaryKernelFuncFromImpl)((0, _tfjsCore.Log), logImpl);
|
|
const logConfig = {
|
|
kernelName: (0, _tfjsCore.Log),
|
|
backendName: "cpu",
|
|
kernelFunc: log
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6BNe1":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxImpl", ()=>maxImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function maxImpl(aVals, reduceSize, outShape, dtype) {
|
|
const vals = (0, _tfjsCore.util).getTypedArrayFromDType(dtype, (0, _tfjsCore.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 (Number.isNaN(value) || value > max) max = value;
|
|
}
|
|
vals[i] = max;
|
|
}
|
|
return vals;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"73P1X":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maximumImpl", ()=>maximumImpl);
|
|
parcelHelpers.export(exports, "maximum", ()=>maximum);
|
|
parcelHelpers.export(exports, "maximumConfig", ()=>maximumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const maximumImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((aValue, bValue)=>Math.max(aValue, bValue));
|
|
const maximum = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Maximum), maximumImpl);
|
|
const maximumConfig = {
|
|
kernelName: (0, _tfjsCore.Maximum),
|
|
backendName: "cpu",
|
|
kernelFunc: maximum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2gO4x":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "minimumImpl", ()=>minimumImpl);
|
|
parcelHelpers.export(exports, "minimum", ()=>minimum);
|
|
parcelHelpers.export(exports, "minimumConfig", ()=>minimumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const minimumImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((aValue, bValue)=>Math.min(aValue, bValue));
|
|
const minimum = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Minimum), minimumImpl);
|
|
const minimumConfig = {
|
|
kernelName: (0, _tfjsCore.Minimum),
|
|
backendName: "cpu",
|
|
kernelFunc: minimum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"FrRi2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "multiplyImpl", ()=>multiplyImpl);
|
|
parcelHelpers.export(exports, "multiplyComplexImpl", ()=>multiplyComplexImpl);
|
|
parcelHelpers.export(exports, "multiply", ()=>multiply);
|
|
parcelHelpers.export(exports, "multiplyConfig", ()=>multiplyConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const multiplyImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((aValue, bValue)=>aValue * bValue);
|
|
const multiplyComplexImpl = (0, _binaryUtils.createComplexBinaryKernelImpl)((aReal, aImag, bReal, bImag)=>{
|
|
return {
|
|
real: aReal * bReal - aImag * bImag,
|
|
imag: aReal * bImag + aImag * bReal
|
|
};
|
|
});
|
|
const multiply = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Multiply), multiplyImpl, multiplyComplexImpl);
|
|
const multiplyConfig = {
|
|
kernelName: (0, _tfjsCore.Multiply),
|
|
backendName: "cpu",
|
|
kernelFunc: multiply
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4sfM4":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "negImpl", ()=>negImpl);
|
|
parcelHelpers.export(exports, "neg", ()=>neg);
|
|
parcelHelpers.export(exports, "negConfig", ()=>negConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _multiply = require("./Multiply");
|
|
function negImpl(xVals, xShape, xDtype) {
|
|
const minusOne = (0, _tfjsCore.util).createScalarValue(-1, xDtype);
|
|
return (0, _multiply.multiplyImpl)([], xShape, minusOne, xVals, xDtype);
|
|
}
|
|
function neg(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "neg");
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const [res, newShape] = negImpl(xVals, x.shape, x.dtype);
|
|
return backend.makeTensorInfo(newShape, x.dtype, res);
|
|
}
|
|
const negConfig = {
|
|
kernelName: (0, _tfjsCore.Neg),
|
|
backendName: "cpu",
|
|
kernelFunc: neg
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Multiply":"FrRi2","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"i62sj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "notEqualImpl", ()=>notEqualImpl);
|
|
parcelHelpers.export(exports, "notEqual", ()=>notEqual);
|
|
parcelHelpers.export(exports, "notEqualConfig", ()=>notEqualConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const notEqualImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a !== b ? 1 : 0);
|
|
const notEqual = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.NotEqual), notEqualImpl, null, "bool");
|
|
const notEqualConfig = {
|
|
kernelName: (0, _tfjsCore.NotEqual),
|
|
backendName: "cpu",
|
|
kernelFunc: notEqual
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8NwGT":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "prodImpl", ()=>prodImpl);
|
|
parcelHelpers.export(exports, "prod", ()=>prod);
|
|
parcelHelpers.export(exports, "prodConfig", ()=>prodConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _transpose = require("./Transpose");
|
|
function prodImpl(xShape, xDtype, xVals, reductionAxes) {
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(xShape, reductionAxes);
|
|
const outDtype = (0, _tfjsCore.upcastType)(xDtype, "int32");
|
|
const outVals = (0, _tfjsCore.util).makeZerosTypedArray((0, _tfjsCore.util).sizeFromShape(outShape), outDtype);
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
for(let i = 0; i < outVals.length; ++i){
|
|
const offset = i * reduceSize;
|
|
let prod = 1;
|
|
for(let j = 0; j < reduceSize; ++j)prod *= xVals[offset + j];
|
|
outVals[i] = prod;
|
|
}
|
|
return {
|
|
outVals,
|
|
outShape,
|
|
outDtype
|
|
};
|
|
}
|
|
function prod(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "prod");
|
|
const xRank = x.shape.length;
|
|
const axes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
const permutation = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
let reductionAxes = axes;
|
|
let permutedX = x;
|
|
const intermediateTensorInfos = [];
|
|
if (permutation != null) {
|
|
permutedX = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutation
|
|
}
|
|
});
|
|
intermediateTensorInfos.push(permutedX);
|
|
reductionAxes = (0, _tfjsCore.backend_util).getInnerMostAxes(reductionAxes.length, xRank);
|
|
}
|
|
const xVals = backend.data.get(permutedX.dataId).values;
|
|
const { outVals, outShape, outDtype } = prodImpl(permutedX.shape, permutedX.dtype, xVals, reductionAxes);
|
|
let resultShape = outShape;
|
|
if (keepDims) resultShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(outShape, axes);
|
|
intermediateTensorInfos.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return backend.makeTensorInfo(resultShape, outDtype, outVals);
|
|
}
|
|
const prodConfig = {
|
|
kernelName: (0, _tfjsCore.Prod),
|
|
backendName: "cpu",
|
|
kernelFunc: prod
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"61ywv":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "transpose", ()=>transpose);
|
|
parcelHelpers.export(exports, "transposeConfig", ()=>transposeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _transposeImpl = require("./Transpose_impl");
|
|
function transpose(args) {
|
|
const { inputs, attrs, backend } = args;
|
|
const { x } = inputs;
|
|
const { perm } = attrs;
|
|
(0, _cpuUtil.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 = backend.data.get(x.dataId).values;
|
|
const result = (0, _transposeImpl.transposeImpl)(values, x.shape, x.dtype, perm, newShape);
|
|
const dataId = backend.write(result, newShape, x.dtype);
|
|
return {
|
|
dataId,
|
|
shape: newShape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
const transposeConfig = {
|
|
kernelName: (0, _tfjsCore.Transpose),
|
|
backendName: "cpu",
|
|
kernelFunc: transpose
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Transpose_impl":"2fFZe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2fFZe":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "transposeImpl", ()=>transposeImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function transposeImpl(xVals, xShape, dtype, perm, newShape) {
|
|
const xRank = xShape.length;
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(xShape);
|
|
const xStrides = (0, _tfjsCore.util).computeStrides(xShape);
|
|
const newStrides = (0, _tfjsCore.util).computeStrides(newShape);
|
|
const result = (0, _tfjsCore.util).getTypedArrayFromDType(dtype, (0, _tfjsCore.util).sizeFromShape(newShape));
|
|
for(let i = 0; i < xSize; ++i){
|
|
const loc = (0, _tfjsCore.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 = (0, _tfjsCore.util).locToIndex(newLoc, xRank, newStrides);
|
|
result[newIndex] = xVals[i];
|
|
}
|
|
return result;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"59HGn":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedGatherImpl", ()=>raggedGatherImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function validateIndices(indices, indicesShape, numParams) {
|
|
indices.forEach((index, i)=>{
|
|
if (index < 0 || index >= numParams) {
|
|
const locString = (0, _tfjsCore.util).indexToLoc(i, indicesShape.length, (0, _tfjsCore.util).computeStrides(indicesShape)).join(",");
|
|
throw new Error(`indices[${locString}] = ${index} is not in [0, ${numParams})`);
|
|
}
|
|
});
|
|
}
|
|
function validateSplits(paramsNestedSplits, numParamsDenseValues) {
|
|
// Validate
|
|
for(let dim = 0; dim < paramsNestedSplits.length; ++dim){
|
|
const splits = paramsNestedSplits[dim];
|
|
const lastSplit = dim === paramsNestedSplits.length - 1 ? numParamsDenseValues : paramsNestedSplits[dim + 1].length;
|
|
if (splits.length === 0) throw new Error("Ragged splits may not be empty");
|
|
if (splits[0] < 0) throw new Error("Ragged splits must be non-negative");
|
|
if (splits[splits.length - 1] > lastSplit) throw new Error("Ragged splits must not point past values");
|
|
for(let i = 1; i < splits.length; ++i){
|
|
if (splits[i - 1] > splits[i]) throw new Error("Ragged splits must be sorted in ascending order");
|
|
}
|
|
}
|
|
}
|
|
// Construct the `splits` output tensors, encoded using a nested vector.
|
|
// Also find the slices of values that need to be copied, and store them
|
|
// in `valueSlices`. The total number of values that will be copied (which
|
|
// we need for allocating the output values tensor) is stored in `numValues`.
|
|
function makeSplits(indices, indicesShape, paramsNestedSplits, numParamsDenseValues) {
|
|
const valueSlices = [];
|
|
let numValues = 0;
|
|
const numSplits = indicesShape.length - 1 + paramsNestedSplits.length;
|
|
const outSplits = new Array(numSplits).fill(null).map(()=>[
|
|
0
|
|
]);
|
|
validateSplits(paramsNestedSplits, numParamsDenseValues);
|
|
// Add `splits` that come from all but the last dimension of the dense
|
|
// Tensor `indices`. In particular, for each dimension D, we add a
|
|
// splits tensor whose values are:
|
|
// range(reduceProd(splits.shape[:D]) + 1) * splits.shape[D+1]
|
|
// E.g., if indices.shape=[2, 3, 4] then we will add splits tensors:
|
|
// [0, 3, 6] # length=2+1, stride=3
|
|
// [0, 4, 8, 12, 16, 20, 24] # length=2*3+1, stride=4
|
|
let nrows = 1;
|
|
for(let dim = 0; dim < indicesShape.length - 1; ++dim){
|
|
nrows *= indicesShape[dim];
|
|
const rowLength = indicesShape[dim + 1];
|
|
for(let i = 1; i < nrows + 1; ++i)outSplits[dim].push(i * rowLength);
|
|
}
|
|
// Add `splits` that come from `paramsNestedSplits`. Starting with the
|
|
// outermost ragged dimension (i.e., the first `splits` tensor), we work
|
|
// our way in, finding the range of values that should be copied. As we
|
|
// go, we update the output `splits` for each dimension with the appropriate
|
|
// values. In particular, the *lengths* of the slices from `param_splits`
|
|
// should be copied to generate corresponding slice lengths in the output
|
|
// splits. E.g., if we are copying a ragged row with length 4, then we
|
|
// should add a new split point to outSplits that is 4 greater than the
|
|
// previous split point in outSplits.
|
|
for(let i = 0; i < indices.length; ++i){
|
|
let start = indices[i];
|
|
let limit = indices[i] + 1;
|
|
// Copy splits.
|
|
for(let dim = 0; dim < paramsNestedSplits.length; ++dim){
|
|
const splits = paramsNestedSplits[dim];
|
|
const outDim = dim + indicesShape.length - 1;
|
|
if (outDim >= 0) {
|
|
const outSplitsOutDim = outSplits[outDim];
|
|
const delta = outSplitsOutDim[outSplitsOutDim.length - 1] - splits[start];
|
|
for(let j = start; j < limit; ++j)outSplits[outDim].push(splits[j + 1] + delta);
|
|
}
|
|
start = splits[start];
|
|
limit = splits[limit];
|
|
}
|
|
if (limit !== start) {
|
|
valueSlices.push([
|
|
start,
|
|
limit
|
|
]);
|
|
numValues += limit - start;
|
|
}
|
|
}
|
|
return {
|
|
outSplits,
|
|
valueSlices,
|
|
numValues
|
|
};
|
|
}
|
|
function getSplits(outSplits) {
|
|
const splitsOut = [];
|
|
for(let i = 0; i < outSplits.length; ++i){
|
|
const numSplits = outSplits[i].length;
|
|
const splits = (0, _tfjsCore.util).getArrayFromDType("int32", numSplits);
|
|
splitsOut.push(splits);
|
|
outSplits[i].forEach((value, j)=>splits[j] = value);
|
|
}
|
|
return splitsOut;
|
|
}
|
|
function computeFlatOuterDims(orig, numOutDims) {
|
|
const outDims = orig.slice(0, numOutDims);
|
|
while(outDims.length < numOutDims)outDims.push(1);
|
|
for(let inDim = numOutDims; inDim < orig.length; inDim++)outDims[numOutDims - 1] *= orig[inDim];
|
|
return outDims;
|
|
}
|
|
// For each slice in `(start, limit)` in `valueSlices`, append
|
|
// `paramsDenseValues[start,...,limit] to `values`. `valueSize` indicates
|
|
// the number of scalars contained in each value paramsDenseValues[i].
|
|
function writeValueSlices(paramsDenseValues, paramsDenseValuesShape, valueSlices, valueSize, values, valuesShape) {
|
|
const denseM = computeFlatOuterDims(paramsDenseValuesShape, 2)[1];
|
|
const valuesM = computeFlatOuterDims(valuesShape, 2)[1];
|
|
let outPos = 0;
|
|
for (const slice of valueSlices)for(let i = slice[0]; i < slice[1]; ++i){
|
|
for(let j = 0; j < valueSize; ++j)values[outPos * valuesM + j] = paramsDenseValues[i * denseM + j];
|
|
++outPos;
|
|
}
|
|
}
|
|
function getValues(paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, valueSlices, numValues) {
|
|
const valuesShape = paramsDenseValuesShape.slice();
|
|
valuesShape[0] = numValues;
|
|
const valuesOut = (0, _tfjsCore.util).getArrayFromDType(paramsDenseValuesDType, (0, _tfjsCore.util).sizeFromShape(valuesShape));
|
|
const numElements = paramsDenseValues.length;
|
|
const valueSize = numElements === 0 ? 0 : numElements / paramsDenseValuesShape[0];
|
|
writeValueSlices(paramsDenseValues, paramsDenseValuesShape, valueSlices, valueSize, valuesOut, valuesShape);
|
|
return [
|
|
valuesOut,
|
|
valuesShape
|
|
];
|
|
}
|
|
function raggedGatherImpl(paramsNestedSplits, paramsNestedSplitsShapes, paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, indices, indicesShape, outputRaggedRank) {
|
|
if (paramsNestedSplits.length === 0) throw new Error("paramsNestedSplits must be non empty");
|
|
if (paramsNestedSplitsShapes[0].length === 0) throw new Error("Split tensors must not be scalars");
|
|
const numParams = paramsNestedSplitsShapes[0][0] - 1;
|
|
validateIndices(indices, indicesShape, numParams);
|
|
if (paramsDenseValuesShape.length === 0) throw new Error("params.rank must be nonzero");
|
|
const numParamsDenseValues = paramsDenseValuesShape[0];
|
|
// Calculate the `splits`, and store the value slices that we need to
|
|
// copy in `valueSlices`.
|
|
const { outSplits, valueSlices, numValues } = makeSplits(indices, indicesShape, paramsNestedSplits, numParamsDenseValues);
|
|
// Write the output tensors.
|
|
const outputNestedSplits = getSplits(outSplits);
|
|
const outputDenseValues = getValues(paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType, valueSlices, numValues);
|
|
return [
|
|
outputNestedSplits,
|
|
outputDenseValues[0],
|
|
outputDenseValues[1]
|
|
];
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"l2R3s":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedRangeImpl", ()=>raggedRangeImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const INT32_MAX = 2147483647;
|
|
function raggedRangeImpl(starts, startsShape, startsDType, limits, limitsShape, deltas, deltasShape) {
|
|
// Check input tensor shapes.
|
|
if (startsShape.length > 1) throw new Error("starts must be a scalar or vector");
|
|
if (limitsShape.length > 1) throw new Error("limits must be a scalar or vector");
|
|
if (deltasShape.length > 1) throw new Error("deltas must be a scalar or vector");
|
|
// Determine which tensors we need to broadcast.
|
|
const broadcastStarts = startsShape.length === 0;
|
|
const broadcastLimits = limitsShape.length === 0;
|
|
const broadcastDeltas = deltasShape.length === 0;
|
|
// nRows (number of output rows) is the size of the non-broadcast inputs,
|
|
// or 1 if all inputs are scalars.
|
|
const inSizes = [];
|
|
if (!broadcastStarts) inSizes.push(startsShape[0]);
|
|
if (!broadcastLimits) inSizes.push(limitsShape[0]);
|
|
if (!broadcastDeltas) inSizes.push(deltasShape[0]);
|
|
for(let i = 1; i < inSizes.length; ++i){
|
|
if (inSizes[i] !== inSizes[i - 1]) throw new Error("starts, limits, and deltas must have the same shape");
|
|
}
|
|
const nRows = inSizes.length === 0 ? 1 : inSizes[0];
|
|
// Construct the rtNestedSplits tensor.
|
|
const rtNestedSplits = (0, _tfjsCore.util).getArrayFromDType("int32", nRows + 1);
|
|
rtNestedSplits[0] = 0;
|
|
for(let row = 0; row < nRows; ++row){
|
|
const start = broadcastStarts ? starts[0] : starts[row];
|
|
const limit = broadcastLimits ? limits[0] : limits[row];
|
|
const delta = broadcastDeltas ? deltas[0] : deltas[row];
|
|
if (delta === 0) throw new Error("Requires delta != 0");
|
|
let size; // The number of elements in the specified range.
|
|
if (delta > 0 && limit < start || delta < 0 && limit > start) size = 0;
|
|
else {
|
|
size = Math.ceil(Math.abs((limit - start) / delta));
|
|
if (size > INT32_MAX) throw new Error(`Requires ((limit - start) / delta) <= ${INT32_MAX}`);
|
|
}
|
|
rtNestedSplits[row + 1] = rtNestedSplits[row] + size;
|
|
}
|
|
const nVals = rtNestedSplits[nRows];
|
|
// Construct the rtDenseValues tensor.
|
|
const rtDenseValues = (0, _tfjsCore.util).getArrayFromDType(startsDType, nVals);
|
|
let valueIndex = 0;
|
|
for(let row = 0; row < nRows; ++row){
|
|
const rowSize = rtNestedSplits[row + 1] - rtNestedSplits[row];
|
|
let value = broadcastStarts ? starts[0] : starts[row];
|
|
const delta = broadcastDeltas ? deltas[0] : deltas[row];
|
|
for(let i = 0; i < rowSize; ++i){
|
|
rtDenseValues[valueIndex++] = value;
|
|
value += delta;
|
|
}
|
|
}
|
|
return [
|
|
rtNestedSplits,
|
|
rtDenseValues
|
|
];
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jDwSG":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedTensorToTensorImpl", ()=>raggedTensorToTensorImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var RowPartitionType = (0, _tfjsCore.backend_util).RowPartitionType;
|
|
// Based on
|
|
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/ragged_tensor_to_tensor_op.cc
|
|
class RaggedTensorToTensorOp {
|
|
constructor(shape, shapeShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypeStrings){
|
|
this.shape = shape;
|
|
this.shapeShape = shapeShape;
|
|
this.values = values;
|
|
this.valuesShape = valuesShape;
|
|
this.valuesDType = valuesDType;
|
|
this.defaultValue = defaultValue;
|
|
this.defaultValueShape = defaultValueShape;
|
|
this.rowPartitionValues = rowPartitionValues;
|
|
this.rowPartitionValuesShapes = rowPartitionValuesShapes;
|
|
this.rowPartitionTypes = (0, _tfjsCore.backend_util).getRowPartitionTypesHelper(rowPartitionTypeStrings);
|
|
this.raggedRank = (0, _tfjsCore.backend_util).getRaggedRank(this.rowPartitionTypes);
|
|
}
|
|
getRowPartitionTypeByDimension(dimension) {
|
|
if (this.rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) return this.rowPartitionTypes[dimension + 1];
|
|
else return this.rowPartitionTypes[dimension];
|
|
}
|
|
// Returns the relationship between dimension and dimension + 1.
|
|
getRowPartitionTensor(dimension) {
|
|
if (this.rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) return this.rowPartitionValues[dimension + 1];
|
|
else return this.rowPartitionValues[dimension];
|
|
}
|
|
getMaxWidth(dimension) {
|
|
const rowPartitionTensor = this.getRowPartitionTensor(dimension - 1);
|
|
switch(this.getRowPartitionTypeByDimension(dimension - 1)){
|
|
case RowPartitionType.VALUE_ROWIDS:
|
|
return RaggedTensorToTensorOp.getMaxWidthValueRowID(rowPartitionTensor);
|
|
case RowPartitionType.ROW_SPLITS:
|
|
return RaggedTensorToTensorOp.getMaxWidthRowSplit(rowPartitionTensor);
|
|
default:
|
|
throw new Error(`Cannot handle partition type ${RowPartitionType[this.getRowPartitionTypeByDimension(dimension - 1)]}`);
|
|
}
|
|
}
|
|
static getMaxWidthRowSplit(rowSplit) {
|
|
const tensorLength = rowSplit.length;
|
|
if (tensorLength === 0 || tensorLength === 1) return 0;
|
|
let maxWidth = 0;
|
|
for(let i = 0; i < tensorLength - 1; ++i){
|
|
const currentWidth = rowSplit[i + 1] - rowSplit[i];
|
|
if (currentWidth > maxWidth) maxWidth = currentWidth;
|
|
}
|
|
return maxWidth;
|
|
}
|
|
static getMaxWidthValueRowID(valueRowIds) {
|
|
const indexLength = valueRowIds.length;
|
|
if (indexLength === 0) return 0;
|
|
let firstEqualIndex = 0;
|
|
let firstEqualIndexValue = valueRowIds[0];
|
|
let maxWidth = 0;
|
|
for(let i = 1; i < indexLength; ++i){
|
|
const value = valueRowIds[i];
|
|
if (value !== firstEqualIndexValue) {
|
|
firstEqualIndexValue = value;
|
|
maxWidth = Math.max(i - firstEqualIndex, maxWidth);
|
|
firstEqualIndex = i;
|
|
}
|
|
}
|
|
return Math.max(indexLength - firstEqualIndex, maxWidth);
|
|
}
|
|
tensorShapeFromTensor(t, tShape, isPartial = true) {
|
|
if (tShape.length === 0) {
|
|
if (t[0] === -1) return [];
|
|
throw new Error(`The only valid scalar shape tensor is the fully unknown shape specified as -1.`);
|
|
}
|
|
// MakePartialShape/MakeShapeHelper.
|
|
return makeShape(t, isPartial);
|
|
}
|
|
calculateOutputSize(firstDim) {
|
|
const valueShape = this.valuesShape;
|
|
const defaultValueShape = this.defaultValueShape;
|
|
(0, _tfjsCore.backend_util).validateDefaultValueShape(defaultValueShape, valueShape);
|
|
const shape = this.tensorShapeFromTensor(this.shape, this.shapeShape);
|
|
const outputShape = (0, _tfjsCore.backend_util).combineRaggedTensorToTensorShapes(this.raggedRank, shape, valueShape);
|
|
const result = outputShape;
|
|
if (result[0] < 0) result[0] = firstDim;
|
|
for(let i = 1; i <= this.raggedRank; ++i)if (result[i] < 0) result[i] = this.getMaxWidth(i);
|
|
return result;
|
|
}
|
|
/**
|
|
* The outputIndex represents the index in the output tensor
|
|
* where the first element of a particular dimension would be written.
|
|
* If it is -1, it indicates that the index is out of scope.
|
|
* Example, given firstDimension = 10, firstDimensionOutput = 6,
|
|
* and outputIndexMultiplier = 100:
|
|
* result = [0 100 200 300 400 500 -1 -1 -1 -1]
|
|
* If firstDimensionOutput = 11 instead, then:
|
|
* result = [0 100 200 300 400 500 600 700 800 900]
|
|
*/ calculateFirstParentOutputIndex(firstDimension, outputIndexMultiplier, firstDimensionOutput) {
|
|
const minDimension = Math.min(firstDimension, firstDimensionOutput);
|
|
const result = [];
|
|
let currentOutputIndex = 0;
|
|
for(let i = 0; i < minDimension; ++i, currentOutputIndex += outputIndexMultiplier)result.push(currentOutputIndex);
|
|
for(let i = minDimension; i < firstDimension; ++i)result.push(-1);
|
|
(0, _tfjsCore.util).assert(result.length === firstDimension, ()=>"Final length of result must be equal to firstDimension.");
|
|
return result;
|
|
}
|
|
calculateOutputIndexRowSplit(rowSplit, parentOutputIndex, outputIndexMultiplier, outputSize) {
|
|
const rowSplitSize = rowSplit.length;
|
|
const result = [];
|
|
for(let i = 0; i < rowSplitSize - 1; ++i){
|
|
const rowLength = rowSplit[i + 1] - rowSplit[i];
|
|
let realLength = Math.min(outputSize, rowLength);
|
|
let parentOutputIndexCurrent = parentOutputIndex[i];
|
|
if (parentOutputIndexCurrent === -1) realLength = 0;
|
|
for(let j = 0; j < realLength; ++j){
|
|
result.push(parentOutputIndexCurrent);
|
|
parentOutputIndexCurrent += outputIndexMultiplier;
|
|
}
|
|
for(let j = 0; j < rowLength - realLength; ++j)result.push(-1);
|
|
}
|
|
if (rowSplitSize > 0 && result.length !== rowSplit[rowSplitSize - 1]) throw new Error("Invalid row split size.");
|
|
return result;
|
|
}
|
|
// Calculate the output index of the first element of a list.
|
|
// The parentOutputIndex is the same computation for the previous list.
|
|
// -1 indicates an element or list that is out of range.
|
|
// The outputIndexMultiplier is the number of output indices one moves
|
|
// forward for each column.
|
|
// E.g., given:
|
|
// valueRowIds:[0 1 2 2 2 3 5 5 6]
|
|
// parentOutputIndex:[1000 1100 2000 2100 -1 3000 4000]
|
|
// outputIndexMultiplier: 10
|
|
// outputSize: 2
|
|
// You get:
|
|
// result = [1000 1100 2000 2010 -1 2100 -1 -1 3000]
|
|
// result[0] = parentOutputIndex[valueRowIds[0]]
|
|
// result[1] = parentOutputIndex[valueRowIds[1]]
|
|
// result[2] = parentOutputIndex[valueRowIds[2]]
|
|
// result[3] = parentOutputIndex[valueRowIds[2] + 10]
|
|
// result[4] = -1 because it is the third element the size is 2.
|
|
// result[5] = parentOutputIndex[valueRowIds[3]]
|
|
// result[6] = -1 because parentOutputIndex[valueRowIds[6]] == -1
|
|
// result[7] = -1 because parentOutputIndex[valueRowIds[6]] == -1
|
|
// result[8] = parentOutputIndex[valueRowIds[7]]
|
|
calculateOutputIndexValueRowID(valueRowIds, parentOutputIndex, outputIndexMultiplier, outputSize) {
|
|
const indexSize = valueRowIds.length;
|
|
const result = [];
|
|
if (indexSize === 0) return [];
|
|
let currentOutputColumn = 0;
|
|
let currentValueRowId = valueRowIds[0];
|
|
if (currentValueRowId >= parentOutputIndex.length) throw new Error(`Got currentValueRowId=${currentValueRowId}, which is not less than ${parentOutputIndex.length}`);
|
|
let currentOutputIndex = parentOutputIndex[currentValueRowId];
|
|
result.push(currentOutputIndex);
|
|
for(let i = 1; i < indexSize; ++i){
|
|
const nextValueRowId = valueRowIds[i];
|
|
if (nextValueRowId === currentValueRowId) {
|
|
if (currentOutputIndex >= 0) {
|
|
++currentOutputColumn;
|
|
if (currentOutputColumn < outputSize) currentOutputIndex += outputIndexMultiplier;
|
|
else currentOutputIndex = -1;
|
|
}
|
|
} else {
|
|
currentOutputColumn = 0;
|
|
currentValueRowId = nextValueRowId;
|
|
if (nextValueRowId >= parentOutputIndex.length) throw new Error(`Got nextValueRowId=${nextValueRowId} which is not less than ${parentOutputIndex.length}`);
|
|
currentOutputIndex = parentOutputIndex[nextValueRowId];
|
|
}
|
|
result.push(currentOutputIndex);
|
|
}
|
|
if (result.length !== valueRowIds.length) throw new Error("Invalid row ids.");
|
|
return result;
|
|
}
|
|
calculateOutputIndex(dimension, parentOutputIndex, outputIndexMultiplier, outputSize) {
|
|
const rowPartitionTensor = this.getRowPartitionTensor(dimension);
|
|
const partitionType = this.getRowPartitionTypeByDimension(dimension);
|
|
switch(partitionType){
|
|
case RowPartitionType.VALUE_ROWIDS:
|
|
return this.calculateOutputIndexValueRowID(rowPartitionTensor, parentOutputIndex, outputIndexMultiplier, outputSize);
|
|
case RowPartitionType.ROW_SPLITS:
|
|
if (rowPartitionTensor.length - 1 > parentOutputIndex.length) throw new Error(`Row partition size is greater than output size: ${rowPartitionTensor.length - 1} > ${parentOutputIndex.length}`);
|
|
return this.calculateOutputIndexRowSplit(rowPartitionTensor, parentOutputIndex, outputIndexMultiplier, outputSize);
|
|
default:
|
|
throw new Error(`Unsupported partition type: ${RowPartitionType[partitionType]}`);
|
|
}
|
|
}
|
|
getFirstDimensionSize() {
|
|
const firstPartitionTensor = this.rowPartitionValues[0];
|
|
if (this.rowPartitionTypes.length === 0) throw new Error("No row_partition_types given.");
|
|
const firstPartitionType = this.rowPartitionTypes[0];
|
|
switch(firstPartitionType){
|
|
case RowPartitionType.FIRST_DIM_SIZE:
|
|
return firstPartitionTensor[0];
|
|
case RowPartitionType.VALUE_ROWIDS:
|
|
throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");
|
|
case RowPartitionType.ROW_SPLITS:
|
|
return this.rowPartitionValuesShapes[0][0] - 1;
|
|
default:
|
|
throw new Error(`Cannot handle type ${RowPartitionType[firstPartitionType]}`);
|
|
}
|
|
}
|
|
compute() {
|
|
const firstPartitionTensor = this.rowPartitionValues[0];
|
|
if (firstPartitionTensor.length <= 0) throw new Error("Invalid first partition input. Tensor requires at least one element.");
|
|
const firstDimension = this.getFirstDimensionSize();
|
|
const outputSize = this.calculateOutputSize(firstDimension);
|
|
const multiplier = new Array(this.raggedRank + 1);
|
|
multiplier[multiplier.length - 1] = 1;
|
|
for(let i = multiplier.length - 2; i >= 0; --i)multiplier[i] = multiplier[i + 1] * outputSize[i + 1];
|
|
// Full size of the tensor.
|
|
const outputShape = makeShape(outputSize, false);
|
|
const outputTensor = (0, _tfjsCore.util).getArrayFromDType(this.valuesDType, (0, _tfjsCore.util).sizeFromShape(outputShape));
|
|
const fullSize = multiplier[0] * outputSize[0];
|
|
if (fullSize > 0) {
|
|
let outputIndex = this.calculateFirstParentOutputIndex(firstDimension, multiplier[0], outputSize[0]);
|
|
for(let i = 1; i <= this.raggedRank; ++i){
|
|
const newOutputIndex = this.calculateOutputIndex(i - 1, outputIndex, multiplier[i], outputSize[i]);
|
|
outputIndex = newOutputIndex;
|
|
}
|
|
this.setOutput(this.raggedRank, outputIndex, outputTensor, outputShape);
|
|
}
|
|
return [
|
|
outputShape,
|
|
outputTensor
|
|
];
|
|
}
|
|
setOutput(raggedRank, outputIndex, outputTensor, outputShape) {
|
|
if (outputTensor.length === 0) return;
|
|
const valuesBase = this.values;
|
|
const outputBase = outputTensor;
|
|
let elementShape = outputShape.slice();
|
|
elementShape = elementShape.slice(raggedRank + 1);
|
|
const valueElementSize = (0, _tfjsCore.util).sizeFromShape(elementShape);
|
|
const outputIndexSize = outputIndex.length;
|
|
// Broadcast the default value to value_element_size. (We can skip this
|
|
// if defaultValueTensor.size == 1, since we use fill when that's true.)
|
|
let defaultValue = this.defaultValue;
|
|
if (defaultValue.length !== valueElementSize && defaultValue.length !== 1) {
|
|
const srcShape = this.defaultValueShape;
|
|
(0, _tfjsCore.tidy)(()=>{
|
|
const defaultValueTensor = (0, _tfjsCore.reshape)(defaultValue, srcShape);
|
|
const bCastDefault = (0, _tfjsCore.broadcastTo)(defaultValueTensor, elementShape);
|
|
defaultValue = bCastDefault.dataSync();
|
|
});
|
|
}
|
|
// Loop through the outputIndex array, finding contiguous regions that
|
|
// should be copied. Once we find the end of a contiguous region, copy it
|
|
// and add any necessary padding (with defaultValue).
|
|
let srcStart = 0; // Start of contiguous region (in values)
|
|
let dstStart = 0; // Destination for contiguous region (in output)
|
|
let dstEnd = 0; // Destination for contiguous region (in output)
|
|
for(let srcI = 0; srcI <= outputIndexSize; ++srcI){
|
|
// dstI is the destination where the value at srcI should be copied.
|
|
let dstI = srcI < outputIndexSize ? outputIndex[srcI] : -1;
|
|
// If we're still in a contiguous region, then update dstEnd go to the
|
|
// next srcI.
|
|
if (dstI === dstEnd) {
|
|
++dstEnd;
|
|
continue;
|
|
}
|
|
// We found the end of contiguous region. This can be because we found
|
|
// a gap (dstI > dstEnd), or a source value that shouldn't be copied
|
|
// because it's out-of-bounds (dstI == -1), or the end of the tensor
|
|
// (dstI === -1).
|
|
if (dstStart < dstEnd) {
|
|
// Copy the contiguous region.
|
|
const src = valuesBase.subarray(srcStart * valueElementSize);
|
|
const dst = outputBase.subarray(dstStart * valueElementSize);
|
|
const nVals = (dstEnd - dstStart) * valueElementSize;
|
|
copyArray(dst, src, nVals);
|
|
}
|
|
// Add any necessary padding (w/ defaultValue).
|
|
if (srcI >= outputIndexSize) {
|
|
// We reached the end of values: pad to the end of output.
|
|
const outputSize = outputTensor.length;
|
|
dstI = Math.floor(outputSize / valueElementSize);
|
|
}
|
|
if (dstI > dstEnd) {
|
|
if (this.defaultValue.length === 1) {
|
|
outputBase.subarray(dstEnd * valueElementSize, dstI * valueElementSize).fill(this.defaultValue[0]);
|
|
dstEnd = dstI;
|
|
} else while(dstI > dstEnd){
|
|
const dst = outputBase.slice(dstEnd * valueElementSize);
|
|
copyArray(dst, defaultValue, valueElementSize);
|
|
++dstEnd;
|
|
}
|
|
}
|
|
// Update indices.
|
|
if (dstI < 0) {
|
|
// srcI should be skipped -- leave it out of the contiguous region.
|
|
srcStart = srcI + 1;
|
|
dstStart = dstEnd;
|
|
} else {
|
|
// srcI should be copied -- include it in the contiguous region.
|
|
srcStart = srcI;
|
|
dstStart = dstEnd;
|
|
dstEnd = dstStart + 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function copyArray(dst, src, size) {
|
|
for(let i = 0; i < size; i++)dst[i] = src[i];
|
|
}
|
|
function makeShape(shape, isPartial) {
|
|
const out = [];
|
|
for (let dim of shape){
|
|
if (dim < 0) {
|
|
if (!isPartial) throw new Error(`Dimension ${dim} must be >= 0`);
|
|
if (dim < -1) throw new Error(`Dimension ${dim} must be >= -1`);
|
|
dim = -1;
|
|
}
|
|
out.push(dim);
|
|
}
|
|
return out;
|
|
}
|
|
function raggedTensorToTensorImpl(shape, shapesShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes) {
|
|
return new RaggedTensorToTensorOp(shape, shapesShape, values, valuesShape, valuesDType, defaultValue, defaultValueShape, rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes).compute();
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gJNJp":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rangeImpl", ()=>rangeImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function rangeImpl(start, stop, step, dtype) {
|
|
const sameStartStop = start === stop;
|
|
const increasingRangeNegativeStep = start < stop && step < 0;
|
|
const decreasingRangePositiveStep = stop < start && step > 1;
|
|
if (sameStartStop || increasingRangeNegativeStep || decreasingRangePositiveStep) return (0, _tfjsCore.util).makeZerosTypedArray(0, dtype);
|
|
const numElements = Math.abs(Math.ceil((stop - start) / step));
|
|
const values = (0, _tfjsCore.util).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 values;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gcVCI":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rsqrtImpl", ()=>rsqrtImpl);
|
|
parcelHelpers.export(exports, "rsqrt", ()=>rsqrt);
|
|
parcelHelpers.export(exports, "rsqrtConfig", ()=>rsqrtConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const rsqrtImpl = (0, _unaryImpl.createSimpleUnaryImpl)((xi)=>1 / Math.sqrt(xi));
|
|
const rsqrt = (0, _unaryUtils.unaryKernelFuncFromImpl)((0, _tfjsCore.Rsqrt), rsqrtImpl);
|
|
const rsqrtConfig = {
|
|
kernelName: (0, _tfjsCore.Rsqrt),
|
|
backendName: "cpu",
|
|
kernelFunc: rsqrt
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kMt6f":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "scatterImpl", ()=>scatterImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function scatterImpl(indices, updates, shape, outputSize, sliceSize, numUpdates, sliceRank, strides, defaultValue, sumDupeIndices) {
|
|
const flattenShape = [
|
|
outputSize / sliceSize,
|
|
sliceSize
|
|
];
|
|
const indicesData = indices.values;
|
|
const updatesData = updates.values;
|
|
if (outputSize === 0) return (0, _tfjsCore.buffer)(shape, updates.dtype);
|
|
const outBuf = defaultValue instanceof (0, _tfjsCore.TensorBuffer) ? defaultValue : (0, _tfjsCore.buffer)(flattenShape, updates.dtype);
|
|
if (typeof defaultValue === "string") outBuf.values.fill(defaultValue);
|
|
else if (typeof defaultValue === "number") outBuf.values.fill(defaultValue);
|
|
else if (typeof defaultValue === "boolean") outBuf.values.fill(+defaultValue);
|
|
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) outBuf.values[flattenIndex * sliceSize + k] += updatesData[i * sliceSize + k];
|
|
else outBuf.values[flattenIndex * sliceSize + k] = updates.rank === 0 ? updatesData[0] : updatesData[i * sliceSize + k];
|
|
}
|
|
return outBuf;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1a9v3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sigmoidImpl", ()=>sigmoidImpl);
|
|
parcelHelpers.export(exports, "sigmoid", ()=>sigmoid);
|
|
parcelHelpers.export(exports, "sigmoidConfig", ()=>sigmoidConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const sigmoidImpl = (0, _unaryImpl.createSimpleUnaryImpl)((xi)=>1 / (1 + Math.exp(-xi)));
|
|
const sigmoid = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Sigmoid), (xi)=>1 / (1 + Math.exp(-xi)));
|
|
const sigmoidConfig = {
|
|
kernelName: (0, _tfjsCore.Sigmoid),
|
|
backendName: "cpu",
|
|
kernelFunc: sigmoid
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9L9GN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sliceImpl", ()=>sliceImpl);
|
|
parcelHelpers.export(exports, "slice", ()=>slice);
|
|
parcelHelpers.export(exports, "sliceConfig", ()=>sliceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function sliceImpl(vals, begin, size, shape, dtype) {
|
|
const isContinous = (0, _tfjsCore.slice_util).isSliceContinous(shape, begin, size);
|
|
const length = (0, _tfjsCore.util).sizeFromShape(size);
|
|
const xStrides = (0, _tfjsCore.util).computeStrides(shape);
|
|
if (isContinous) {
|
|
const flatOffset = (0, _tfjsCore.slice_util).computeFlatOffset(begin, xStrides);
|
|
if (dtype === "string") return vals.slice(flatOffset, flatOffset + length);
|
|
return vals.subarray(flatOffset, flatOffset + length);
|
|
}
|
|
const decodedData = dtype === "string" ? (0, _tfjsCore.backend_util).fromUint8ToStringArray(vals) : vals;
|
|
const inBuf = (0, _tfjsCore.buffer)(shape, dtype, decodedData);
|
|
const outBuf = (0, _tfjsCore.buffer)(size, dtype);
|
|
for(let i = 0; i < outBuf.size; ++i){
|
|
const outLoc = outBuf.indexToLoc(i);
|
|
const inLoc = outLoc.map((idx, j)=>idx + begin[j]);
|
|
outBuf.set(inBuf.get(...inLoc), ...outLoc);
|
|
}
|
|
if (dtype === "string") return (0, _tfjsCore.backend_util).fromStringArrayToUint8(outBuf.values);
|
|
return outBuf.values;
|
|
}
|
|
function slice(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { begin, size } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "slice");
|
|
const [$begin, $size] = (0, _tfjsCore.slice_util).parseSliceParams(x, begin, size);
|
|
(0, _tfjsCore.slice_util).assertParamsValid(x, $begin, $size);
|
|
const vals = backend.data.get(x.dataId).values;
|
|
const outVals = sliceImpl(vals, $begin, $size, x.shape, x.dtype);
|
|
return backend.makeTensorInfo($size, x.dtype, outVals);
|
|
}
|
|
const sliceConfig = {
|
|
kernelName: (0, _tfjsCore.Slice),
|
|
backendName: "cpu",
|
|
kernelFunc: slice
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"72f9e":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseFillEmptyRowsImpl", ()=>sparseFillEmptyRowsImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function sparseFillEmptyRowsImpl(indices, indicesShape, indicesDType, values, valuesDType, denseShape, defaultValue) {
|
|
const indicesCount = indicesShape[0];
|
|
const denseRows = denseShape[0];
|
|
const emptyRowIndicator = new Array(denseRows);
|
|
const reverseIndexMap = new Array(indicesCount);
|
|
const rank = indicesShape[1];
|
|
if (denseRows === 0) {
|
|
if (indicesCount !== 0) throw new Error((0, _tfjsCore.backend_util).getSparseFillEmptyRowsIndicesDenseShapeMismatch(indicesCount));
|
|
const outputIndices = (0, _tfjsCore.util).getArrayFromDType(indicesDType, 0);
|
|
const outputValues = (0, _tfjsCore.util).getArrayFromDType(valuesDType, 0);
|
|
return [
|
|
outputIndices,
|
|
[
|
|
0,
|
|
rank
|
|
],
|
|
outputValues,
|
|
emptyRowIndicator,
|
|
reverseIndexMap
|
|
];
|
|
}
|
|
let rowsAreOrdered = true;
|
|
let lastIndicesRow = 0;
|
|
const csrOffset = new Array(denseRows).fill(0);
|
|
for(let i = 0; i < indicesCount; ++i){
|
|
// indices is a 2d tensor with shape of [N, rank]
|
|
const row = indices[i * rank];
|
|
if (row < 0) throw new Error((0, _tfjsCore.backend_util).getSparseFillEmptyRowsNegativeIndexErrorMessage(i, row));
|
|
if (row >= denseRows) throw new Error((0, _tfjsCore.backend_util).getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(i, row, denseRows));
|
|
++csrOffset[row];
|
|
rowsAreOrdered = rowsAreOrdered && row >= lastIndicesRow;
|
|
lastIndicesRow = row;
|
|
}
|
|
let allRowsFull = true;
|
|
for(let row = 0; row < denseRows; ++row){
|
|
// csrOffset here describes the number of elements in this dense row
|
|
const rowEmpty = csrOffset[row] === 0;
|
|
emptyRowIndicator[row] = rowEmpty;
|
|
allRowsFull = allRowsFull && !rowEmpty;
|
|
// In filled version, each row has at least one element.
|
|
csrOffset[row] = Math.max(csrOffset[row], 1);
|
|
// Update csrOffset to represent the number of elements up to and
|
|
// including denseRows + 1:
|
|
// csrOffset[0] == #{elements of row 0}
|
|
// csrOffset[1] == #{elements of row 1} + #{elements of row 0}
|
|
// ..
|
|
// csrOffset[i] == starting index for elements in row i + 1.
|
|
if (row > 0) csrOffset[row] += csrOffset[row - 1];
|
|
}
|
|
if (allRowsFull && rowsAreOrdered) {
|
|
const outputIndices = indices;
|
|
const outputValues = values;
|
|
for(let i = 0; i < indicesCount; ++i)reverseIndexMap[i] = i;
|
|
return [
|
|
outputIndices,
|
|
[
|
|
indicesCount,
|
|
rank
|
|
],
|
|
outputValues,
|
|
emptyRowIndicator,
|
|
reverseIndexMap
|
|
];
|
|
} else {
|
|
const fullIndicesCount = csrOffset[denseRows - 1];
|
|
const outputIndices = (0, _tfjsCore.util).getArrayFromDType(indicesDType, fullIndicesCount * rank);
|
|
const outputValues = (0, _tfjsCore.util).getArrayFromDType(valuesDType, fullIndicesCount);
|
|
const filledCount = new Array(denseRows).fill(0);
|
|
// Fill in values for rows that are not missing
|
|
for(let i = 0; i < indicesCount; ++i){
|
|
// indices is a 2d tensor with shape of [N, rank]
|
|
const row = indices[i * rank];
|
|
const offset = filledCount[row];
|
|
const outputI = (row === 0 ? 0 : csrOffset[row - 1]) + offset;
|
|
filledCount[row]++; // Increment the filled count for this row.
|
|
for(let j = 0; j < rank; ++j)// indices and outputIndices are 2d tensors with shape of [N, rank]
|
|
outputIndices[outputI * rank + j] = indices[i * rank + j];
|
|
outputValues[outputI] = values[i];
|
|
// We'll need this reverse index map to backprop correctly.
|
|
reverseIndexMap[i] = outputI;
|
|
}
|
|
// Fill in values for rows that are missing
|
|
for(let row = 0; row < denseRows; ++row){
|
|
const rowCount = filledCount[row];
|
|
if (rowCount === 0) {
|
|
const startingIndex = row === 0 ? 0 : csrOffset[row - 1];
|
|
// Remaining index values were set to zero already.
|
|
// Just need to set the row index in the right location.
|
|
// outputIndices is a 2d tensor with shape of [N, rank]
|
|
outputIndices[startingIndex * rank + 0] = row;
|
|
for(let col = 1; col < rank; ++col)outputIndices[startingIndex * rank + col] = 0;
|
|
outputValues[startingIndex] = defaultValue;
|
|
}
|
|
}
|
|
return [
|
|
outputIndices,
|
|
[
|
|
fullIndicesCount,
|
|
rank
|
|
],
|
|
outputValues,
|
|
emptyRowIndicator,
|
|
reverseIndexMap
|
|
];
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ecdf6":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseReshapeImpl", ()=>sparseReshapeImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function sparseReshapeImpl(inputIndices, inputIndicesShape, inputDType, inputShape, targetShape) {
|
|
const denseSize = (0, _tfjsCore.util).sizeFromShape(inputShape);
|
|
const nnz = inputIndicesShape[0];
|
|
const outputRank = targetShape.length;
|
|
// Compute the output shape. Determine product of specified dimensions, and
|
|
// find the index of the unspecified one.
|
|
const outputShape = [];
|
|
let product = 1;
|
|
let unknownIndex = -1;
|
|
for(let d = 0; d < outputRank; ++d){
|
|
const size = targetShape[d];
|
|
if (size === -1) {
|
|
if (unknownIndex !== -1) throw new Error((0, _tfjsCore.backend_util).getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(unknownIndex, d));
|
|
unknownIndex = d;
|
|
outputShape.push(1);
|
|
} else {
|
|
if (size < 0) throw new Error((0, _tfjsCore.backend_util).getSparseReshapeNegativeOutputDimErrorMessage(d, size));
|
|
product *= size;
|
|
outputShape.push(size);
|
|
}
|
|
}
|
|
if (unknownIndex !== -1) {
|
|
if (product <= 0) throw new Error((0, _tfjsCore.backend_util).getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());
|
|
const missing = Math.trunc(denseSize / product);
|
|
if (product * missing !== denseSize) throw new Error((0, _tfjsCore.backend_util).getSparseReshapeInputOutputMultipleErrorMessage(inputShape, outputShape));
|
|
outputShape[unknownIndex] = missing;
|
|
}
|
|
const outputSize = (0, _tfjsCore.util).sizeFromShape(outputShape);
|
|
if (outputSize !== denseSize) throw new Error((0, _tfjsCore.backend_util).getSparseReshapeInputOutputMismatchErrorMessage(inputShape, outputShape));
|
|
const inputRank = inputShape.length;
|
|
const inputStrides = [];
|
|
if (inputRank > 0) {
|
|
inputStrides[inputRank - 1] = 1;
|
|
for(let d = inputRank - 2; d >= 0; --d)inputStrides[d] = inputStrides[d + 1] * inputShape[d + 1];
|
|
}
|
|
const outputStrides = [];
|
|
if (outputRank > 0) {
|
|
outputStrides[outputRank - 1] = 1;
|
|
for(let d = outputRank - 2; d >= 0; --d)outputStrides[d] = outputStrides[d + 1] * outputShape[d + 1];
|
|
}
|
|
const newIndices = (0, _tfjsCore.util).getArrayFromDType(inputDType, nnz * outputRank);
|
|
for(let i = 0; i < nnz; ++i){
|
|
let id = 0;
|
|
for(let j = 0; j < inputRank; ++j)// inputIndices is a 2d tensor with shape of [nnz, inputRank]
|
|
id += inputIndices[i * inputRank + j] * inputStrides[j];
|
|
for(let j = 0; j < outputRank; ++j){
|
|
// newIndices is a 2d tensor with shape of [nnz, outputRank]
|
|
newIndices[i * outputRank + j] = Math.trunc(id / outputStrides[j]);
|
|
id %= outputStrides[j];
|
|
}
|
|
}
|
|
return [
|
|
newIndices,
|
|
[
|
|
nnz,
|
|
outputRank
|
|
],
|
|
outputShape
|
|
];
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ie2pQ":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseSegmentReductionImpl", ()=>sparseSegmentReductionImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function sparseSegmentReductionImpl(input, inputShape, inputDType, indices, segmentIds, isMean = false, defaultValue = 0) {
|
|
const numIndices = indices.length;
|
|
// Flatten the array to two dimensions
|
|
const inputFlat = [
|
|
inputShape[0],
|
|
input.length / inputShape[0]
|
|
];
|
|
const numCol = inputFlat[1];
|
|
// Note that the current implementation assumes that segmentIds values are
|
|
// sorted.
|
|
const lastSegmentIdPlusOne = numIndices > 0 ? segmentIds[numIndices - 1] + 1 : 0;
|
|
const outputRows = lastSegmentIdPlusOne;
|
|
if (outputRows < 0) throw new Error((0, _tfjsCore.backend_util).getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
|
|
const outputShape = inputShape.slice();
|
|
outputShape[0] = outputRows;
|
|
const outputLength = outputShape.reduce((product, value)=>product * value, 1);
|
|
// Output array is initialized with the value 0 by default.
|
|
const output = (0, _tfjsCore.util).getArrayFromDType(inputDType, outputLength);
|
|
// Note that we do not initialize the output buffer with a default value, so
|
|
// we need to explicitly set missing indices to the default value.
|
|
if (numIndices === 0) {
|
|
if (outputRows > 0) output.fill(defaultValue);
|
|
return [
|
|
output,
|
|
outputShape
|
|
];
|
|
}
|
|
if (outputRows <= 0) throw new Error((0, _tfjsCore.backend_util).getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
|
|
let start = 0, end = 1;
|
|
// Index from which the output is not initialized.
|
|
let uninitializedIndex = 0;
|
|
let outIndex = segmentIds[start];
|
|
while(true){
|
|
// We initialize nextIndex to 0 to avoid may be uninitialized warning
|
|
let nextIndex = 0;
|
|
if (end < numIndices) {
|
|
nextIndex = segmentIds[end];
|
|
if (outIndex === nextIndex) {
|
|
++end;
|
|
continue;
|
|
}
|
|
// We have a new segment here. Verify that the segment ids are growing.
|
|
if (outIndex >= nextIndex) throw new Error((0, _tfjsCore.backend_util).getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage());
|
|
}
|
|
if (outIndex < 0 || outIndex >= outputRows) throw new Error((0, _tfjsCore.backend_util).getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(outIndex, outputRows));
|
|
// If there is a gap between two indices, we need to set that gap to the
|
|
// default value.
|
|
if (outIndex > uninitializedIndex) output.fill(defaultValue, uninitializedIndex * numCol, outIndex * numCol);
|
|
for(let i = start; i < end; ++i){
|
|
const index = indices[i];
|
|
if (index < 0 || index >= inputFlat[0]) throw new Error((0, _tfjsCore.backend_util).getSparseSegmentReductionIndicesOutOfRangeErrorMessage(i, indices[i], inputFlat[0]));
|
|
for(let j = 0; j < numCol; j++)output[outIndex * numCol + j] += input[index * numCol + j];
|
|
}
|
|
if (isMean) for(let j = 0; j < numCol; j++)output[outIndex * numCol + j] /= end - start;
|
|
start = end;
|
|
++end;
|
|
uninitializedIndex = outIndex + 1;
|
|
outIndex = nextIndex;
|
|
if (end > numIndices) break;
|
|
}
|
|
// Fill the gap at the end with the default value.
|
|
if (uninitializedIndex < outputRows) output.fill(defaultValue, uninitializedIndex * numCol, outputRows * numCol);
|
|
return [
|
|
output,
|
|
outputShape
|
|
];
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cnnoj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sqrtImpl", ()=>sqrtImpl);
|
|
parcelHelpers.export(exports, "sqrt", ()=>sqrt);
|
|
parcelHelpers.export(exports, "sqrtConfig", ()=>sqrtConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const sqrtImpl = (0, _unaryImpl.createSimpleUnaryImpl)((xi)=>Math.sqrt(xi));
|
|
const sqrt = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Sqrt), (xi)=>Math.sqrt(xi));
|
|
const sqrtConfig = {
|
|
kernelName: (0, _tfjsCore.Sqrt),
|
|
backendName: "cpu",
|
|
kernelFunc: sqrt
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"77Ql7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "squaredDifferenceImpl", ()=>squaredDifferenceImpl);
|
|
parcelHelpers.export(exports, "squaredDifference", ()=>squaredDifference);
|
|
parcelHelpers.export(exports, "squaredDifferenceConfig", ()=>squaredDifferenceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const squaredDifferenceImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>{
|
|
const diff = a - b;
|
|
return diff * diff;
|
|
});
|
|
const squaredDifference = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.SquaredDifference), squaredDifferenceImpl);
|
|
const squaredDifferenceConfig = {
|
|
kernelName: (0, _tfjsCore.SquaredDifference),
|
|
backendName: "cpu",
|
|
kernelFunc: squaredDifference
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9G2f2":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "staticRegexReplaceImpl", ()=>staticRegexReplaceImpl);
|
|
parcelHelpers.export(exports, "staticRegexReplaceConfig", ()=>staticRegexReplaceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryImpl = require("../utils/unary_impl");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const staticRegexReplaceImpl = (0, _unaryImpl.createSimpleUnaryImpl)((x, attrs)=>{
|
|
const { pattern, replaceGlobal, rewrite } = attrs;
|
|
// TODO(mattSoulanille): Don't create a regex each time.
|
|
return x.replace(new RegExp(pattern, replaceGlobal ? "g" : ""), rewrite);
|
|
});
|
|
const staticRegexReplace = (0, _unaryUtils.unaryKernelFuncFromImpl)((0, _tfjsCore.StaticRegexReplace), staticRegexReplaceImpl);
|
|
const staticRegexReplaceConfig = {
|
|
kernelName: (0, _tfjsCore.StaticRegexReplace),
|
|
backendName: "cpu",
|
|
kernelFunc: staticRegexReplace
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_impl":"jdtAN","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kCJo9":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stridedSliceImpl", ()=>stridedSliceImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function stridedSliceImpl(outShape, xBuf, strides, begin) {
|
|
const outBuf = (0, _tfjsCore.buffer)(outShape, xBuf.dtype);
|
|
for(let i = 0; i < outBuf.size; i++){
|
|
const loc = outBuf.indexToLoc(i);
|
|
const newLoc = new Array(loc.length);
|
|
for(let j = 0; j < newLoc.length; j++)newLoc[j] = loc[j] * strides[j] + begin[j];
|
|
outBuf.set(xBuf.get(...newLoc), ...loc);
|
|
}
|
|
return outBuf;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3rAXp":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringNGramsImpl", ()=>stringNGramsImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
/**
|
|
* The StringNGramsOp class creates ngrams from ragged string data.
|
|
* The constructor contains all attributes related to the operation such as
|
|
* padding widths and strings, and the compute function can be used to
|
|
* compute the ngrams for different ragged tensor inputs.
|
|
*/ class StringNGramsOp {
|
|
constructor(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences){
|
|
this.separator = (0, _tfjsCore.util).encodeString(separator);
|
|
this.nGramWidths = nGramWidths;
|
|
this.leftPad = (0, _tfjsCore.util).encodeString(leftPad);
|
|
this.rightPad = (0, _tfjsCore.util).encodeString(rightPad);
|
|
this.padWidth = padWidth;
|
|
this.preserveShort = preserveShortSequences;
|
|
}
|
|
getPadWidth(nGramWidth) {
|
|
// Ngrams can be padded with either a fixed pad width or a dynamic pad
|
|
// width depending on the 'padWidth' arg, but in no case should the padding
|
|
// ever be wider than 'nGramWidth' - 1.
|
|
return Math.min(this.padWidth < 0 ? nGramWidth - 1 : this.padWidth, nGramWidth - 1);
|
|
}
|
|
getNumNGrams(length, nGramWidth) {
|
|
const padWidth = this.getPadWidth(nGramWidth);
|
|
return Math.max(0, length + 2 * padWidth - nGramWidth + 1);
|
|
}
|
|
createNGrams(data, splitIndex, output, outputStartIndex, numNGrams, nGramWidth) {
|
|
for(let nGramIndex = 0; nGramIndex < numNGrams; ++nGramIndex){
|
|
const padWidth = this.getPadWidth(nGramWidth);
|
|
const leftPadding = Math.max(0, padWidth - nGramIndex);
|
|
const rightPadding = Math.max(0, padWidth - (numNGrams - (nGramIndex + 1)));
|
|
const numTokens = nGramWidth - (leftPadding + rightPadding);
|
|
const dataStartIndex = splitIndex + (leftPadding > 0 ? 0 : nGramIndex - padWidth);
|
|
// Calculate the total expected size of the nGram so we can reserve the
|
|
// correct amount of space in the string.
|
|
let nGramSize = 0;
|
|
// Size of the left padding.
|
|
nGramSize += leftPadding * this.leftPad.length;
|
|
// Size of the tokens.
|
|
for(let n = 0; n < numTokens; ++n)nGramSize += data[dataStartIndex + n].length;
|
|
// Size of the right padding.
|
|
nGramSize += rightPadding * this.rightPad.length;
|
|
// Size of the separators.
|
|
const numSeparators = leftPadding + rightPadding + numTokens - 1;
|
|
nGramSize += numSeparators * this.separator.length;
|
|
// Build the nGram.
|
|
output[outputStartIndex + nGramIndex] = new Uint8Array(nGramSize);
|
|
const nGram = output[outputStartIndex + nGramIndex];
|
|
let nextNGramIndex = 0;
|
|
const appendToNGram = (str)=>str.forEach((value)=>nGram[nextNGramIndex++] = value);
|
|
for(let n = 0; n < leftPadding; ++n){
|
|
appendToNGram(this.leftPad);
|
|
appendToNGram(this.separator);
|
|
}
|
|
// Only output first numTokens - 1 pairs of data and separator
|
|
for(let n = 0; n < numTokens - 1; ++n){
|
|
appendToNGram(data[dataStartIndex + n]);
|
|
appendToNGram(this.separator);
|
|
}
|
|
// Handle case when there are no tokens or no right padding as these
|
|
// can result in consecutive separators.
|
|
if (numTokens > 0) {
|
|
// If we have tokens, then output last and then pair each separator
|
|
// with the right padding that follows, to ensure nGram ends either with
|
|
// the token or with the right pad.
|
|
appendToNGram(data[dataStartIndex + numTokens - 1]);
|
|
for(let n = 0; n < rightPadding; ++n){
|
|
appendToNGram(this.separator);
|
|
appendToNGram(this.rightPad);
|
|
}
|
|
} else {
|
|
// If we don't have tokens, then the last item inserted into the nGram
|
|
// has been the separator from the left padding loop above. Hence,
|
|
// output right pad and separator and make sure to finish with a
|
|
// padding, not a separator.
|
|
for(let n = 0; n < rightPadding - 1; ++n){
|
|
appendToNGram(this.rightPad);
|
|
appendToNGram(this.separator);
|
|
}
|
|
appendToNGram(this.rightPad);
|
|
}
|
|
}
|
|
}
|
|
// Data and splits together form the definition of the ragged tensor,
|
|
// where data is 1 dimensional and contains the values of the tensor
|
|
// and splits denotes the indices at which each row starts.
|
|
compute(data, splits) {
|
|
// Validate that the splits are valid indices into data, only if there are
|
|
// splits specified.
|
|
const inputDataSize = data.length;
|
|
const splitsSize = splits.length;
|
|
if (splitsSize > 0) {
|
|
let prevSplit = splits[0];
|
|
if (prevSplit !== 0) throw new Error(`First split value must be 0, got ${prevSplit}`);
|
|
for(let i = 1; i < splitsSize; ++i){
|
|
let validSplits = splits[i] >= prevSplit;
|
|
validSplits = validSplits && splits[i] <= inputDataSize;
|
|
if (!validSplits) throw new Error(`Invalid split value ${splits[i]}, must be in [${prevSplit}, ${inputDataSize}]`);
|
|
prevSplit = splits[i];
|
|
}
|
|
if (prevSplit !== inputDataSize) throw new Error(`Last split value must be data size. Expected ${inputDataSize}, got ${prevSplit}`);
|
|
}
|
|
const numBatchItems = splitsSize - 1;
|
|
const nGramsSplits = (0, _tfjsCore.util).getArrayFromDType("int32", splitsSize);
|
|
// If there is no data or size, return an empty ragged tensor.
|
|
if (inputDataSize === 0 || splitsSize === 0) {
|
|
const empty = new Array(inputDataSize);
|
|
for(let i = 0; i <= numBatchItems; ++i)nGramsSplits[i] = 0;
|
|
return [
|
|
empty,
|
|
nGramsSplits
|
|
];
|
|
}
|
|
nGramsSplits[0] = 0;
|
|
for(let i = 1; i <= numBatchItems; ++i){
|
|
const length = splits[i] - splits[i - 1];
|
|
let numNGrams = 0;
|
|
this.nGramWidths.forEach((nGramWidth)=>{
|
|
numNGrams += this.getNumNGrams(length, nGramWidth);
|
|
});
|
|
if (this.preserveShort && length > 0 && numNGrams === 0) numNGrams = 1;
|
|
nGramsSplits[i] = nGramsSplits[i - 1] + numNGrams;
|
|
}
|
|
const nGrams = new Array(nGramsSplits[numBatchItems]);
|
|
for(let i = 0; i < numBatchItems; ++i){
|
|
const splitIndex = splits[i];
|
|
let outputStartIdx = nGramsSplits[i];
|
|
this.nGramWidths.forEach((nGramWidth)=>{
|
|
const length = splits[i + 1] - splits[i];
|
|
const numNGrams = this.getNumNGrams(length, nGramWidth);
|
|
this.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);
|
|
outputStartIdx += numNGrams;
|
|
});
|
|
// If we're preserving short sequences, check to see if no sequence was
|
|
// generated by comparing the current output start idx to the original
|
|
// one (nGramSplitsdata). If no ngrams were generated, then they will
|
|
// be equal (since we increment outputStartIdx by numNGrams every
|
|
// time we create a set of ngrams.)
|
|
if (this.preserveShort && outputStartIdx === nGramsSplits[i]) {
|
|
const dataLength = splits[i + 1] - splits[i];
|
|
// One legitimate reason to not have any ngrams when this.preserveShort
|
|
// is true is if the sequence itself is empty. In that case, move on.
|
|
if (dataLength === 0) continue;
|
|
// We don't have to worry about dynamic padding sizes here: if padding
|
|
// was dynamic, every sequence would have had sufficient padding to
|
|
// generate at least one nGram.
|
|
const nGramWidth = dataLength + 2 * this.padWidth;
|
|
const numNGrams = 1;
|
|
this.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);
|
|
}
|
|
}
|
|
return [
|
|
nGrams,
|
|
nGramsSplits
|
|
];
|
|
}
|
|
}
|
|
function stringNGramsImpl(data, dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
|
|
return new StringNGramsOp(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences).compute(data, dataSplits);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8xmpZ":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringSplitImpl", ()=>stringSplitImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function split(str, delimiters, skipEmpty, result) {
|
|
if (!str.length) return;
|
|
// When the delimiter is empty, the input is split into individual characters.
|
|
if (delimiters.length === 0) {
|
|
for(let i = 0; i < str.length; ++i)result.push(str.subarray(i, i + 1));
|
|
return;
|
|
}
|
|
// When there is one delimiter, the input is split only at that delimiter.
|
|
if (delimiters.length === 1) {
|
|
const delimiter = delimiters[0];
|
|
let f = str.indexOf(delimiter);
|
|
while(f !== -1){
|
|
const token = str.subarray(0, f);
|
|
if (!skipEmpty || token.length !== 0) result.push(token);
|
|
str = str.subarray(f + 1);
|
|
f = str.indexOf(delimiter);
|
|
}
|
|
if (!skipEmpty || str.length !== 0) result.push(str);
|
|
return;
|
|
}
|
|
// When there are multiple delimiters, the input is split at every instance
|
|
// one of the delimiters appears.
|
|
let tokenStart = 0;
|
|
for(let i = 0; i < str.length + 1; i++)if (i === str.length || delimiters.indexOf(str[i]) !== -1) {
|
|
const token = str.subarray(tokenStart, i);
|
|
if (!skipEmpty || token.length !== 0) result.push(token);
|
|
tokenStart = i + 1;
|
|
}
|
|
}
|
|
function stringSplitImpl(input, delimiter, skipEmpty) {
|
|
const batchSize = input.length;
|
|
// Empty delimiter means split the input character by character.
|
|
const tokens = [];
|
|
let outputSize = 0;
|
|
let maxNumEntries = 0;
|
|
const numIndices = new Array(batchSize);
|
|
for(let i = 0; i < batchSize; ++i){
|
|
const prevTokensLength = tokens.length;
|
|
split(input[i], delimiter, skipEmpty, tokens);
|
|
const nEntries = tokens.length - prevTokensLength;
|
|
numIndices[i] = nEntries;
|
|
outputSize += nEntries;
|
|
maxNumEntries = Math.max(maxNumEntries, nEntries);
|
|
}
|
|
const indices = (0, _tfjsCore.util).getArrayFromDType("int32", outputSize * 2);
|
|
const values = new Array(outputSize);
|
|
const shape = [
|
|
batchSize,
|
|
maxNumEntries
|
|
];
|
|
let c = 0;
|
|
for(let i = 0; i < batchSize; ++i)for(let j = 0; j < numIndices[i]; ++j){
|
|
// indices is a 2d tensor with shape of [outputSize, 2]
|
|
indices[c * 2] = i;
|
|
indices[c * 2 + 1] = j;
|
|
values[c] = tokens[c];
|
|
++c;
|
|
}
|
|
return [
|
|
indices,
|
|
values,
|
|
shape
|
|
];
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6jwLv":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringToHashBucketFastImpl", ()=>stringToHashBucketFastImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function stringToHashBucketFastImpl(input, numBuckets) {
|
|
const output = (0, _tfjsCore.util).getArrayFromDType("int32", input.length);
|
|
for(let i = 0; i < input.length; ++i)output[i] = (0, _tfjsCore.util).fingerPrint64(input[i]).modulo(numBuckets).getLowBitsUnsigned();
|
|
return output;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4DByI":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "subImpl", ()=>subImpl);
|
|
parcelHelpers.export(exports, "subComplexImpl", ()=>subComplexImpl);
|
|
parcelHelpers.export(exports, "sub", ()=>sub);
|
|
parcelHelpers.export(exports, "subConfig", ()=>subConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const subImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((aValue, bValue)=>aValue - bValue);
|
|
const subComplexImpl = (0, _binaryUtils.createComplexBinaryKernelImpl)((aReal, aImag, bReal, bImag)=>{
|
|
return {
|
|
real: aReal - bReal,
|
|
imag: aImag - bImag
|
|
};
|
|
});
|
|
const sub = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Sub), subImpl, subComplexImpl);
|
|
const subConfig = {
|
|
kernelName: (0, _tfjsCore.Sub),
|
|
backendName: "cpu",
|
|
kernelFunc: sub
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7g2re":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* An implementation of the tile kernel shared between webgl and cpu for string
|
|
* tensors only.
|
|
*/ parcelHelpers.export(exports, "tileImpl", ()=>tileImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function tileImpl(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 = (0, _tfjsCore.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;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dl1sf":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ /** An implementation of the TopK kernel shared between webgl and cpu. */ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "topKImpl", ()=>topKImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const comparePair = (a, b)=>{
|
|
const valueDiff = b.value - a.value;
|
|
return valueDiff === 0 ? a.index - b.index : valueDiff;
|
|
};
|
|
/**
|
|
* Partitions array where all elements smaller than the (k+1) smallest element
|
|
* are found to the left of it, and all larger to the right of it.
|
|
* Based on the Floyd-Rivest Algorithm, ref:
|
|
* https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm
|
|
* @param array: Array to partition
|
|
* @param left: Left index for the interval
|
|
* @param right: Right index for the interval
|
|
* @param k: Desired index value, where array[k] is the (k+1)th smallest element
|
|
* when left = 0
|
|
*/ function select(array, k, left = 0, right = array.length - 1) {
|
|
while(right > left){
|
|
// Use select recursively to sample a smaller set of size s
|
|
// the arbitrary constants 600 and 0.5 are used in the original
|
|
// version to minimize execution time.
|
|
if (right - left > 600) {
|
|
const n = right - left + 1;
|
|
const i = k - left + 1;
|
|
const z = Math.log(n);
|
|
const s = 0.5 * Math.exp(2 * z / 3);
|
|
const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * Math.sign(i - n / 2);
|
|
const newLeft = Math.max(left, Math.floor(k - i * s / n + sd));
|
|
const newRight = Math.min(right, Math.floor(k + (n - i) * s / n + sd));
|
|
select(array, k, newLeft, newRight);
|
|
}
|
|
// partition the elements between left and right around t
|
|
const t = array[k];
|
|
let i = left;
|
|
let j = right;
|
|
(0, _tfjsCore.util).swap(array, left, k);
|
|
if (comparePair(array[right], t) > 0) (0, _tfjsCore.util).swap(array, left, right);
|
|
while(i < j){
|
|
(0, _tfjsCore.util).swap(array, i, j);
|
|
i++;
|
|
j--;
|
|
while(comparePair(array[i], t) < 0)i = i + 1;
|
|
while(comparePair(array[j], t) > 0)j = j - 1;
|
|
}
|
|
if (comparePair(array[left], t) === 0) (0, _tfjsCore.util).swap(array, left, j);
|
|
else {
|
|
j = j + 1;
|
|
(0, _tfjsCore.util).swap(array, j, right);
|
|
}
|
|
// Adjust left and right towards the boundaries of the subset
|
|
// containing the (k - left + 1)th smallest element.
|
|
if (j <= k) left = j + 1;
|
|
if (k <= j) right = j - 1;
|
|
}
|
|
}
|
|
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 = (0, _tfjsCore.util).getTypedArrayFromDType(xDtype, batch * k);
|
|
const allTopKIndices = (0, _tfjsCore.util).getTypedArrayFromDType("int32", batch * k);
|
|
for(let b = 0; b < batch; b++){
|
|
const offset = b * size;
|
|
const vals = x.subarray(offset, offset + size);
|
|
let valAndInd = new Array(vals.length);
|
|
vals.forEach((value, index)=>valAndInd[index] = {
|
|
value,
|
|
index
|
|
});
|
|
if (k < valAndInd.length) {
|
|
select(valAndInd, k);
|
|
valAndInd = valAndInd.slice(0, k);
|
|
}
|
|
if (sorted) valAndInd.sort(comparePair);
|
|
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 [
|
|
(0, _tfjsCore.buffer)(outputShape, xDtype, allTopKVals),
|
|
(0, _tfjsCore.buffer)(outputShape, "int32", allTopKIndices)
|
|
];
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gLexL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "uniqueImpl", ()=>uniqueImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function uniqueImpl(values, axis, shape, dtype) {
|
|
// Normalize and validate axis.
|
|
const $axis = (0, _tfjsCore.util).parseAxisParam(axis, shape)[0];
|
|
// Calculate the new shape that is suitable for extracting data along the
|
|
// given axis.
|
|
//
|
|
// The rank is 3.
|
|
// The size of the 1st dimension is the size of all the axes < the given axis.
|
|
// The size of the 2nd dimension is the same as the size of the given axis.
|
|
// The size of the 3rd dimension is the size of all the axes > the given axis.
|
|
//
|
|
// For example, for a 4D tensor with shape=[2, 3, 5, 4] and axis=2, the
|
|
// newShape would be: [2*3, 5, 4].
|
|
//
|
|
// Note that this is not the final output shape. This will be the shape for an
|
|
// intermediate TensorBuffer (see inputBuffer below) to allow us to extract
|
|
// values along the given axis. To demonstrate how it works, consider the
|
|
// following example:
|
|
//
|
|
// Input: a 3D tensor, with shape [1, 2, 3]
|
|
// [
|
|
// [
|
|
// [1,2,3],
|
|
// [4,5,6]
|
|
// ]
|
|
// ]
|
|
// Axis: 2 (the last axis).
|
|
// Along axis 2, we expect to extract 3 tensors: [1,4], [2,5], [3,6].
|
|
//
|
|
// For this example, newShape would be: [2, 3, 1], where 2 is calculated from
|
|
// 1*2. The re-shaped data would look like:
|
|
//
|
|
// [
|
|
// [
|
|
// [1], [2], [3]
|
|
// ],
|
|
// [
|
|
// [4], [5], [6]
|
|
// ]
|
|
// ]
|
|
//
|
|
// Then, we can construct a 3-level nested loop by the following dimension
|
|
// order to extract the values along the axis (dimension1):
|
|
// i: dimension1 // 0,1,2 (newShape[1])
|
|
// m: dimension0 // 0,1 (newShape[0])
|
|
// n: dimension2 // 0 (newShape[2])
|
|
//
|
|
// m, i, n
|
|
// ---------
|
|
// Iteration 0: data at [0, 0, 0] => "1"
|
|
// Iteration 1: data at [1, 0, 0] => "4"
|
|
// We got [1,4].
|
|
// Iteration 2: data at [0, 1, 0] => "2"
|
|
// Iteration 3: data at [1, 1, 0] => "5"
|
|
// We got [2,5].
|
|
// Iteration 4: data at [0, 2, 0] => "3"
|
|
// Iteration 5: data at [1, 2, 0] => "6"
|
|
// We got [3,6].
|
|
const newShape = [
|
|
1,
|
|
shape[0],
|
|
1
|
|
];
|
|
for(let i = 0; i < $axis; i++)newShape[0] *= shape[i];
|
|
newShape[1] = shape[$axis];
|
|
for(let i = $axis + 1; i < shape.length; i++)newShape[2] *= shape[i];
|
|
// A map from unique elements (their string representations) to their values
|
|
// in "indices" (below).
|
|
const uniqueElements = new Map();
|
|
// The indices of each unique element in the original tensor along the given
|
|
// axis. It is 1D and has the same size as the given axis.
|
|
const indices = new Int32Array(shape[$axis]);
|
|
// Create a buffer so we can easily extract value at a given location.
|
|
const inputBuffer = new (0, _tfjsCore.TensorBuffer)(newShape, dtype, values);
|
|
// The indices along the given axis that have unique elements. This is a
|
|
// de-duped version of "indices" above.
|
|
const uniqueIndices = [];
|
|
const is1DTensor = newShape[0] === 1 && newShape[2] === 1;
|
|
for(let i = 0; i < shape[$axis]; i++){
|
|
// Extract values along the axis.
|
|
let element;
|
|
if (is1DTensor) // Fast path for 1D tensor input.
|
|
element = values[i].toString();
|
|
else {
|
|
const axisValues = [];
|
|
for(let m = 0; m < newShape[0]; m++)for(let n = 0; n < newShape[2]; n++)axisValues.push(inputBuffer.get(m, i, n));
|
|
element = axisValues.join(",");
|
|
}
|
|
// Dedup and update various indices.
|
|
const existingIndex = uniqueElements.get(element);
|
|
if (existingIndex != null) indices[i] = existingIndex;
|
|
else {
|
|
const uniqueIndex = uniqueElements.size;
|
|
uniqueElements.set(element, uniqueIndex);
|
|
indices[i] = uniqueIndex;
|
|
uniqueIndices.push(i);
|
|
}
|
|
}
|
|
// Now we know where each of the unique elements are located along the axis
|
|
// (uniqueIndices). Extract them from input buffer and store them in the
|
|
// output buffer.
|
|
const outputTmpShape = newShape.slice();
|
|
outputTmpShape[1] = uniqueElements.size;
|
|
const outputBuffer = new (0, _tfjsCore.TensorBuffer)(outputTmpShape, dtype);
|
|
uniqueIndices.forEach((uniqueElementIndex, i)=>{
|
|
for(let m = 0; m < newShape[0]; m++)for(let n = 0; n < newShape[2]; n++)outputBuffer.set(inputBuffer.get(m, uniqueElementIndex, n), m, i, n);
|
|
});
|
|
// The output shape can be calculated from the input shape with the size of
|
|
// the given axis replaced by the number of unique elements along that axis.
|
|
const outputShape = shape.slice();
|
|
outputShape[$axis] = outputTmpShape[1];
|
|
return {
|
|
outputValues: outputBuffer.values,
|
|
outputShape,
|
|
indices
|
|
};
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1FCRm":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "PackProgram", ()=>PackProgram);
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class PackProgram {
|
|
constructor(outputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = false;
|
|
this.packedOutput = true;
|
|
// Only input / output 3D tensors.
|
|
this.outputShape = outputShape;
|
|
this.rank = outputShape.length;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
if (this.rank === 0) this.userCode = `
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;
|
|
else {
|
|
const channels = (0, _packingUtil.getChannels)("rc", this.rank);
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(this.rank);
|
|
const outOfBoundsCondition = this.getOutOfBoundsCondition(channels);
|
|
const setup = this.getSetup(channels);
|
|
const output = this.getOutput(channels);
|
|
this.userCode = `
|
|
void main() {
|
|
${dtype} rc = getOutputCoords();
|
|
|
|
if(${outOfBoundsCondition}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${setup}
|
|
|
|
setOutput(vec4(${output}));
|
|
}
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
getSourceCoordsArr(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 < this.rank; d++)coord = `${dims[dims.length - 1 - d]},` + coord;
|
|
coords.push(coord);
|
|
}
|
|
return coords;
|
|
}
|
|
getOutOfBoundsCondition(dims) {
|
|
if (this.rank === 1) return `rc > ${this.enableShapeUniforms ? "outShape" : this.outputShape[0]}`;
|
|
let cond = "";
|
|
for(let i = this.rank - 2; i < this.rank; i++){
|
|
cond += `${dims[i]} >= ${this.enableShapeUniforms ? `outShape[${i}]` : this.outputShape[i]}`;
|
|
if (i < this.rank - 1) cond += "||";
|
|
}
|
|
return cond;
|
|
}
|
|
getSetup(dims) {
|
|
if (this.rank === 1) return "";
|
|
const innerDims = dims.slice(-2);
|
|
const col = this.enableShapeUniforms ? `outShape[${this.rank} - 1]` : this.outputShape[this.rank - 1];
|
|
const row = this.enableShapeUniforms ? `outShape[${this.rank} - 2]` : this.outputShape[this.rank - 2];
|
|
return `
|
|
int r = ${innerDims[0]};
|
|
int c = ${innerDims[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${col};
|
|
bool rEdge = rp1 >= ${row};
|
|
`;
|
|
}
|
|
getOutput(dims) {
|
|
const sourceCoords = this.getSourceCoordsArr(dims);
|
|
if (this.rank === 1) {
|
|
const outShape = this.enableShapeUniforms ? "outShape" : this.outputShape[0];
|
|
return `getA(rc), (rc + 1 >= ${outShape} ? 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]})`;
|
|
}
|
|
}
|
|
|
|
},{"./gpgpu_math":"btJo5","./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5ylpz":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getVecChannels", ()=>getVecChannels);
|
|
parcelHelpers.export(exports, "getChannels", ()=>getChannels);
|
|
parcelHelpers.export(exports, "getSourceCoords", ()=>getSourceCoords);
|
|
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;
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6lTtb":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ReshapePackedProgram", ()=>ReshapePackedProgram);
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _shaderCompilerUtil = require("./shader_compiler_util");
|
|
class ReshapePackedProgram {
|
|
constructor(outputShape, inputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.customUniforms = [
|
|
{
|
|
name: "inputShape",
|
|
type: "ivec3"
|
|
}
|
|
];
|
|
this.outputShape = outputShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
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, this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms ? _shaderCompilerUtil.getFlatIndexFrom3DOutput() : _shaderCompilerUtil.getFlatIndexFrom3D(outputShape)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${this.enableShapeUniforms ? "outShape[1]" : outputShape[1]};
|
|
int cols = ${this.enableShapeUniforms ? "outShape[2]" : outputShape[2]};
|
|
|
|
${mainLoop}
|
|
|
|
setOutput(result);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
function getReshapedInputCoords(shape, enableShapeUniforms) {
|
|
const coordsFromIndexSnippet = enableShapeUniforms ? _shaderCompilerUtil.getLogicalCoordinatesFromFlatIndexByUniform([
|
|
"r",
|
|
"c",
|
|
"d"
|
|
], "inputShape") : _shaderCompilerUtil.getLogicalCoordinatesFromFlatIndex([
|
|
"r",
|
|
"c",
|
|
"d"
|
|
], shape);
|
|
return `
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${coordsFromIndexSnippet}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;
|
|
}
|
|
|
|
},{"./gpgpu_math":"btJo5","./shader_compiler_util":"4ROqF","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"72VRa":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "TextureManager", ()=>TextureManager);
|
|
parcelHelpers.export(exports, "computeBytes", ()=>computeBytes);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gpgpuUtil = require("./gpgpu_util");
|
|
var _texUtil = require("./tex_util");
|
|
class TextureManager {
|
|
constructor(gpgpu){
|
|
this.gpgpu = gpgpu;
|
|
this.numUsedTextures = 0;
|
|
this.numFreeTextures = 0;
|
|
this._numBytesAllocated = 0;
|
|
// Number of bytes that have been allocated and available for reuse.
|
|
this._numBytesFree = 0;
|
|
this.freeTextures = {};
|
|
this.usedTextures = {};
|
|
this.logEnabled = false;
|
|
}
|
|
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] = [];
|
|
const texBytes = computeBytes(shapeRC, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig, isPacked);
|
|
if (this.freeTextures[shapeKey].length > 0) {
|
|
this.numFreeTextures--;
|
|
this.numUsedTextures++;
|
|
this._numBytesFree -= texBytes;
|
|
this.log();
|
|
const newTexture = this.freeTextures[shapeKey].pop();
|
|
this.usedTextures[shapeKey].push(newTexture);
|
|
return newTexture;
|
|
}
|
|
let newTexture;
|
|
if (physicalTexType === (0, _texUtil.PhysicalTextureType).PACKED_2X2_FLOAT32) newTexture = this.gpgpu.createPackedMatrixTexture(shapeRC[0], shapeRC[1]);
|
|
else if (physicalTexType === (0, _texUtil.PhysicalTextureType).PACKED_2X2_FLOAT16) newTexture = this.gpgpu.createFloat16PackedMatrixTexture(shapeRC[0], shapeRC[1]);
|
|
else if (physicalTexType === (0, _texUtil.PhysicalTextureType).UNPACKED_FLOAT32) newTexture = this.gpgpu.createFloat32MatrixTexture(shapeRC[0], shapeRC[1]);
|
|
else if (physicalTexType === (0, _texUtil.PhysicalTextureType).UNPACKED_FLOAT16) newTexture = this.gpgpu.createFloat16MatrixTexture(shapeRC[0], shapeRC[1]);
|
|
else if (physicalTexType === (0, _texUtil.PhysicalTextureType).PACKED_4X1_UNSIGNED_BYTE) newTexture = this.gpgpu.createUnsignedBytesMatrixTexture(shapeRC[0], shapeRC[1]);
|
|
this.usedTextures[shapeKey].push(newTexture);
|
|
this.numUsedTextures++;
|
|
this._numBytesAllocated += texBytes;
|
|
this.log();
|
|
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] = [];
|
|
const texBytes = computeBytes(shape, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig, isPacked);
|
|
const deleteTexThreshold = (0, _tfjsCore.env)().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");
|
|
if (deleteTexThreshold !== -1 && this._numBytesAllocated > deleteTexThreshold) {
|
|
this.gpgpu.deleteMatrixTexture(texture.texture);
|
|
this._numBytesAllocated -= texBytes;
|
|
} else {
|
|
this.freeTextures[shapeKey].push(texture);
|
|
this.numFreeTextures++;
|
|
this._numBytesFree += texBytes;
|
|
}
|
|
this.numUsedTextures--;
|
|
const texList = this.usedTextures[shapeKey];
|
|
const texIndex = texList && texList.indexOf(texture);
|
|
if (texIndex == null || texIndex < 0) throw new Error("Cannot release a texture that was never provided by this texture manager");
|
|
texList[texIndex] = texList[texList.length - 1];
|
|
texList.pop();
|
|
this.log();
|
|
}
|
|
log() {
|
|
if (!this.logEnabled) return;
|
|
const total = this.numFreeTextures + this.numUsedTextures;
|
|
console.log("Free/Used", `${this.numFreeTextures} / ${this.numUsedTextures}`, `(${total})`);
|
|
const freeRatio = this._numBytesFree / this._numBytesAllocated;
|
|
console.log(`Bytes allocated: ${this._numBytesAllocated}`);
|
|
console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100 * freeRatio)}%)`);
|
|
}
|
|
get numBytesAllocated() {
|
|
return this._numBytesAllocated;
|
|
}
|
|
get numBytesFree() {
|
|
return this._numBytesFree;
|
|
}
|
|
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.texture);
|
|
});
|
|
for(const texShape in this.usedTextures)this.usedTextures[texShape].forEach((tex)=>{
|
|
this.gpgpu.deleteMatrixTexture(tex.texture);
|
|
});
|
|
// TODO: Assign non-null value (empty object) to textures after disposed.
|
|
this.freeTextures = null;
|
|
this.usedTextures = null;
|
|
this.numUsedTextures = 0;
|
|
this.numFreeTextures = 0;
|
|
this._numBytesAllocated = 0;
|
|
this._numBytesFree = 0;
|
|
}
|
|
}
|
|
function numBytesForInternalFormat(gl, internalFormat) {
|
|
// tslint:disable-next-line:no-any
|
|
const glany = gl;
|
|
if (internalFormat === glany.R32F) return 4;
|
|
else if (internalFormat === glany.R16F) return 2;
|
|
else if (internalFormat === glany.RGBA32F) return 16;
|
|
else if (internalFormat === gl.RGBA) return 16;
|
|
else if (internalFormat === glany.RGBA16F) return 8;
|
|
else if (internalFormat === glany.RGBA8) return 4;
|
|
throw new Error(`Unknown internal format ${internalFormat}`);
|
|
}
|
|
function computeBytes(shape, physicalTexType, gl, textureConfig, isPacked) {
|
|
// It is not possible to infer packed status from the texture type because
|
|
// depending on the textureConfig, different texture types may resolve to the
|
|
// same internal format (e.g. in WebGL1, the internal format for
|
|
// UNPACKED_FLOAT16 textures is gl.RGBA). Therefore we pass in `isPacked`
|
|
// explicitly.
|
|
const internalFormat = internalFormatForPhysicalTexType(physicalTexType, textureConfig);
|
|
let numElements;
|
|
if (isPacked) {
|
|
const [packedWidth, packedHeight] = (0, _texUtil.getPackedMatrixTextureShapeWidthHeight)(shape[0], shape[1]);
|
|
numElements = packedWidth * packedHeight;
|
|
} else {
|
|
const [width, height] = (0, _texUtil.getUnpackedMatrixTextureShapeWidthHeight)(shape[0], shape[1]);
|
|
numElements = width * height;
|
|
}
|
|
const bytesPerElement = numBytesForInternalFormat(gl, internalFormat);
|
|
return numElements * bytesPerElement;
|
|
}
|
|
function internalFormatForPhysicalTexType(physicalTexType, textureConfig) {
|
|
switch(physicalTexType){
|
|
case (0, _texUtil.PhysicalTextureType).PACKED_2X2_FLOAT32:
|
|
return (0, _gpgpuUtil.getInternalFormatForPackedMatrixTexture)(textureConfig);
|
|
case (0, _texUtil.PhysicalTextureType).PACKED_2X2_FLOAT16:
|
|
return (0, _gpgpuUtil.getInternalFormatForFloat16PackedMatrixTexture)(textureConfig);
|
|
case (0, _texUtil.PhysicalTextureType).UNPACKED_FLOAT32:
|
|
return (0, _gpgpuUtil.getInternalFormatForFloat32MatrixTexture)(textureConfig);
|
|
case (0, _texUtil.PhysicalTextureType).UNPACKED_FLOAT16:
|
|
return (0, _gpgpuUtil.getInternalFormatForFloat16MatrixTexture)(textureConfig);
|
|
case (0, _texUtil.PhysicalTextureType).PACKED_4X1_UNSIGNED_BYTE:
|
|
return (0, _gpgpuUtil.getInternalFormatForUnsignedBytesMatrixTexture)(textureConfig);
|
|
default:
|
|
throw new Error(`Unknown physical texture type ${physicalTexType}`);
|
|
}
|
|
}
|
|
function getPhysicalTextureForRendering(isPacked) {
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_RENDER_FLOAT32_ENABLED")) {
|
|
if (isPacked) return (0, _texUtil.PhysicalTextureType).PACKED_2X2_FLOAT32;
|
|
return (0, _texUtil.PhysicalTextureType).UNPACKED_FLOAT32;
|
|
}
|
|
if (isPacked) return (0, _texUtil.PhysicalTextureType).PACKED_2X2_FLOAT16;
|
|
return (0, _texUtil.PhysicalTextureType).UNPACKED_FLOAT16;
|
|
}
|
|
function getPhysicalFromLogicalTextureType(logicalTexType, isPacked) {
|
|
if (logicalTexType === (0, _texUtil.TextureUsage).UPLOAD) return (0, _texUtil.PhysicalTextureType).PACKED_2X2_FLOAT32;
|
|
else if (logicalTexType === (0, _texUtil.TextureUsage).RENDER || logicalTexType == null) return getPhysicalTextureForRendering(isPacked);
|
|
else if (logicalTexType === (0, _texUtil.TextureUsage).DOWNLOAD || logicalTexType === (0, _texUtil.TextureUsage).PIXELS) return (0, _texUtil.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}`;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./gpgpu_util":"ezSrp","./tex_util":"1oYRe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gIMrR":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "UnaryOpProgram", ()=>UnaryOpProgram);
|
|
parcelHelpers.export(exports, "CHECK_NAN_SNIPPET", ()=>CHECK_NAN_SNIPPET);
|
|
parcelHelpers.export(exports, "LINEAR", ()=>LINEAR);
|
|
parcelHelpers.export(exports, "ABS", ()=>ABS);
|
|
parcelHelpers.export(exports, "STEP", ()=>STEP);
|
|
parcelHelpers.export(exports, "ELU", ()=>ELU);
|
|
parcelHelpers.export(exports, "RELU", ()=>RELU);
|
|
parcelHelpers.export(exports, "RELU6", ()=>RELU6);
|
|
parcelHelpers.export(exports, "CLONE", ()=>CLONE);
|
|
parcelHelpers.export(exports, "SIGMOID", ()=>SIGMOID);
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
class UnaryOpProgram {
|
|
constructor(aShape, opSnippet){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.outputShape = aShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
this.userCode = `
|
|
float unaryOperation(float x) {
|
|
${opSnippet}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
const CHECK_NAN_SNIPPET = `if (isnan(x)) return x;`;
|
|
const LINEAR = `return x;`;
|
|
const ABS = `return abs(x);`;
|
|
function STEP(alpha = 0.0) {
|
|
return CHECK_NAN_SNIPPET + `
|
|
return x > 0.0 ? 1.0 : float(${alpha});
|
|
`;
|
|
}
|
|
const ELU = `return (x >= 0.0) ? x : (exp(x) - 1.0);`;
|
|
const RELU = CHECK_NAN_SNIPPET + `
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`;
|
|
const RELU6 = CHECK_NAN_SNIPPET + `
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`;
|
|
const CLONE = "return x;";
|
|
const SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;
|
|
|
|
},{"./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c4D5K":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "LINEAR", ()=>LINEAR);
|
|
parcelHelpers.export(exports, "ELU", ()=>ELU);
|
|
parcelHelpers.export(exports, "RELU", ()=>RELU);
|
|
parcelHelpers.export(exports, "RELU6", ()=>RELU6);
|
|
parcelHelpers.export(exports, "SIGMOID", ()=>SIGMOID);
|
|
parcelHelpers.export(exports, "UnaryOpPackedProgram", ()=>UnaryOpPackedProgram);
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
const LINEAR = `return x;`;
|
|
const 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;
|
|
`;
|
|
const 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 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 SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;
|
|
class UnaryOpPackedProgram {
|
|
constructor(aShape, opSnippet){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.outputShape = aShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
this.userCode = `
|
|
vec4 unaryOperation(vec4 x) {
|
|
${opSnippet}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6fxgJ":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "UnpackProgram", ()=>UnpackProgram);
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class UnpackProgram {
|
|
constructor(outputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = false;
|
|
this.outputShape = outputShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
const rank = outputShape.length;
|
|
const channels = (0, _packingUtil.getChannels)("rc", rank);
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(rank);
|
|
const sourceCoords = (0, _packingUtil.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}));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./gpgpu_math":"btJo5","./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8XYZf":[function(require,module,exports) {
|
|
/** @license See the LICENSE file. */ // This code is auto-generated, do not modify this file!
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "version", ()=>version);
|
|
const version = "4.21.0";
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"l4jNp":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MathBackendWebGL", ()=>(0, _backendWebgl.MathBackendWebGL));
|
|
parcelHelpers.export(exports, "setWebGLContext", ()=>(0, _canvasUtil.setWebGLContext));
|
|
parcelHelpers.export(exports, "GPGPUContext", ()=>(0, _gpgpuContext.GPGPUContext));
|
|
// WebGL specific utils.
|
|
parcelHelpers.export(exports, "gpgpu_util", ()=>_gpgpuUtil);
|
|
parcelHelpers.export(exports, "webgl_util", ()=>_webglUtil);
|
|
/**
|
|
* Enforce use of half precision textures if available on the platform.
|
|
*
|
|
* @doc {heading: 'Environment', namespace: 'webgl'}
|
|
*/ parcelHelpers.export(exports, "forceHalfFloat", ()=>forceHalfFloat);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gpgpuUtil = require("./gpgpu_util");
|
|
var _webglUtil = require("./webgl_util");
|
|
var _backendWebgl = require("./backend_webgl");
|
|
var _canvasUtil = require("./canvas_util");
|
|
var _gpgpuContext = require("./gpgpu_context");
|
|
function forceHalfFloat() {
|
|
(0, _tfjsCore.env)().set("WEBGL_FORCE_F16_TEXTURES", true);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./gpgpu_util":"ezSrp","./webgl_util":"fjf7t","./backend_webgl":"9XxNW","./canvas_util":"1tNGf","./gpgpu_context":"9nvvF","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"es42p":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fusedMatMul = require("./kernels/_FusedMatMul");
|
|
var _abs = require("./kernels/Abs");
|
|
var _acos = require("./kernels/Acos");
|
|
var _acosh = require("./kernels/Acosh");
|
|
var _add = require("./kernels/Add");
|
|
var _addN = require("./kernels/AddN");
|
|
var _all = require("./kernels/All");
|
|
var _any = require("./kernels/Any");
|
|
var _argMax = require("./kernels/ArgMax");
|
|
var _argMin = require("./kernels/ArgMin");
|
|
var _asin = require("./kernels/Asin");
|
|
var _asinh = require("./kernels/Asinh");
|
|
var _atan = require("./kernels/Atan");
|
|
var _atan2 = require("./kernels/Atan2");
|
|
var _atanh = require("./kernels/Atanh");
|
|
var _avgPool = require("./kernels/AvgPool");
|
|
var _avgPool3D = require("./kernels/AvgPool3D");
|
|
var _avgPool3DGrad = require("./kernels/AvgPool3DGrad");
|
|
var _avgPoolGrad = require("./kernels/AvgPoolGrad");
|
|
var _batchMatMul = require("./kernels/BatchMatMul");
|
|
var _batchNorm = require("./kernels/BatchNorm");
|
|
var _batchToSpaceND = require("./kernels/BatchToSpaceND");
|
|
var _bincount = require("./kernels/Bincount");
|
|
var _bitwiseAnd = require("./kernels/BitwiseAnd");
|
|
var _broadcastArgs = require("./kernels/BroadcastArgs");
|
|
var _cast = require("./kernels/Cast");
|
|
var _ceil = require("./kernels/Ceil");
|
|
var _clipByValue = require("./kernels/ClipByValue");
|
|
var _complex = require("./kernels/Complex");
|
|
var _complexAbs = require("./kernels/ComplexAbs");
|
|
var _concat = require("./kernels/Concat");
|
|
var _conv2D = require("./kernels/Conv2D");
|
|
var _conv2DBackpropFilter = require("./kernels/Conv2DBackpropFilter");
|
|
var _conv2DBackpropInput = require("./kernels/Conv2DBackpropInput");
|
|
var _conv3D = require("./kernels/Conv3D");
|
|
var _conv3DBackpropFilterV2 = require("./kernels/Conv3DBackpropFilterV2");
|
|
var _conv3DBackpropInputV2 = require("./kernels/Conv3DBackpropInputV2");
|
|
var _cos = require("./kernels/Cos");
|
|
var _cosh = require("./kernels/Cosh");
|
|
var _cropAndResize = require("./kernels/CropAndResize");
|
|
var _cumprod = require("./kernels/Cumprod");
|
|
var _cumsum = require("./kernels/Cumsum");
|
|
var _denseBincount = require("./kernels/DenseBincount");
|
|
var _depthToSpace = require("./kernels/DepthToSpace");
|
|
var _depthwiseConv2DNative = require("./kernels/DepthwiseConv2dNative");
|
|
var _depthwiseConv2DNativeBackpropFilter = require("./kernels/DepthwiseConv2dNativeBackpropFilter");
|
|
var _depthwiseConv2DNativeBackpropInput = require("./kernels/DepthwiseConv2dNativeBackpropInput");
|
|
var _diag = require("./kernels/Diag");
|
|
var _dilation2D = require("./kernels/Dilation2D");
|
|
var _einsum = require("./kernels/Einsum");
|
|
var _elu = require("./kernels/Elu");
|
|
var _eluGrad = require("./kernels/EluGrad");
|
|
var _equal = require("./kernels/Equal");
|
|
var _erf = require("./kernels/Erf");
|
|
var _exp = require("./kernels/Exp");
|
|
var _expandDims = require("./kernels/ExpandDims");
|
|
var _expm1 = require("./kernels/Expm1");
|
|
var _fft = require("./kernels/FFT");
|
|
var _fill = require("./kernels/Fill");
|
|
var _flipLeftRight = require("./kernels/FlipLeftRight");
|
|
var _floor = require("./kernels/Floor");
|
|
var _floorDiv = require("./kernels/FloorDiv");
|
|
var _fromPixels = require("./kernels/FromPixels");
|
|
var _fusedConv2D = require("./kernels/FusedConv2D");
|
|
var _fusedDepthwiseConv2D = require("./kernels/FusedDepthwiseConv2D");
|
|
var _gatherNd = require("./kernels/GatherNd");
|
|
var _gatherV2 = require("./kernels/GatherV2");
|
|
var _greater = require("./kernels/Greater");
|
|
var _greaterEqual = require("./kernels/GreaterEqual");
|
|
var _identity = require("./kernels/Identity");
|
|
var _ifft = require("./kernels/IFFT");
|
|
var _imag = require("./kernels/Imag");
|
|
var _isFinite = require("./kernels/IsFinite");
|
|
var _isInf = require("./kernels/IsInf");
|
|
var _isNaN = require("./kernels/IsNaN");
|
|
var _leakyRelu = require("./kernels/LeakyRelu");
|
|
var _less = require("./kernels/Less");
|
|
var _lessEqual = require("./kernels/LessEqual");
|
|
var _linSpace = require("./kernels/LinSpace");
|
|
var _log = require("./kernels/Log");
|
|
var _log1P = require("./kernels/Log1p");
|
|
var _logicalAnd = require("./kernels/LogicalAnd");
|
|
var _logicalNot = require("./kernels/LogicalNot");
|
|
var _logicalOr = require("./kernels/LogicalOr");
|
|
var _lrn = require("./kernels/LRN");
|
|
var _lrngrad = require("./kernels/LRNGrad");
|
|
var _max = require("./kernels/Max");
|
|
var _maximum = require("./kernels/Maximum");
|
|
var _maxPool = require("./kernels/MaxPool");
|
|
var _maxPool3D = require("./kernels/MaxPool3D");
|
|
var _maxPool3DGrad = require("./kernels/MaxPool3DGrad");
|
|
var _maxPoolGrad = require("./kernels/MaxPoolGrad");
|
|
var _maxPoolWithArgmax = require("./kernels/MaxPoolWithArgmax");
|
|
var _mean = require("./kernels/Mean");
|
|
var _min = require("./kernels/Min");
|
|
var _minimum = require("./kernels/Minimum");
|
|
var _mirrorPad = require("./kernels/MirrorPad");
|
|
var _mod = require("./kernels/Mod");
|
|
var _multinomial = require("./kernels/Multinomial");
|
|
var _multiply = require("./kernels/Multiply");
|
|
var _neg = require("./kernels/Neg");
|
|
var _nonMaxSuppressionV3 = require("./kernels/NonMaxSuppressionV3");
|
|
var _nonMaxSuppressionV4 = require("./kernels/NonMaxSuppressionV4");
|
|
var _nonMaxSuppressionV5 = require("./kernels/NonMaxSuppressionV5");
|
|
var _notEqual = require("./kernels/NotEqual");
|
|
var _oneHot = require("./kernels/OneHot");
|
|
var _onesLike = require("./kernels/OnesLike");
|
|
var _pack = require("./kernels/Pack");
|
|
var _padV2 = require("./kernels/PadV2");
|
|
var _pow = require("./kernels/Pow");
|
|
var _prelu = require("./kernels/Prelu");
|
|
var _prod = require("./kernels/Prod");
|
|
var _raggedGather = require("./kernels/RaggedGather");
|
|
var _raggedRange = require("./kernels/RaggedRange");
|
|
var _raggedTensorToTensor = require("./kernels/RaggedTensorToTensor");
|
|
var _range = require("./kernels/Range");
|
|
var _real = require("./kernels/Real");
|
|
var _realDiv = require("./kernels/RealDiv");
|
|
var _reciprocal = require("./kernels/Reciprocal");
|
|
var _relu = require("./kernels/Relu");
|
|
var _relu6 = require("./kernels/Relu6");
|
|
var _reshape = require("./kernels/Reshape");
|
|
var _resizeBilinear = require("./kernels/ResizeBilinear");
|
|
var _resizeBilinearGrad = require("./kernels/ResizeBilinearGrad");
|
|
var _resizeNearestNeighbor = require("./kernels/ResizeNearestNeighbor");
|
|
var _resizeNearestNeighborGrad = require("./kernels/ResizeNearestNeighborGrad");
|
|
var _reverse = require("./kernels/Reverse");
|
|
var _rotateWithOffset = require("./kernels/RotateWithOffset");
|
|
var _round = require("./kernels/Round");
|
|
var _rsqrt = require("./kernels/Rsqrt");
|
|
var _scatterNd = require("./kernels/ScatterNd");
|
|
var _searchSorted = require("./kernels/SearchSorted");
|
|
var _select = require("./kernels/Select");
|
|
var _selu = require("./kernels/Selu");
|
|
var _sigmoid = require("./kernels/Sigmoid");
|
|
var _sign = require("./kernels/Sign");
|
|
var _sin = require("./kernels/Sin");
|
|
var _sinh = require("./kernels/Sinh");
|
|
var _slice = require("./kernels/Slice");
|
|
var _softmax = require("./kernels/Softmax");
|
|
var _softplus = require("./kernels/Softplus");
|
|
var _spaceToBatchND = require("./kernels/SpaceToBatchND");
|
|
var _sparseFillEmptyRows = require("./kernels/SparseFillEmptyRows");
|
|
var _sparseReshape = require("./kernels/SparseReshape");
|
|
var _sparseSegmentMean = require("./kernels/SparseSegmentMean");
|
|
var _sparseSegmentSum = require("./kernels/SparseSegmentSum");
|
|
var _sparseToDense = require("./kernels/SparseToDense");
|
|
var _splitV = require("./kernels/SplitV");
|
|
var _sqrt = require("./kernels/Sqrt");
|
|
var _square = require("./kernels/Square");
|
|
var _squaredDifference = require("./kernels/SquaredDifference");
|
|
var _staticRegexReplace = require("./kernels/StaticRegexReplace");
|
|
var _step = require("./kernels/Step");
|
|
var _stridedSlice = require("./kernels/StridedSlice");
|
|
var _stringNGrams = require("./kernels/StringNGrams");
|
|
var _stringSplit = require("./kernels/StringSplit");
|
|
var _stringToHashBucketFast = require("./kernels/StringToHashBucketFast");
|
|
var _sub = require("./kernels/Sub");
|
|
var _sum = require("./kernels/Sum");
|
|
var _tan = require("./kernels/Tan");
|
|
var _tanh = require("./kernels/Tanh");
|
|
var _tensorScatterUpdate = require("./kernels/TensorScatterUpdate");
|
|
var _tile = require("./kernels/Tile");
|
|
var _topK = require("./kernels/TopK");
|
|
var _transform = require("./kernels/Transform");
|
|
var _transpose = require("./kernels/Transpose");
|
|
var _unique = require("./kernels/Unique");
|
|
var _unpack = require("./kernels/Unpack");
|
|
var _unsortedSegmentSum = require("./kernels/UnsortedSegmentSum");
|
|
var _zerosLike = require("./kernels/ZerosLike");
|
|
// List all kernel configs here
|
|
const kernelConfigs = [
|
|
(0, _fusedMatMul._fusedMatMulConfig),
|
|
(0, _abs.absConfig),
|
|
(0, _acos.acosConfig),
|
|
(0, _acosh.acoshConfig),
|
|
(0, _add.addConfig),
|
|
(0, _addN.addNConfig),
|
|
(0, _all.allConfig),
|
|
(0, _any.anyConfig),
|
|
(0, _argMax.argMaxConfig),
|
|
(0, _argMin.argMinConfig),
|
|
(0, _asin.asinConfig),
|
|
(0, _asinh.asinhConfig),
|
|
(0, _atan.atanConfig),
|
|
(0, _atan2.atan2Config),
|
|
(0, _atanh.atanhConfig),
|
|
(0, _avgPool.avgPoolConfig),
|
|
(0, _avgPool3D.avgPool3DConfig),
|
|
(0, _avgPool3DGrad.avgPool3DGradConfig),
|
|
(0, _avgPoolGrad.avgPoolGradConfig),
|
|
(0, _batchMatMul.batchMatMulConfig),
|
|
(0, _batchNorm.batchNormConfig),
|
|
(0, _batchToSpaceND.batchToSpaceNDConfig),
|
|
(0, _bincount.bincountConfig),
|
|
(0, _bitwiseAnd.bitwiseAndConfig),
|
|
(0, _broadcastArgs.broadcastArgsConfig),
|
|
(0, _cast.castConfig),
|
|
(0, _ceil.ceilConfig),
|
|
(0, _clipByValue.clipByValueConfig),
|
|
(0, _complex.complexConfig),
|
|
(0, _complexAbs.complexAbsConfig),
|
|
(0, _concat.concatConfig),
|
|
(0, _conv2D.conv2DConfig),
|
|
(0, _conv2DBackpropFilter.conv2DBackpropFilterConfig),
|
|
(0, _conv2DBackpropInput.conv2DBackpropInputConfig),
|
|
(0, _conv3D.conv3DConfig),
|
|
(0, _conv3DBackpropFilterV2.conv3DBackpropFilterV2Config),
|
|
(0, _conv3DBackpropInputV2.conv3DBackpropInputConfig),
|
|
(0, _cos.cosConfig),
|
|
(0, _cosh.coshConfig),
|
|
(0, _cropAndResize.cropAndResizeConfig),
|
|
(0, _cumprod.cumprodConfig),
|
|
(0, _cumsum.cumsumConfig),
|
|
(0, _denseBincount.denseBincountConfig),
|
|
(0, _depthToSpace.depthToSpaceConfig),
|
|
(0, _depthwiseConv2DNative.depthwiseConv2dNativeConfig),
|
|
(0, _depthwiseConv2DNativeBackpropFilter.depthwiseConv2dNativeBackpropFilterConfig),
|
|
(0, _depthwiseConv2DNativeBackpropInput.depthwiseConv2dNativeBackpropInputConfig),
|
|
(0, _diag.diagConfig),
|
|
(0, _dilation2D.dilation2DConfig),
|
|
(0, _einsum.einsumConfig),
|
|
(0, _elu.eluConfig),
|
|
(0, _eluGrad.eluGradConfig),
|
|
(0, _equal.equalConfig),
|
|
(0, _erf.erfConfig),
|
|
(0, _exp.expConfig),
|
|
(0, _expandDims.expandDimsConfig),
|
|
(0, _expm1.expm1Config),
|
|
(0, _fft.fftConfig),
|
|
(0, _fill.fillConfig),
|
|
(0, _flipLeftRight.flipLeftRightConfig),
|
|
(0, _floor.floorConfig),
|
|
(0, _floorDiv.floorDivConfig),
|
|
(0, _fromPixels.fromPixelsConfig),
|
|
(0, _fusedConv2D.fusedConv2DConfig),
|
|
(0, _fusedDepthwiseConv2D.fusedDepthwiseConv2DConfig),
|
|
(0, _gatherNd.gatherNdConfig),
|
|
(0, _gatherV2.gatherV2Config),
|
|
(0, _greater.greaterConfig),
|
|
(0, _greaterEqual.greaterEqualConfig),
|
|
(0, _identity.identityConfig),
|
|
(0, _ifft.ifftConfig),
|
|
(0, _imag.imagConfig),
|
|
(0, _isFinite.isFiniteConfig),
|
|
(0, _isInf.isInfConfig),
|
|
(0, _isNaN.isNaNConfig),
|
|
(0, _leakyRelu.leakyReluConfig),
|
|
(0, _less.lessConfig),
|
|
(0, _lessEqual.lessEqualConfig),
|
|
(0, _linSpace.linSpaceConfig),
|
|
(0, _log.logConfig),
|
|
(0, _log1P.log1pConfig),
|
|
(0, _logicalAnd.logicalAndConfig),
|
|
(0, _logicalNot.logicalNotConfig),
|
|
(0, _logicalOr.logicalOrConfig),
|
|
(0, _lrn.LRNConfig),
|
|
(0, _lrngrad.LRNGradConfig),
|
|
(0, _max.maxConfig),
|
|
(0, _maximum.maximumConfig),
|
|
(0, _maxPool.maxPoolConfig),
|
|
(0, _maxPool3D.maxPool3DConfig),
|
|
(0, _maxPool3DGrad.maxPool3DGradConfig),
|
|
(0, _maxPoolGrad.maxPoolGradConfig),
|
|
(0, _maxPoolWithArgmax.maxPoolWithArgmaxConfig),
|
|
(0, _mean.meanConfig),
|
|
(0, _min.minConfig),
|
|
(0, _minimum.minimumConfig),
|
|
(0, _mirrorPad.mirrorPadConfig),
|
|
(0, _mod.modConfig),
|
|
(0, _multinomial.multinomialConfig),
|
|
(0, _multiply.multiplyConfig),
|
|
(0, _neg.negConfig),
|
|
(0, _nonMaxSuppressionV3.nonMaxSuppressionV3Config),
|
|
(0, _nonMaxSuppressionV4.nonMaxSuppressionV4Config),
|
|
(0, _nonMaxSuppressionV5.nonMaxSuppressionV5Config),
|
|
(0, _notEqual.notEqualConfig),
|
|
(0, _oneHot.oneHotConfig),
|
|
(0, _onesLike.onesLikeConfig),
|
|
(0, _pack.packConfig),
|
|
(0, _padV2.padV2Config),
|
|
(0, _pow.powConfig),
|
|
(0, _prelu.preluConfig),
|
|
(0, _prod.prodConfig),
|
|
(0, _raggedGather.raggedGatherConfig),
|
|
(0, _raggedRange.raggedRangeConfig),
|
|
(0, _raggedTensorToTensor.raggedTensorToTensorConfig),
|
|
(0, _range.rangeConfig),
|
|
(0, _real.realConfig),
|
|
(0, _realDiv.realDivConfig),
|
|
(0, _reciprocal.reciprocalConfig),
|
|
(0, _relu.reluConfig),
|
|
(0, _relu6.relu6Config),
|
|
(0, _reshape.reshapeConfig),
|
|
(0, _resizeBilinear.resizeBilinearConfig),
|
|
(0, _resizeBilinearGrad.resizeBilinearGradConfig),
|
|
(0, _resizeNearestNeighbor.resizeNearestNeighborConfig),
|
|
(0, _resizeNearestNeighborGrad.resizeNearestNeighborGradConfig),
|
|
(0, _reverse.reverseConfig),
|
|
(0, _rotateWithOffset.rotateWithOffsetConfig),
|
|
(0, _round.roundConfig),
|
|
(0, _rsqrt.rsqrtConfig),
|
|
(0, _scatterNd.scatterNdConfig),
|
|
(0, _searchSorted.searchSortedConfig),
|
|
(0, _select.selectConfig),
|
|
(0, _selu.seluConfig),
|
|
(0, _sigmoid.sigmoidConfig),
|
|
(0, _sign.signConfig),
|
|
(0, _sin.sinConfig),
|
|
(0, _sinh.sinhConfig),
|
|
(0, _slice.sliceConfig),
|
|
(0, _softmax.softmaxConfig),
|
|
(0, _softplus.softplusConfig),
|
|
(0, _spaceToBatchND.spaceToBatchNDConfig),
|
|
(0, _sparseFillEmptyRows.sparseFillEmptyRowsConfig),
|
|
(0, _sparseReshape.sparseReshapeConfig),
|
|
(0, _sparseSegmentMean.sparseSegmentMeanConfig),
|
|
(0, _sparseSegmentSum.sparseSegmentSumConfig),
|
|
(0, _sparseToDense.sparseToDenseConfig),
|
|
(0, _splitV.splitVConfig),
|
|
(0, _sqrt.sqrtConfig),
|
|
(0, _square.squareConfig),
|
|
(0, _squaredDifference.squaredDifferenceConfig),
|
|
(0, _staticRegexReplace.staticRegexReplaceConfig),
|
|
(0, _step.stepConfig),
|
|
(0, _stridedSlice.stridedSliceConfig),
|
|
(0, _stringNGrams.stringNGramsConfig),
|
|
(0, _stringSplit.stringSplitConfig),
|
|
(0, _stringToHashBucketFast.stringToHashBucketFastConfig),
|
|
(0, _sub.subConfig),
|
|
(0, _sum.sumConfig),
|
|
(0, _tan.tanConfig),
|
|
(0, _tanh.tanhConfig),
|
|
(0, _tensorScatterUpdate.tensorScatterUpdateConfig),
|
|
(0, _tile.tileConfig),
|
|
(0, _topK.topKConfig),
|
|
(0, _transform.transformConfig),
|
|
(0, _transpose.transposeConfig),
|
|
(0, _unique.uniqueConfig),
|
|
(0, _unpack.unpackConfig),
|
|
(0, _unsortedSegmentSum.unsortedSegmentSumConfig),
|
|
(0, _zerosLike.zerosLikeConfig)
|
|
];
|
|
for (const kernelConfig of kernelConfigs)(0, _tfjsCore.registerKernel)(kernelConfig);
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./kernels/_FusedMatMul":"f5H8C","./kernels/Abs":"5sWXh","./kernels/Acos":"88j8R","./kernels/Acosh":"3MqlI","./kernels/Add":"iCeMO","./kernels/AddN":"inami","./kernels/All":"8QrzY","./kernels/Any":"cNRuv","./kernels/ArgMax":"cxDNq","./kernels/ArgMin":"7we0s","./kernels/Asin":"2y04O","./kernels/Asinh":"8uUU0","./kernels/Atan":"hh4aJ","./kernels/Atan2":"k9THK","./kernels/Atanh":"3axXM","./kernels/AvgPool":"iU9nc","./kernels/AvgPool3D":"dFK3l","./kernels/AvgPool3DGrad":"kSFm4","./kernels/AvgPoolGrad":"dwrYJ","./kernels/BatchMatMul":"9tzUH","./kernels/BatchNorm":"2u2bT","./kernels/BatchToSpaceND":"bsQ5u","./kernels/Bincount":"7xVX3","./kernels/BitwiseAnd":"87LwA","./kernels/BroadcastArgs":"9Zlag","./kernels/Cast":"c2JG9","./kernels/Ceil":"iSroj","./kernels/ClipByValue":"gt2mD","./kernels/Complex":"55NfL","./kernels/ComplexAbs":"fwiH6","./kernels/Concat":"2gCZH","./kernels/Conv2D":"425yr","./kernels/Conv2DBackpropFilter":"iNkBM","./kernels/Conv2DBackpropInput":"jm349","./kernels/Conv3D":"c8Gvg","./kernels/Conv3DBackpropFilterV2":"lV1Z3","./kernels/Conv3DBackpropInputV2":"fnJFd","./kernels/Cos":"2H7EX","./kernels/Cosh":"jBLJs","./kernels/CropAndResize":"aCuUK","./kernels/Cumprod":"fIbv6","./kernels/Cumsum":"l2jIP","./kernels/DenseBincount":"7qaEa","./kernels/DepthToSpace":"926cY","./kernels/DepthwiseConv2dNative":"9xbgW","./kernels/DepthwiseConv2dNativeBackpropFilter":"aWI5l","./kernels/DepthwiseConv2dNativeBackpropInput":"6HZVm","./kernels/Diag":"7TZuU","./kernels/Dilation2D":"lLrqs","./kernels/Einsum":"hmWYw","./kernels/Elu":"fJBTw","./kernels/EluGrad":"hjBqq","./kernels/Equal":"dNiJE","./kernels/Erf":"ahvKl","./kernels/Exp":"i4xew","./kernels/ExpandDims":"5OvP3","./kernels/Expm1":"baClA","./kernels/FFT":"zq0LC","./kernels/Fill":"6Rawr","./kernels/FlipLeftRight":"8QDUY","./kernels/Floor":"hB9uc","./kernels/FloorDiv":"g0Hz7","./kernels/FromPixels":"bNE2l","./kernels/FusedConv2D":"5vkH0","./kernels/FusedDepthwiseConv2D":"5SfAK","./kernels/GatherNd":"4xUDy","./kernels/GatherV2":"cBFXe","./kernels/Greater":"eDhqn","./kernels/GreaterEqual":"1w6uF","./kernels/Identity":"hY9aT","./kernels/IFFT":"1mdy7","./kernels/Imag":"3PMfw","./kernels/IsFinite":"aWWtq","./kernels/IsInf":"bxXPH","./kernels/IsNaN":"jUwW0","./kernels/LeakyRelu":"hocMJ","./kernels/Less":"htToM","./kernels/LessEqual":"eXbD5","./kernels/LinSpace":"kM2RJ","./kernels/Log":"fVZGS","./kernels/Log1p":"czYhe","./kernels/LogicalAnd":"37RLf","./kernels/LogicalNot":"b9oed","./kernels/LogicalOr":"4Kv3V","./kernels/LRN":"6ZjnF","./kernels/LRNGrad":"BMOEB","./kernels/Max":"11YMi","./kernels/Maximum":"9B0Ki","./kernels/MaxPool":"74RsU","./kernels/MaxPool3D":"iXVcU","./kernels/MaxPool3DGrad":"eejL1","./kernels/MaxPoolGrad":"eaA7G","./kernels/MaxPoolWithArgmax":"jaMAy","./kernels/Mean":"4HPXU","./kernels/Min":"pHfvF","./kernels/Minimum":"5hTEN","./kernels/MirrorPad":"fGu7V","./kernels/Mod":"f0WUU","./kernels/Multinomial":"wTvWa","./kernels/Multiply":"5ePR8","./kernels/Neg":"6P8i7","./kernels/NonMaxSuppressionV3":"fEqP1","./kernels/NonMaxSuppressionV4":"5Qv9T","./kernels/NonMaxSuppressionV5":"T9Z8C","./kernels/NotEqual":"hOvsV","./kernels/OneHot":"6SVa6","./kernels/OnesLike":"cH3Uy","./kernels/Pack":"73QIj","./kernels/PadV2":"bOlXa","./kernels/Pow":"5GYaP","./kernels/Prelu":"a9omL","./kernels/Prod":"1BmsY","./kernels/RaggedGather":"dhNCK","./kernels/RaggedRange":"e99uc","./kernels/RaggedTensorToTensor":"c17RR","./kernels/Range":"4ulNZ","./kernels/Real":"4HOZy","./kernels/RealDiv":"cbtMz","./kernels/Reciprocal":"5wKjZ","./kernels/Relu":"fTpFl","./kernels/Relu6":"inRmD","./kernels/Reshape":"fgZen","./kernels/ResizeBilinear":"iNia7","./kernels/ResizeBilinearGrad":"gEi6O","./kernels/ResizeNearestNeighbor":"eTSe5","./kernels/ResizeNearestNeighborGrad":"fZoE2","./kernels/Reverse":"81ghw","./kernels/RotateWithOffset":"7nWSD","./kernels/Round":"gGWXk","./kernels/Rsqrt":"2xH8K","./kernels/ScatterNd":"cYHjA","./kernels/SearchSorted":"kyGeI","./kernels/Select":"b6rGf","./kernels/Selu":"1HlBg","./kernels/Sigmoid":"c3gWE","./kernels/Sign":"83hlB","./kernels/Sin":"6Fn44","./kernels/Sinh":"9tvOm","./kernels/Slice":"6jQ29","./kernels/Softmax":"cHx7b","./kernels/Softplus":"1YmQs","./kernels/SpaceToBatchND":"58w9T","./kernels/SparseFillEmptyRows":"iVlEr","./kernels/SparseReshape":"arBQ7","./kernels/SparseSegmentMean":"gQmRe","./kernels/SparseSegmentSum":"2zeh8","./kernels/SparseToDense":"2SjVb","./kernels/SplitV":"6cXfl","./kernels/Sqrt":"4bT4M","./kernels/Square":"jCuUm","./kernels/SquaredDifference":"fSbIq","./kernels/StaticRegexReplace":"8HWNl","./kernels/Step":"d3n9V","./kernels/StridedSlice":"47wD9","./kernels/StringNGrams":"aUZOK","./kernels/StringSplit":"ezwh5","./kernels/StringToHashBucketFast":"b6pUo","./kernels/Sub":"gV1EU","./kernels/Sum":"c4eiD","./kernels/Tan":"2vzWF","./kernels/Tanh":"7BFBf","./kernels/TensorScatterUpdate":"2uPVJ","./kernels/Tile":"dbDLN","./kernels/TopK":"gvorh","./kernels/Transform":"4cCvF","./kernels/Transpose":"cKJAC","./kernels/Unique":"e7lqL","./kernels/Unpack":"5jnF3","./kernels/UnsortedSegmentSum":"vnA1C","./kernels/ZerosLike":"28sQG"}],"f5H8C":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "_fusedMatMul", ()=>_fusedMatMul);
|
|
parcelHelpers.export(exports, "_fusedMatMulConfig", ()=>_fusedMatMulConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _batchMatMulImpl = require("./BatchMatMul_impl");
|
|
function _fusedMatMul(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { a, b, bias, preluActivationWeights } = inputs;
|
|
const { transposeA, transposeB, activation, leakyreluAlpha } = attrs;
|
|
return (0, _batchMatMulImpl.batchMatMulImpl)({
|
|
a,
|
|
b,
|
|
transposeA,
|
|
transposeB,
|
|
backend,
|
|
bias,
|
|
preluActivationWeights,
|
|
leakyreluAlpha,
|
|
activation
|
|
});
|
|
}
|
|
const _fusedMatMulConfig = {
|
|
kernelName: (0, _tfjsCore._FusedMatMul),
|
|
backendName: "webgl",
|
|
kernelFunc: _fusedMatMul
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./BatchMatMul_impl":"kyEQG","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kyEQG":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MATMUL_SHARED_DIM_THRESHOLD", ()=>MATMUL_SHARED_DIM_THRESHOLD);
|
|
parcelHelpers.export(exports, "batchMatMulImpl", ()=>batchMatMulImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _mulmatPackedGpu = require("../mulmat_packed_gpu");
|
|
var _multiply = require("./Multiply");
|
|
var _reshape = require("./Reshape");
|
|
var _sum = require("./Sum");
|
|
var _transpose = require("./Transpose");
|
|
const MATMUL_SHARED_DIM_THRESHOLD = 1000;
|
|
function batchMatMulImpl({ a, b, transposeA, transposeB, backend, bias = null, preluActivationWeights = null, leakyreluAlpha = 0, activation = null }) {
|
|
const aRank = a.shape.length;
|
|
const bRank = b.shape.length;
|
|
const innerShapeA = transposeA ? a.shape[aRank - 2] : a.shape[aRank - 1];
|
|
const innerShapeB = transposeB ? b.shape[bRank - 1] : b.shape[bRank - 2];
|
|
const outerShapeA = transposeA ? a.shape[aRank - 1] : a.shape[aRank - 2];
|
|
const outerShapeB = transposeB ? b.shape[bRank - 2] : b.shape[bRank - 1];
|
|
const outerDimsA = a.shape.slice(0, -2);
|
|
const outerDimsB = b.shape.slice(0, -2);
|
|
const batchDimA = (0, _tfjsCore.util).sizeFromShape(outerDimsA);
|
|
const batchDimB = (0, _tfjsCore.util).sizeFromShape(outerDimsB);
|
|
const outShapeOuterDims = (0, _tfjsCore.broadcast_util).assertAndGetBroadcastShape(a.shape.slice(0, -2), b.shape.slice(0, -2));
|
|
const outShape = outShapeOuterDims.concat([
|
|
outerShapeA,
|
|
outerShapeB
|
|
]);
|
|
(0, _tfjsCore.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 a3dShape = transposeA ? [
|
|
batchDimA,
|
|
innerShapeA,
|
|
outerShapeA
|
|
] : [
|
|
batchDimA,
|
|
outerShapeA,
|
|
innerShapeA
|
|
];
|
|
const b3dShape = transposeB ? [
|
|
batchDimB,
|
|
outerShapeB,
|
|
innerShapeB
|
|
] : [
|
|
batchDimB,
|
|
innerShapeB,
|
|
outerShapeB
|
|
];
|
|
// The rest of the implementation is designed to operate on rank-3 tensors
|
|
const a3d = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: a
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: a3dShape
|
|
}
|
|
});
|
|
const b3d = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: b
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: b3dShape
|
|
}
|
|
});
|
|
const intermediates = [
|
|
a3d,
|
|
b3d
|
|
];
|
|
const batchDim = Math.max(batchDimA, batchDimB);
|
|
const sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];
|
|
const hasBias = bias != null;
|
|
const hasPreluActivationWeights = preluActivationWeights != null;
|
|
const hasLeakyreluAlpha = activation === "leakyrelu";
|
|
const fusedActivation = activation != null ? (0, _kernelFuncsUtils.mapActivationToShaderProgram)(activation, true) : null;
|
|
const containsFusedOps = hasBias || hasPreluActivationWeights || hasLeakyreluAlpha || fusedActivation != null;
|
|
let out;
|
|
// 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 && containsFusedOps === false) {
|
|
let aVec = a3d;
|
|
let bVec = b3d;
|
|
if (transposeA) {
|
|
aVec = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: a3d
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: [
|
|
0,
|
|
2,
|
|
1
|
|
]
|
|
}
|
|
});
|
|
intermediates.push(aVec);
|
|
}
|
|
if (transposeB) {
|
|
bVec = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: b3d
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: [
|
|
0,
|
|
2,
|
|
1
|
|
]
|
|
}
|
|
});
|
|
intermediates.push(bVec);
|
|
}
|
|
const shouldReshapeA = outerShapeB !== 1;
|
|
const shouldReshapeB = outerShapeB === 1;
|
|
let aVec3d = aVec;
|
|
if (shouldReshapeA) {
|
|
aVec3d = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: aVec
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
batchDim,
|
|
sharedDim,
|
|
1
|
|
]
|
|
}
|
|
});
|
|
intermediates.push(aVec3d);
|
|
}
|
|
const axis = outerShapeB === 1 ? 2 : 1;
|
|
let bVec3d = bVec;
|
|
if (shouldReshapeB) {
|
|
bVec3d = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: bVec
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
batchDim,
|
|
1,
|
|
sharedDim
|
|
]
|
|
}
|
|
});
|
|
intermediates.push(bVec3d);
|
|
}
|
|
const product = (0, _multiply.multiply)({
|
|
inputs: {
|
|
a: aVec3d,
|
|
b: bVec3d
|
|
},
|
|
backend
|
|
});
|
|
out = (0, _sum.sum)({
|
|
inputs: {
|
|
x: product
|
|
},
|
|
backend,
|
|
attrs: {
|
|
axis,
|
|
keepDims: true
|
|
}
|
|
});
|
|
intermediates.push(product);
|
|
} else {
|
|
const dtype = (0, _tfjsCore.upcastType)(a.dtype, b.dtype);
|
|
const program = new (0, _mulmatPackedGpu.MatMulPackedProgram)(a3dShape, b3dShape, [
|
|
batchDim,
|
|
outerShapeA,
|
|
outerShapeB
|
|
], transposeA, transposeB, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
|
|
const inputs = [
|
|
a3d,
|
|
b3d
|
|
];
|
|
if (bias != null) inputs.push(bias);
|
|
if (hasPreluActivationWeights) inputs.push(preluActivationWeights);
|
|
if (hasLeakyreluAlpha) {
|
|
const $leakyreluAlpha = backend.makeTensorInfo([], "float32", (0, _tfjsCore.util).createScalarValue(leakyreluAlpha, "float32"));
|
|
inputs.push($leakyreluAlpha);
|
|
intermediates.push($leakyreluAlpha);
|
|
}
|
|
out = backend.runWebGLProgram(program, inputs, dtype);
|
|
}
|
|
const outReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: out
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
intermediates.push(out);
|
|
for (const i of intermediates)backend.disposeIntermediateTensorInfo(i);
|
|
return outReshaped;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../mulmat_packed_gpu":"cdOmp","./Multiply":"5ePR8","./Reshape":"fgZen","./Sum":"c4eiD","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"grPtN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "CHECK_NAN_SNIPPET_UNARY", ()=>CHECK_NAN_SNIPPET_UNARY);
|
|
/**
|
|
* Template that creates a `KernelFunc` for unary ops.
|
|
* @param opSnippet Op snippet to create `UnaryOpProgram`.
|
|
* @param packedOpSnippet Op snippet to create `UnaryOpPackedProgram`.
|
|
* @param dtype Optional. If set, the result has this dtype. Otherwise, the
|
|
* result has the same dtype as the first input. This is mainly used in
|
|
* comparison kernels, such as Equal, Less, Greater, etc.
|
|
*/ parcelHelpers.export(exports, "unaryKernelFunc", ()=>unaryKernelFunc);
|
|
/**
|
|
* Template that creates a `KernelFunc` for binary ops.
|
|
* @param opSnippet Op snippet to create `BinaryOpProgram`.
|
|
* @param packedOpSnippet Op snippet to create `BinaryOpPackedProgram`.
|
|
* @param checkOutOfBoundsForPackedProgram Whether to set checkOutOfBounds=true
|
|
* when creating BinaryOpPackedProgram.
|
|
* @param dtype Optional. If set, the result has this dtype. Otherwise, the
|
|
* result has the same dtype as the first input. This is mainly used in
|
|
* comparison kernels, such as Equal, Less, Greater, etc.
|
|
*/ parcelHelpers.export(exports, "binaryKernelFunc", ()=>binaryKernelFunc);
|
|
parcelHelpers.export(exports, "mapActivationToShaderProgram", ()=>mapActivationToShaderProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _complex = require("../kernels/Complex");
|
|
var _leakyRelu = require("../kernels/LeakyRelu");
|
|
var _prelu = require("../kernels/Prelu");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
var _unaryopPackedGpu = require("../unaryop_packed_gpu");
|
|
const CHECK_NAN_SNIPPET_UNARY = `if (isnan(x)) return x;`;
|
|
function unaryKernelFunc({ opSnippet, packedOpSnippet, cpuKernelImpl, dtype }) {
|
|
return ({ inputs, backend })=>{
|
|
const { x } = inputs;
|
|
const webglBackend = backend;
|
|
const $dtype = dtype || x.dtype;
|
|
if (webglBackend.shouldExecuteOnCPU([
|
|
x
|
|
]) && cpuKernelImpl != null) {
|
|
const xData = webglBackend.texData.get(x.dataId);
|
|
const outValues = cpuKernelImpl(xData.values, $dtype);
|
|
return webglBackend.makeTensorInfo(x.shape, $dtype, outValues);
|
|
}
|
|
const shouldUsePackedProgram = (0, _tfjsCore.env)().getBool("WEBGL_PACK_UNARY_OPERATIONS") && packedOpSnippet != null;
|
|
let program;
|
|
if (shouldUsePackedProgram) program = new (0, _unaryopPackedGpu.UnaryOpPackedProgram)(x.shape, packedOpSnippet);
|
|
else program = new (0, _unaryopGpu.UnaryOpProgram)(x.shape, opSnippet);
|
|
return webglBackend.runWebGLProgram(program, [
|
|
x
|
|
], $dtype);
|
|
};
|
|
}
|
|
function binaryKernelFunc({ opSnippet, packedOpSnippet, checkOutOfBounds = false, supportsComplex = false, cpuKernelImpl, dtype }) {
|
|
return ({ inputs, backend })=>{
|
|
const { a, b } = inputs;
|
|
const webglBackend = backend;
|
|
if (supportsComplex && a.dtype === "complex64") {
|
|
const aData = webglBackend.texData.get(a.dataId);
|
|
const bData = webglBackend.texData.get(b.dataId);
|
|
const [real, imag] = [
|
|
[
|
|
aData.complexTensorInfos.real,
|
|
bData.complexTensorInfos.real
|
|
],
|
|
[
|
|
aData.complexTensorInfos.imag,
|
|
bData.complexTensorInfos.imag
|
|
]
|
|
].map((complexParts)=>{
|
|
const [aPart, bPart] = complexParts;
|
|
const aHandle = {
|
|
dataId: aPart.dataId,
|
|
dtype: aPart.dtype,
|
|
shape: a.shape
|
|
};
|
|
const bHandle = {
|
|
dataId: bPart.dataId,
|
|
dtype: bPart.dtype,
|
|
shape: b.shape
|
|
};
|
|
const program = new (0, _binaryopGpu.BinaryOpProgram)(opSnippet, a.shape, b.shape);
|
|
return webglBackend.runWebGLProgram(program, [
|
|
aHandle,
|
|
bHandle
|
|
], (0, _tfjsCore.upcastType)(aPart.dtype, bPart.dtype));
|
|
});
|
|
const complexOutput = (0, _complex.complex)({
|
|
inputs: {
|
|
real,
|
|
imag
|
|
},
|
|
backend: webglBackend
|
|
});
|
|
webglBackend.disposeIntermediateTensorInfo(real);
|
|
webglBackend.disposeIntermediateTensorInfo(imag);
|
|
// TODO(annxingyuan): Implement CPU forwarding for complex inputs.
|
|
return complexOutput;
|
|
}
|
|
const $dtype = dtype || (0, _tfjsCore.upcastType)(a.dtype, b.dtype);
|
|
if ((a.dtype === "string" || b.dtype === "string" || webglBackend.shouldExecuteOnCPU([
|
|
a,
|
|
b
|
|
])) && cpuKernelImpl != null) {
|
|
const aVals = webglBackend.texData.get(a.dataId).values;
|
|
const bVals = webglBackend.texData.get(b.dataId).values;
|
|
const decodedAVals = a.dtype === "string" ? // tslint:disable-next-line: no-any
|
|
(0, _tfjsCore.backend_util).fromUint8ToStringArray(aVals) : aVals;
|
|
const decodedBVals = a.dtype === "string" ? // tslint:disable-next-line: no-any
|
|
(0, _tfjsCore.backend_util).fromUint8ToStringArray(bVals) : bVals;
|
|
const [outValues, outShape] = cpuKernelImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype);
|
|
const out = webglBackend.makeTensorInfo(outShape, $dtype);
|
|
const outData = webglBackend.texData.get(out.dataId);
|
|
outData.values = outValues;
|
|
return out;
|
|
}
|
|
const shouldUsePackedProgram = (0, _tfjsCore.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS") && packedOpSnippet != null;
|
|
let program;
|
|
if (shouldUsePackedProgram) program = new (0, _binaryopPackedGpu.BinaryOpPackedProgram)(packedOpSnippet, a.shape, b.shape, checkOutOfBounds);
|
|
else program = new (0, _binaryopGpu.BinaryOpProgram)(opSnippet, a.shape, b.shape);
|
|
return webglBackend.runWebGLProgram(program, [
|
|
a,
|
|
b
|
|
], $dtype);
|
|
};
|
|
}
|
|
function mapActivationToShaderProgram(activation, packed = false) {
|
|
if (activation === "linear") {
|
|
if (packed) return _unaryopPackedGpu.LINEAR;
|
|
return _unaryopGpu.LINEAR;
|
|
} else if (activation === "relu") {
|
|
if (packed) return _unaryopPackedGpu.RELU;
|
|
return _unaryopGpu.RELU;
|
|
} else if (activation === "elu") {
|
|
if (packed) return _unaryopPackedGpu.ELU;
|
|
return _unaryopGpu.ELU;
|
|
} else if (activation === "relu6") {
|
|
if (packed) return _unaryopPackedGpu.RELU6;
|
|
return _unaryopGpu.RELU6;
|
|
} else if (activation === "prelu") {
|
|
if (packed) return 0, _prelu.PRELU_PACKED;
|
|
return 0, _prelu.PRELU;
|
|
} else if (activation === "leakyrelu") {
|
|
if (packed) return 0, _leakyRelu.LEAKYRELU_PACKED;
|
|
return 0, _leakyRelu.LEAKYRELU;
|
|
} else if (activation === "sigmoid") {
|
|
if (packed) return _unaryopPackedGpu.SIGMOID;
|
|
return _unaryopGpu.SIGMOID;
|
|
}
|
|
throw new Error(`Activation ${activation} has not been implemented for the WebGL backend.`);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","../kernels/Complex":"55NfL","../kernels/LeakyRelu":"hocMJ","../kernels/Prelu":"a9omL","../unaryop_gpu":"gIMrR","../unaryop_packed_gpu":"c4D5K","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"d0A5z":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "CHECK_NAN_SNIPPET", ()=>CHECK_NAN_SNIPPET);
|
|
parcelHelpers.export(exports, "SQUARED_DIFFERENCE", ()=>SQUARED_DIFFERENCE);
|
|
parcelHelpers.export(exports, "BinaryOpProgram", ()=>BinaryOpProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
const CHECK_NAN_SNIPPET = `
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`;
|
|
const SQUARED_DIFFERENCE = "return (a - b) * (a - b);";
|
|
class BinaryOpProgram {
|
|
constructor(op, aShape, bShape){
|
|
this.variableNames = [
|
|
"A",
|
|
"B"
|
|
];
|
|
this.outputShape = (0, _tfjsCore.backend_util).assertAndGetBroadcastShape(aShape, bShape);
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
this.userCode = `
|
|
float binaryOperation(float a, float b) {
|
|
${op}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hkzp7":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "CHECK_NAN_SNIPPET_PACKED", ()=>CHECK_NAN_SNIPPET_PACKED);
|
|
parcelHelpers.export(exports, "ELU_DER", ()=>ELU_DER);
|
|
parcelHelpers.export(exports, "NOT_EQUAL", ()=>NOT_EQUAL);
|
|
parcelHelpers.export(exports, "BinaryOpPackedProgram", ()=>BinaryOpPackedProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
const CHECK_NAN_SNIPPET_PACKED = `
|
|
result.r = isNaN.r ? NAN : result.r;
|
|
result.g = isNaN.g ? NAN : result.g;
|
|
result.b = isNaN.b ? NAN : result.b;
|
|
result.a = isNaN.a ? NAN : result.a;
|
|
`;
|
|
const ELU_DER = `
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`;
|
|
const NOT_EQUAL = `
|
|
return vec4(notEqual(a, b));
|
|
`;
|
|
class BinaryOpPackedProgram {
|
|
constructor(op, aShape, bShape, checkOutOfBounds = false){
|
|
this.variableNames = [
|
|
"A",
|
|
"B"
|
|
];
|
|
this.supportsBroadcasting = true;
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.outputShape = (0, _tfjsCore.backend_util).assertAndGetBroadcastShape(aShape, bShape);
|
|
const rank = this.outputShape.length;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(rank);
|
|
let checkOutOfBoundsString = "";
|
|
if (checkOutOfBounds) {
|
|
if (rank === 0 || (0, _tfjsCore.util).sizeFromShape(this.outputShape) === 1) checkOutOfBoundsString = `
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;
|
|
else {
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(rank);
|
|
checkOutOfBoundsString = `
|
|
${dtype} coords = getOutputCoords();
|
|
`;
|
|
if (rank === 1) {
|
|
if (this.enableShapeUniforms) checkOutOfBoundsString += `
|
|
result.y = (coords + 1) >= outShape ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;
|
|
else checkOutOfBoundsString += `
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;
|
|
} else {
|
|
const channels = (0, _packingUtil.getChannels)("coords", rank);
|
|
if (this.enableShapeUniforms) checkOutOfBoundsString += `
|
|
bool nextRowOutOfBounds =
|
|
(${channels[rank - 2]} + 1) >= outShape[${rank} - 2];
|
|
bool nextColOutOfBounds =
|
|
(${channels[rank - 1]} + 1) >= outShape[${rank} - 1];
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`;
|
|
else 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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./gpgpu_math":"btJo5","./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"55NfL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* In WebGL data is stored in GPU textures which can't be efficiently copied, so
|
|
* complex tensors share data with their real and imaginary components. Complex
|
|
* tensors' reference to the components is tracked by refCount on the individual
|
|
* component. The refCounts are increased by the identity call.
|
|
*
|
|
* When a complex tensor is disposed, it will reduce the refCount on the
|
|
* components by calling disposeData on each.
|
|
*/ parcelHelpers.export(exports, "complex", ()=>complex);
|
|
parcelHelpers.export(exports, "complexConfig", ()=>complexConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _identity = require("./Identity");
|
|
function complex(args) {
|
|
const { inputs, backend } = args;
|
|
const { real, imag } = inputs;
|
|
const complexInfo = backend.makeTensorInfo(real.shape, "complex64");
|
|
const complex = backend.texData.get(complexInfo.dataId);
|
|
const realTensorInfo = (0, _identity.identity)({
|
|
inputs: {
|
|
x: real
|
|
},
|
|
backend
|
|
});
|
|
const imagTensorInfo = (0, _identity.identity)({
|
|
inputs: {
|
|
x: imag
|
|
},
|
|
backend
|
|
});
|
|
complex.complexTensorInfos = {
|
|
real: realTensorInfo,
|
|
imag: imagTensorInfo
|
|
};
|
|
return complexInfo;
|
|
}
|
|
const complexConfig = {
|
|
kernelName: (0, _tfjsCore.Complex),
|
|
backendName: "webgl",
|
|
kernelFunc: complex
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Identity":"hY9aT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hY9aT":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "identity", ()=>identity);
|
|
parcelHelpers.export(exports, "identityConfig", ()=>identityConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function identity(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
backend.incRef(x.dataId);
|
|
return {
|
|
dataId: x.dataId,
|
|
shape: x.shape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
const identityConfig = {
|
|
kernelName: (0, _tfjsCore.Identity),
|
|
backendName: "webgl",
|
|
kernelFunc: identity
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hocMJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "LEAKYRELU", ()=>LEAKYRELU);
|
|
parcelHelpers.export(exports, "LEAKYRELU_PACKED", ()=>LEAKYRELU_PACKED);
|
|
parcelHelpers.export(exports, "leakyRelu", ()=>leakyRelu);
|
|
parcelHelpers.export(exports, "leakyReluConfig", ()=>leakyReluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
const LEAKYRELU = `return (a < 0.) ? b * a : a;`;
|
|
const LEAKYRELU_PACKED = `
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;
|
|
function leakyRelu(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { alpha } = attrs;
|
|
const $alpha = backend.makeTensorInfo([], "float32", (0, _tfjsCore.util).createScalarValue(alpha, "float32"));
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new (0, _binaryopPackedGpu.BinaryOpPackedProgram)(LEAKYRELU_PACKED, x.shape, $alpha.shape) : new (0, _binaryopGpu.BinaryOpProgram)(LEAKYRELU, x.shape, $alpha.shape);
|
|
const result = backend.runWebGLProgram(program, [
|
|
x,
|
|
$alpha
|
|
], "float32");
|
|
backend.disposeIntermediateTensorInfo($alpha);
|
|
return result;
|
|
}
|
|
const leakyReluConfig = {
|
|
kernelName: (0, _tfjsCore.LeakyRelu),
|
|
backendName: "webgl",
|
|
kernelFunc: leakyRelu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a9omL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "PRELU", ()=>PRELU);
|
|
parcelHelpers.export(exports, "PRELU_PACKED", ()=>PRELU_PACKED);
|
|
parcelHelpers.export(exports, "prelu", ()=>prelu);
|
|
parcelHelpers.export(exports, "preluConfig", ()=>preluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
const PRELU = `return (a < 0.) ? b * a : a;`;
|
|
const PRELU_PACKED = `
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;
|
|
function prelu(args) {
|
|
const { inputs, backend } = args;
|
|
const { x, alpha } = inputs;
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new (0, _binaryopPackedGpu.BinaryOpPackedProgram)(PRELU_PACKED, x.shape, alpha.shape) : new (0, _binaryopGpu.BinaryOpProgram)(PRELU, x.shape, alpha.shape);
|
|
return backend.runWebGLProgram(program, [
|
|
x,
|
|
alpha
|
|
], "float32");
|
|
}
|
|
const preluConfig = {
|
|
kernelName: (0, _tfjsCore.Prelu),
|
|
backendName: "webgl",
|
|
kernelFunc: prelu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cdOmp":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MatMulPackedProgram", ()=>MatMulPackedProgram);
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
class MatMulPackedProgram {
|
|
constructor(aShape, bShape, outputShape, transposeA = false, transposeB = false, addBias = false, activation = null, hasPreluActivation = false, hasLeakyreluActivation = false){
|
|
this.variableNames = [
|
|
"matrixA",
|
|
"matrixB"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.outputShape = outputShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
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 if (hasLeakyreluActivation) activationSnippet = `vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${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");
|
|
if (hasLeakyreluActivation) this.variableNames.push("leakyreluAlpha");
|
|
let batchASnippet = "rc.x";
|
|
let batchBSnippet = "rc.x";
|
|
if (aShape[0] < bShape[0]) batchASnippet = `imod(rc.x, ${aShape[0]})`;
|
|
else if (bShape[0] < aShape[0]) batchBSnippet = `imod(rc.x, ${bShape[0]})`;
|
|
this.userCode = `
|
|
${activationSnippet}
|
|
// Don't use uniform for sharedDimensionPacked for performance.
|
|
const float sharedDimension = ${sharedDimensionPacked}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
int batchA = ${batchASnippet};
|
|
int batchB = ${batchBSnippet};
|
|
for (int i = 0; i < ${sharedDimensionPacked}; i++) {
|
|
vec4 a = getMatrixA(batchA, ${aSample});
|
|
vec4 b = getMatrixB(batchB, ${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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5ePR8":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "multiply", ()=>multiply);
|
|
parcelHelpers.export(exports, "multiplyConfig", ()=>multiplyConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopComplexGpu = require("../binaryop_complex_gpu");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _complex = require("./Complex");
|
|
const MUL = "return a * b;";
|
|
function multiply(args) {
|
|
const { inputs, backend } = args;
|
|
const { a, b } = inputs;
|
|
const dtype = (0, _tfjsCore.backend_util).upcastType(a.dtype, b.dtype);
|
|
if (a.dtype === "complex64") {
|
|
const aData = backend.texData.get(a.dataId);
|
|
const bData = backend.texData.get(b.dataId);
|
|
const realProgram = new (0, _binaryopComplexGpu.BinaryOpComplexProgram)(_binaryopComplexGpu.COMPLEX_MULTIPLY.REAL, a.shape, b.shape);
|
|
const imagProgram = new (0, _binaryopComplexGpu.BinaryOpComplexProgram)(_binaryopComplexGpu.COMPLEX_MULTIPLY.IMAG, a.shape, b.shape);
|
|
const inputs = [
|
|
{
|
|
dataId: aData.complexTensorInfos.real.dataId,
|
|
dtype: aData.complexTensorInfos.real.dtype,
|
|
shape: a.shape
|
|
},
|
|
{
|
|
dataId: aData.complexTensorInfos.imag.dataId,
|
|
dtype: aData.complexTensorInfos.imag.dtype,
|
|
shape: a.shape
|
|
},
|
|
{
|
|
dataId: bData.complexTensorInfos.real.dataId,
|
|
dtype: bData.complexTensorInfos.real.dtype,
|
|
shape: b.shape
|
|
},
|
|
{
|
|
dataId: bData.complexTensorInfos.imag.dataId,
|
|
dtype: bData.complexTensorInfos.imag.dtype,
|
|
shape: b.shape
|
|
}
|
|
];
|
|
const realPart = backend.runWebGLProgram(realProgram, inputs, "float32");
|
|
const imagPart = backend.runWebGLProgram(imagProgram, inputs, "float32");
|
|
const complexOutput = (0, _complex.complex)({
|
|
inputs: {
|
|
real: realPart,
|
|
imag: imagPart
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(realPart);
|
|
backend.disposeIntermediateTensorInfo(imagPart);
|
|
// TODO(annxingyuan): CPU forwarding for complex inputs.
|
|
return complexOutput;
|
|
}
|
|
if (backend.shouldExecuteOnCPU([
|
|
a,
|
|
b
|
|
])) {
|
|
const aData = backend.texData.get(a.dataId);
|
|
const bData = backend.texData.get(b.dataId);
|
|
const [outValues, outShape] = (0, _shared.multiplyImplCPU)(a.shape, b.shape, aData.values, bData.values, dtype);
|
|
const out = backend.makeTensorInfo(outShape, dtype);
|
|
const outData = backend.texData.get(out.dataId);
|
|
outData.values = outValues;
|
|
return out;
|
|
}
|
|
let program;
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS")) program = new (0, _binaryopPackedGpu.BinaryOpPackedProgram)(MUL, a.shape, b.shape);
|
|
else program = new (0, _binaryopGpu.BinaryOpProgram)(MUL, a.shape, b.shape);
|
|
return backend.runWebGLProgram(program, [
|
|
a,
|
|
b
|
|
], dtype);
|
|
}
|
|
const multiplyConfig = {
|
|
kernelName: (0, _tfjsCore.Multiply),
|
|
backendName: "webgl",
|
|
kernelFunc: multiply
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_complex_gpu":"3sjSC","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","../kernel_utils/shared":"e4M7v","./Complex":"55NfL","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3sjSC":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "COMPLEX_MULTIPLY", ()=>COMPLEX_MULTIPLY);
|
|
parcelHelpers.export(exports, "BinaryOpComplexProgram", ()=>BinaryOpComplexProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const COMPLEX_MULTIPLY = {
|
|
REAL: "return areal * breal - aimag * bimag;",
|
|
IMAG: "return areal * bimag + aimag * breal;"
|
|
};
|
|
class BinaryOpComplexProgram {
|
|
constructor(op, aShape, bShape){
|
|
this.variableNames = [
|
|
"AReal",
|
|
"AImag",
|
|
"BReal",
|
|
"BImag"
|
|
];
|
|
this.outputShape = (0, _tfjsCore.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));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fgZen":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reshape", ()=>reshape);
|
|
parcelHelpers.export(exports, "reshapeConfig", ()=>reshapeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reshape = require("../kernel_utils/reshape");
|
|
var _webglUtil = require("../webgl_util");
|
|
function reshape(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { shape } = attrs;
|
|
const webglBackend = backend;
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const $shape = (0, _tfjsCore.util).inferFromImplicitShape(shape, xSize);
|
|
const $xSize = (0, _tfjsCore.util).sizeFromShape($shape);
|
|
(0, _tfjsCore.util).assert(xSize === $xSize, ()=>`The new shape (${$shape}) has ${$xSize} elements and the old ` + `shape (${x.shape}) has ${xSize} elements. The new shape and old ` + `shape must have the same number of elements.`);
|
|
const xTexData = webglBackend.texData.get(x.dataId);
|
|
if (xTexData.isPacked && !(0, _webglUtil.isReshapeFree)(x.shape, $shape) && !(xTexData.texture !== null && (0, _webglUtil.isReshapeFree)(xTexData.shape, $shape))) return (0, _reshape.packedReshape)(x, $shape, webglBackend);
|
|
webglBackend.incRef(x.dataId);
|
|
return {
|
|
dataId: x.dataId,
|
|
shape: $shape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
const reshapeConfig = {
|
|
kernelName: (0, _tfjsCore.Reshape),
|
|
backendName: "webgl",
|
|
kernelFunc: reshape
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/reshape":"jLTQF","../webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jLTQF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "packedReshape", ()=>packedReshape);
|
|
var _reshapePackedGpu = require("../reshape_packed_gpu");
|
|
var _webglUtil = require("../webgl_util");
|
|
function packedReshape(input, afterShape, backend) {
|
|
const input3DShape = [
|
|
(0, _webglUtil.getBatchDim)(input.shape),
|
|
...(0, _webglUtil.getRowsCols)(input.shape)
|
|
];
|
|
const input3D = {
|
|
dtype: input.dtype,
|
|
shape: input3DShape,
|
|
dataId: input.dataId
|
|
};
|
|
const afterShapeAs3D = [
|
|
(0, _webglUtil.getBatchDim)(afterShape),
|
|
...(0, _webglUtil.getRowsCols)(afterShape)
|
|
];
|
|
const program = new (0, _reshapePackedGpu.ReshapePackedProgram)(afterShapeAs3D, input3DShape);
|
|
const preventEagerUnpackingOfOutput = true;
|
|
const customValues = [
|
|
input3DShape
|
|
];
|
|
const output = backend.runWebGLProgram(program, [
|
|
input3D
|
|
], input.dtype, customValues, preventEagerUnpackingOfOutput);
|
|
return {
|
|
dataId: output.dataId,
|
|
shape: afterShape,
|
|
dtype: output.dtype
|
|
};
|
|
}
|
|
|
|
},{"../reshape_packed_gpu":"6lTtb","../webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c4eiD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sum", ()=>sum);
|
|
parcelHelpers.export(exports, "sumConfig", ()=>sumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _sumImpl = require("./Sum_impl");
|
|
function sum(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
return (0, _sumImpl.sumImpl)(x, axis, keepDims, backend);
|
|
}
|
|
const sumConfig = {
|
|
kernelName: (0, _tfjsCore.Sum),
|
|
backendName: "webgl",
|
|
kernelFunc: sum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Sum_impl":"jJiik","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jJiik":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sumImpl", ()=>sumImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reduce = require("../kernel_utils/reduce");
|
|
var _reshape = require("./Reshape");
|
|
var _transposeImpl = require("./Transpose_impl");
|
|
function sumImpl(x, axis, keepDims, backend) {
|
|
const reductionIndices = axis;
|
|
const xRank = x.shape.length;
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(reductionIndices, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
const sumInputIsTransposed = permutedAxes != null;
|
|
let sumInput = x;
|
|
if (sumInputIsTransposed) {
|
|
sumInput = (0, _transposeImpl.transposeImpl)(x, permutedAxes, backend);
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, xRank);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("sum", axes, xRank);
|
|
const [sumOutShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(sumInput.shape, axes);
|
|
let outShape = sumOutShape;
|
|
if (keepDims) // rather than reshape at the end, set the target shape here.
|
|
outShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(sumOutShape, origAxes);
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const batchSize = xSize / inSize;
|
|
const reshapedInput = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: sumInput
|
|
},
|
|
attrs: {
|
|
shape: [
|
|
batchSize,
|
|
inSize
|
|
]
|
|
},
|
|
backend
|
|
});
|
|
const outType = (0, _tfjsCore.sumOutType)(x.dtype);
|
|
const reduced = (0, _reduce.reduce)(reshapedInput, outType, "sum", backend);
|
|
const out = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
attrs: {
|
|
shape: outShape
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(reshapedInput);
|
|
backend.disposeIntermediateTensorInfo(reduced);
|
|
if (sumInputIsTransposed) backend.disposeIntermediateTensorInfo(sumInput);
|
|
return out;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/reduce":"dr0Xl","./Reshape":"fgZen","./Transpose_impl":"arYj9","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dr0Xl":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reduce", ()=>reduce);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _meanGpu = require("../mean_gpu");
|
|
var _reduceGpu = require("../reduce_gpu");
|
|
// Returns an array of configuration objects that describe each stage of the
|
|
// reduction.
|
|
function getReductionStages(inShape) {
|
|
const stages = [];
|
|
while(stages.length === 0 || stages[stages.length - 1].outSize !== 1){
|
|
const outSize = stages.length ? stages[stages.length - 1].outSize : inShape[1];
|
|
const windowSize = (0, _tfjsCore.backend_util).computeOptimalWindowSize(outSize);
|
|
stages.push({
|
|
inSize: outSize,
|
|
windowSize,
|
|
outSize: Math.ceil(outSize / windowSize)
|
|
});
|
|
}
|
|
return stages;
|
|
}
|
|
function reduce(x, dtype, reductionType, backend) {
|
|
const reductionStages = getReductionStages(x.shape);
|
|
let result = x;
|
|
for(let i = 0; i < reductionStages.length; i++){
|
|
const { inSize, windowSize, outSize } = reductionStages[i];
|
|
let program;
|
|
let previousResult;
|
|
if (reductionType === "mean") program = i === 0 ? new (0, _meanGpu.MeanProgram)({
|
|
windowSize,
|
|
inSize,
|
|
batchSize: x.shape[0],
|
|
outSize
|
|
}, inSize) : new (0, _meanGpu.MeanProgram)({
|
|
windowSize,
|
|
inSize,
|
|
batchSize: x.shape[0],
|
|
outSize
|
|
});
|
|
else program = new (0, _reduceGpu.ReduceProgram)({
|
|
windowSize,
|
|
inSize,
|
|
batchSize: x.shape[0],
|
|
outSize
|
|
}, reductionType);
|
|
previousResult = result;
|
|
result = backend.runWebGLProgram(program, [
|
|
result
|
|
], dtype);
|
|
if (previousResult.dataId !== x.dataId) backend.disposeIntermediateTensorInfo(previousResult);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../mean_gpu":"gMZwh","../reduce_gpu":"kqmxI","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gMZwh":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MeanProgram", ()=>MeanProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
class MeanProgram {
|
|
constructor(reduceInfo, divisor){
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
const { windowSize, batchSize, inSize, outSize } = reduceInfo;
|
|
this.outputShape = [
|
|
batchSize,
|
|
outSize
|
|
];
|
|
const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
|
|
const windowSizeVec4Remainder = windowSize % 4;
|
|
let updateSnippet = `sumValue += dot(values, ones);`;
|
|
if (divisor != null) {
|
|
const denominator = 1 / divisor;
|
|
updateSnippet = `sumValue += dot(values * ${(0, _tfjsCore.util).isInt(denominator) ? denominator.toPrecision(2) : denominator}, ones);`;
|
|
}
|
|
let checkOutOfBounds = "";
|
|
if (inSize % windowSize > 0) checkOutOfBounds = `
|
|
if (inIdx < 0 || inIdx >= ${inSize}) {
|
|
return 0.0;
|
|
}
|
|
`;
|
|
this.userCode = `
|
|
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};
|
|
|
|
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)
|
|
);
|
|
|
|
${updateSnippet}
|
|
}
|
|
|
|
int inIdx = inOffset + ${windowSizeNearestVec4};
|
|
if (${windowSizeVec4Remainder === 1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${updateSnippet}
|
|
} else if (${windowSizeVec4Remainder === 2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${updateSnippet}
|
|
} else if (${windowSizeVec4Remainder === 3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${updateSnippet}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kqmxI":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ReduceProgram", ()=>ReduceProgram);
|
|
class ReduceProgram {
|
|
constructor(reduceInfo, reduceType){
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
const { windowSize, batchSize, inSize, outSize } = reduceInfo;
|
|
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);
|
|
if (${reduceType === "min"} || ${reduceType === "max"}) {
|
|
minMaxValue = ${compareOp}(values, minMaxValue);
|
|
bvec4 isNaN = isnan(values);
|
|
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
|
|
minMaxValue = vec4(NAN);
|
|
}
|
|
}
|
|
}
|
|
`;
|
|
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});
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"arYj9":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "transposeImpl", ()=>transposeImpl);
|
|
parcelHelpers.export(exports, "transposeImplCPU", ()=>(0, _shared.transposeImplCPU));
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _transposeGpu = require("../transpose_gpu");
|
|
var _transposePackedGpu = require("../transpose_packed_gpu");
|
|
function transposeImpl(x, perm, backend) {
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new (0, _transposePackedGpu.TransposePackedProgram)(x.shape, perm) : new (0, _transposeGpu.TransposeProgram)(x.shape, perm);
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../transpose_gpu":"ejy1h","../transpose_packed_gpu":"bN4zV","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ejy1h":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "TransposeProgram", ()=>TransposeProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class 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 = (0, _shaderCompiler.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();
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bN4zV":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "TransposePackedProgram", ()=>TransposePackedProgram);
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class 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 = (0, _shaderCompiler.getCoordsDataType)(this.rank);
|
|
const outputOrder = (0, _packingUtil.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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cKJAC":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "transpose", ()=>transpose);
|
|
parcelHelpers.export(exports, "transposeConfig", ()=>transposeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _transposeImpl = require("./Transpose_impl");
|
|
function transpose(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
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 = (0, _transposeImpl.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 = (0, _transposeImpl.transposeImpl)(x, perm, webglBackend);
|
|
return out;
|
|
}
|
|
const transposeConfig = {
|
|
kernelName: (0, _tfjsCore.Transpose),
|
|
backendName: "webgl",
|
|
kernelFunc: transpose
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Transpose_impl":"arYj9","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5sWXh":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "abs", ()=>abs);
|
|
parcelHelpers.export(exports, "absConfig", ()=>absConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
var _unaryopPackedGpu = require("../unaryop_packed_gpu");
|
|
const ABS = `return abs(x);`;
|
|
function abs(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
// TODO: handle cases when x is complex. Once the cpu implementation
|
|
// can handle complex values, refactor to use unaryKernelFunc.
|
|
if (backend.shouldExecuteOnCPU([
|
|
x
|
|
]) && x.dtype !== "complex64") {
|
|
const xData = backend.texData.get(x.dataId);
|
|
const outValues = (0, _shared.simpleAbsImplCPU)(xData.values);
|
|
return backend.makeTensorInfo(x.shape, x.dtype, outValues);
|
|
}
|
|
let program;
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_PACK_UNARY_OPERATIONS")) program = new (0, _unaryopPackedGpu.UnaryOpPackedProgram)(x.shape, ABS);
|
|
else program = new (0, _unaryopGpu.UnaryOpProgram)(x.shape, ABS);
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
const absConfig = {
|
|
kernelName: (0, _tfjsCore.Abs),
|
|
backendName: "webgl",
|
|
kernelFunc: abs
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../unaryop_gpu":"gIMrR","../unaryop_packed_gpu":"c4D5K","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"88j8R":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "acos", ()=>acos);
|
|
parcelHelpers.export(exports, "acosConfig", ()=>acosConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const ACOS = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`;
|
|
const acos = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ACOS
|
|
});
|
|
const acosConfig = {
|
|
kernelName: (0, _tfjsCore.Acos),
|
|
backendName: "webgl",
|
|
kernelFunc: acos
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3MqlI":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "acosh", ()=>acosh);
|
|
parcelHelpers.export(exports, "acoshConfig", ()=>acoshConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const ACOSH = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`;
|
|
const acosh = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ACOSH
|
|
});
|
|
const acoshConfig = {
|
|
kernelName: (0, _tfjsCore.Acosh),
|
|
backendName: "webgl",
|
|
kernelFunc: acosh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iCeMO":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "addKernelFunc", ()=>addKernelFunc);
|
|
parcelHelpers.export(exports, "addConfig", ()=>addConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const ADD = "return a + b;";
|
|
const addKernelFunc = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: ADD,
|
|
packedOpSnippet: ADD,
|
|
supportsComplex: true,
|
|
cpuKernelImpl: (0, _shared.addImplCPU)
|
|
});
|
|
const addConfig = {
|
|
kernelName: (0, _tfjsCore.Add),
|
|
backendName: "webgl",
|
|
kernelFunc: addKernelFunc
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"inami":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "addN", ()=>addN);
|
|
parcelHelpers.export(exports, "addNConfig", ()=>addNConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _addnGpu = require("../addn_gpu");
|
|
var _addnPackedGpu = require("../addn_packed_gpu");
|
|
var _identity = require("./Identity");
|
|
function addN(args) {
|
|
const { inputs, backend } = args;
|
|
const tensors = inputs;
|
|
if (tensors.length === 1) return (0, _identity.identity)({
|
|
inputs: {
|
|
x: tensors[0]
|
|
},
|
|
backend
|
|
});
|
|
// Limit the number of uploaded textures for optimization.
|
|
if (tensors.length > (0, _tfjsCore.env)().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")) {
|
|
const midIndex = Math.floor(tensors.length / 2);
|
|
const leftSide = addN({
|
|
inputs: tensors.slice(0, midIndex),
|
|
backend
|
|
});
|
|
const rightSide = addN({
|
|
inputs: tensors.slice(midIndex),
|
|
backend
|
|
});
|
|
return addN({
|
|
inputs: [
|
|
leftSide,
|
|
rightSide
|
|
],
|
|
backend
|
|
});
|
|
}
|
|
const dtype = tensors.map((t)=>t.dtype).reduce((d1, d2)=>(0, _tfjsCore.upcastType)(d1, d2));
|
|
const shapes = tensors.map((t)=>t.shape);
|
|
// We can make sure shapes are identical in op level.
|
|
const usePackedOp = (0, _tfjsCore.env)().getBool("WEBGL_PACK");
|
|
const program = usePackedOp ? new (0, _addnPackedGpu.AddNPackedProgram)(tensors[0].shape, shapes) : new (0, _addnGpu.AddNProgram)(tensors[0].shape, shapes);
|
|
return backend.runWebGLProgram(program, tensors, dtype);
|
|
}
|
|
const addNConfig = {
|
|
kernelName: (0, _tfjsCore.AddN),
|
|
backendName: "webgl",
|
|
kernelFunc: addN
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../addn_gpu":"jJYUj","../addn_packed_gpu":"96PNN","./Identity":"hY9aT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jJYUj":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "AddNProgram", ()=>AddNProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"96PNN":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "AddNPackedProgram", ()=>AddNPackedProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8QrzY":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "all", ()=>all);
|
|
parcelHelpers.export(exports, "allConfig", ()=>allConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reduce = require("../kernel_utils/reduce");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function all(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
const xRank = x.shape.length;
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
let permutedX = x;
|
|
if (permutedAxes != null) {
|
|
permutedX = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, xRank);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("all", axes, xRank);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(permutedX.shape, axes);
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const a2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: permutedX
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
-1,
|
|
inSize
|
|
]
|
|
}
|
|
});
|
|
const reduced = (0, _reduce.reduce)(a2D, a2D.dtype, "all", backend);
|
|
let res;
|
|
if (keepDims) {
|
|
const newShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(outShape, origAxes);
|
|
res = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: newShape
|
|
}
|
|
});
|
|
} else res = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(a2D);
|
|
backend.disposeIntermediateTensorInfo(reduced);
|
|
if (permutedAxes != null) backend.disposeIntermediateTensorInfo(permutedX);
|
|
return res;
|
|
}
|
|
const allConfig = {
|
|
kernelName: (0, _tfjsCore.All),
|
|
backendName: "webgl",
|
|
kernelFunc: all
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/reduce":"dr0Xl","./Reshape":"fgZen","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cNRuv":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "any", ()=>any);
|
|
parcelHelpers.export(exports, "anyConfig", ()=>anyConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reduce = require("../kernel_utils/reduce");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function any(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
const xRank = x.shape.length;
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
let permutedX = x;
|
|
if (permutedAxes != null) {
|
|
permutedX = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, xRank);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("any", axes, xRank);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(permutedX.shape, axes);
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const a2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: permutedX
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
-1,
|
|
inSize
|
|
]
|
|
}
|
|
});
|
|
const reduced = (0, _reduce.reduce)(a2D, a2D.dtype, "any", backend);
|
|
let res;
|
|
if (keepDims) {
|
|
const newShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(outShape, origAxes);
|
|
res = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: newShape
|
|
}
|
|
});
|
|
} else res = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(a2D);
|
|
backend.disposeIntermediateTensorInfo(reduced);
|
|
if (permutedAxes != null) backend.disposeIntermediateTensorInfo(permutedX);
|
|
return res;
|
|
}
|
|
const anyConfig = {
|
|
kernelName: (0, _tfjsCore.Any),
|
|
backendName: "webgl",
|
|
kernelFunc: any
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/reduce":"dr0Xl","./Reshape":"fgZen","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cxDNq":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "argMax", ()=>argMax);
|
|
parcelHelpers.export(exports, "argMaxConfig", ()=>argMaxConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _argMinMax = require("../kernel_utils/arg_min_max");
|
|
var _transpose = require("./Transpose");
|
|
function argMax(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis } = attrs;
|
|
let axes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, x.shape.length);
|
|
let $x = x;
|
|
const intermediateTensorInfos = [];
|
|
if (permutedAxes != null) {
|
|
$x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
intermediateTensorInfos.push($x);
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, $x.shape.length);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("argMax", [
|
|
axes[0]
|
|
], $x.shape.length);
|
|
const out = (0, _argMinMax.argMinMaxReduce)(backend, $x, axes[0], "max");
|
|
intermediateTensorInfos.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return out;
|
|
}
|
|
const argMaxConfig = {
|
|
kernelName: (0, _tfjsCore.ArgMax),
|
|
backendName: "webgl",
|
|
kernelFunc: argMax
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/arg_min_max":"1rsTF","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1rsTF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "argMinMaxReduce", ()=>argMinMaxReduce);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _argminmaxGpu = require("../argminmax_gpu");
|
|
var _argminmaxPackedGpu = require("../argminmax_packed_gpu");
|
|
var _reshape = require("../kernels/Reshape");
|
|
function argReduce(backend, 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 = (0, _tfjsCore.backend_util).computeOptimalWindowSize(inSize);
|
|
const reduceInfo = {
|
|
windowSize,
|
|
inSize,
|
|
batchSize,
|
|
outSize: Math.ceil(inSize / windowSize)
|
|
};
|
|
const program = new (0, _argminmaxGpu.ArgMinMaxProgram)(reduceInfo, reduceType, bestIndicesA == null);
|
|
const inputs = [
|
|
x
|
|
];
|
|
if (bestIndicesA != null) inputs.push(bestIndicesA);
|
|
const output = backend.runWebGLProgram(program, inputs, "int32");
|
|
// No need to run another GPGPU program.
|
|
if (output.shape[1] === 1) return output;
|
|
const result = argReduce(backend, x, reduceType, output);
|
|
backend.disposeIntermediateTensorInfo(output);
|
|
return result;
|
|
}
|
|
function argReducePacked(backend, x, reduceType, bestIndicesA = null) {
|
|
const inShape = bestIndicesA != null ? bestIndicesA.shape : x.shape;
|
|
const inSize = inShape[inShape.length - 1];
|
|
const windowSize = (0, _tfjsCore.backend_util).computeOptimalWindowSize(inSize);
|
|
const program = new (0, _argminmaxPackedGpu.ArgMinMaxPackedProgram)(inShape, windowSize, reduceType, bestIndicesA == null);
|
|
const inputs = bestIndicesA == null ? [
|
|
x
|
|
] : [
|
|
x,
|
|
bestIndicesA
|
|
];
|
|
const output = backend.runWebGLProgram(program, inputs, "int32");
|
|
if (output.shape.length === x.shape.length) {
|
|
const result = argReducePacked(backend, x, reduceType, output);
|
|
backend.disposeIntermediateTensorInfo(output);
|
|
return result;
|
|
}
|
|
return output;
|
|
}
|
|
function argMinMaxReduce(backend, x, axis, reduceType) {
|
|
const axes = [
|
|
axis
|
|
];
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("arg" + reduceType.charAt(0).toUpperCase() + reduceType.slice(1), axes, x.shape.length);
|
|
if (!(0, _tfjsCore.env)().getBool("WEBGL_PACK_REDUCE") || x.shape.length <= 2) {
|
|
const intermediateTensorInfos = [];
|
|
// Eagerly unpack x input since it is passed in to all the shaders which
|
|
// require unpacked inputs.
|
|
const xtexData = backend.texData.get(x.dataId);
|
|
const xIsPacked = xtexData !== null && xtexData.isPacked;
|
|
let xUnPacked = x;
|
|
if (xIsPacked) {
|
|
xUnPacked = backend.unpackTensor(x);
|
|
intermediateTensorInfos.push(xUnPacked);
|
|
}
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(xUnPacked.shape, axes);
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const a2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: xUnPacked
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
-1,
|
|
inSize
|
|
]
|
|
}
|
|
});
|
|
intermediateTensorInfos.push(a2D);
|
|
const reduced = argReduce(backend, a2D, reduceType);
|
|
intermediateTensorInfos.push(reduced);
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
intermediateTensorInfos.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return reshaped;
|
|
}
|
|
return argReducePacked(backend, x, reduceType);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../argminmax_gpu":"7Vig3","../argminmax_packed_gpu":"1fu9z","../kernels/Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7Vig3":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ArgMinMaxProgram", ()=>ArgMinMaxProgram);
|
|
class ArgMinMaxProgram {
|
|
constructor(reduceInfo, op, firstPass){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
const { windowSize, batchSize, outSize } = reduceInfo;
|
|
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));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1fu9z":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ArgMinMaxPackedProgram", ()=>ArgMinMaxPackedProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class ArgMinMaxPackedProgram {
|
|
constructor(shape, windowSize, op, firstPass){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
(0, _tfjsCore.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 = (0, _shaderCompiler.getCoordsDataType)(rank);
|
|
const coords = (0, _packingUtil.getChannels)("coords", rank);
|
|
let sourceLocSetup;
|
|
let sourceRank;
|
|
if (outSize === 1) {
|
|
sourceRank = rank + 1;
|
|
const sourceLocDType = (0, _shaderCompiler.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 = (0, _packingUtil.getChannels)("sourceLocR", sourceRank - 1).concat("inIdx.r");
|
|
const srcGCoords = (0, _packingUtil.getChannels)("sourceLocG", sourceRank - 1).concat("inIdx.g");
|
|
const srcBCoords = (0, _packingUtil.getChannels)("sourceLocB", sourceRank - 1).concat("inIdx.b");
|
|
const srcACoords = (0, _packingUtil.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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7we0s":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "argMin", ()=>argMin);
|
|
parcelHelpers.export(exports, "argMinConfig", ()=>argMinConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _argMinMax = require("../kernel_utils/arg_min_max");
|
|
var _transpose = require("./Transpose");
|
|
function argMin(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis } = attrs;
|
|
let axes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, x.shape.length);
|
|
let $x = x;
|
|
const intermediateTensorInfos = [];
|
|
if (permutedAxes != null) {
|
|
$x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
intermediateTensorInfos.push($x);
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, $x.shape.length);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("argMin", [
|
|
axes[0]
|
|
], $x.shape.length);
|
|
const out = (0, _argMinMax.argMinMaxReduce)(backend, $x, axes[0], "min");
|
|
intermediateTensorInfos.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return out;
|
|
}
|
|
const argMinConfig = {
|
|
kernelName: (0, _tfjsCore.ArgMin),
|
|
backendName: "webgl",
|
|
kernelFunc: argMin
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/arg_min_max":"1rsTF","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2y04O":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "asin", ()=>asin);
|
|
parcelHelpers.export(exports, "asinConfig", ()=>asinConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const ASIN = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`;
|
|
const asin = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ASIN
|
|
});
|
|
const asinConfig = {
|
|
kernelName: (0, _tfjsCore.Asin),
|
|
backendName: "webgl",
|
|
kernelFunc: asin
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8uUU0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "asinh", ()=>asinh);
|
|
parcelHelpers.export(exports, "asinhConfig", ()=>asinhConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const ASINH = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `return log(x + sqrt(x * x + 1.0));`;
|
|
const asinh = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ASINH
|
|
});
|
|
const asinhConfig = {
|
|
kernelName: (0, _tfjsCore.Asinh),
|
|
backendName: "webgl",
|
|
kernelFunc: asinh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hh4aJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atan", ()=>atan);
|
|
parcelHelpers.export(exports, "atanConfig", ()=>atanConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const ATAN = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
return atan(x);
|
|
`;
|
|
const atan = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ATAN
|
|
});
|
|
const atanConfig = {
|
|
kernelName: (0, _tfjsCore.Atan),
|
|
backendName: "webgl",
|
|
kernelFunc: atan
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"k9THK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atan2", ()=>atan2);
|
|
parcelHelpers.export(exports, "atan2Config", ()=>atan2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const ATAN2 = (0, _binaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
return atan(a, b);
|
|
`;
|
|
const ATAN2_PACKED = `
|
|
vec4 result = atan(a, b);
|
|
bvec4 isNaNA = isnan(a);
|
|
bvec4 isNaNB = isnan(b);
|
|
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
|
|
` + (0, _binaryopPackedGpu.CHECK_NAN_SNIPPET_PACKED) + `
|
|
return result;
|
|
`;
|
|
const atan2 = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: ATAN2,
|
|
packedOpSnippet: ATAN2_PACKED
|
|
});
|
|
const atan2Config = {
|
|
kernelName: (0, _tfjsCore.Atan2),
|
|
backendName: "webgl",
|
|
kernelFunc: atan2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3axXM":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atanh", ()=>atanh);
|
|
parcelHelpers.export(exports, "atanhConfig", ()=>atanhConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const ATANH = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`;
|
|
const atanh = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ATANH
|
|
});
|
|
const atanhConfig = {
|
|
kernelName: (0, _tfjsCore.Atanh),
|
|
backendName: "webgl",
|
|
kernelFunc: atanh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iU9nc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPool", ()=>avgPool);
|
|
parcelHelpers.export(exports, "avgPoolConfig", ()=>avgPoolConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _poolGpu = require("../pool_gpu");
|
|
var _webglUtil = require("../webgl_util");
|
|
var _identity = require("./Identity");
|
|
function avgPool(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
(0, _webglUtil.assertNotComplex)(x, "avgPool");
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
const dilations = 1;
|
|
(0, _tfjsCore.util).assert((0, _tfjsCore.backend_util).eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in avgPool: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
|
|
if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 && (0, _tfjsCore.util).arraysEqual(convInfo.inShape, convInfo.outShape)) return (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
const avgPoolProgram = new (0, _poolGpu.Pool2DProgram)(convInfo, "avg", false);
|
|
return backend.runWebGLProgram(avgPoolProgram, [
|
|
x
|
|
], "float32");
|
|
}
|
|
const avgPoolConfig = {
|
|
kernelName: (0, _tfjsCore.AvgPool),
|
|
backendName: "webgl",
|
|
kernelFunc: avgPool
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../pool_gpu":"b1t1V","../webgl_util":"fjf7t","./Identity":"hY9aT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b1t1V":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Pool2DProgram", ()=>Pool2DProgram);
|
|
parcelHelpers.export(exports, "Pool3DProgram", ()=>Pool3DProgram);
|
|
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 / max(count, 1.0)`;
|
|
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") // Use `max(count, 1.0)` instead of `count` in case count === 0.0.
|
|
// If count === 0.0, `avgValue` is always 0.0 and we change `count`'s
|
|
// value to avoid dividing zero.
|
|
returnValue = `avgValue / max(count, 1.0)`;
|
|
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});
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dFK3l":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPool3D", ()=>avgPool3D);
|
|
parcelHelpers.export(exports, "avgPool3DConfig", ()=>avgPool3DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _poolGpu = require("../pool_gpu");
|
|
function avgPool3D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { filterSize, strides, pad, dimRoundingMode, dataFormat } = attrs;
|
|
const dilations = [
|
|
1,
|
|
1,
|
|
1
|
|
];
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode, dataFormat);
|
|
const avgPoolProgram = new (0, _poolGpu.Pool3DProgram)(convInfo, "avg", false);
|
|
return backend.runWebGLProgram(avgPoolProgram, [
|
|
x
|
|
], "float32");
|
|
}
|
|
const avgPool3DConfig = {
|
|
kernelName: (0, _tfjsCore.AvgPool3D),
|
|
backendName: "webgl",
|
|
kernelFunc: avgPool3D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../pool_gpu":"b1t1V","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kSFm4":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPool3DGrad", ()=>avgPool3DGrad);
|
|
parcelHelpers.export(exports, "avgPool3DGradConfig", ()=>avgPool3DGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _avgPoolBackpropGpu = require("../avg_pool_backprop_gpu");
|
|
function avgPool3DGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, input } = inputs;
|
|
const x = input;
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
const dilations = [
|
|
1,
|
|
1,
|
|
1
|
|
];
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
|
|
const avgPoolBackpropProgram = new (0, _avgPoolBackpropGpu.AvgPool3DBackpropProgram)(convInfo);
|
|
return backend.runWebGLProgram(avgPoolBackpropProgram, [
|
|
dy
|
|
], x.dtype);
|
|
}
|
|
const avgPool3DGradConfig = {
|
|
kernelName: (0, _tfjsCore.AvgPool3DGrad),
|
|
backendName: "webgl",
|
|
kernelFunc: avgPool3DGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../avg_pool_backprop_gpu":"6KYh8","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6KYh8":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "AvgPool2DBackpropProgram", ()=>AvgPool2DBackpropProgram);
|
|
parcelHelpers.export(exports, "AvgPool3DBackpropProgram", ()=>AvgPool3DBackpropProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dwrYJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPoolGrad", ()=>avgPoolGrad);
|
|
parcelHelpers.export(exports, "avgPoolGradConfig", ()=>avgPoolGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _avgPoolBackpropGpu = require("../avg_pool_backprop_gpu");
|
|
var _webglUtil = require("../webgl_util");
|
|
function avgPoolGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, input } = inputs;
|
|
const x = input;
|
|
(0, _webglUtil.assertNotComplex)([
|
|
dy,
|
|
input
|
|
], "avgPoolGrad");
|
|
const { filterSize, strides, pad } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, 1 /* dilations */ , pad);
|
|
const avgPoolBackpropProgram = new (0, _avgPoolBackpropGpu.AvgPool2DBackpropProgram)(convInfo);
|
|
return backend.runWebGLProgram(avgPoolBackpropProgram, [
|
|
dy
|
|
], x.dtype);
|
|
}
|
|
const avgPoolGradConfig = {
|
|
kernelName: (0, _tfjsCore.AvgPoolGrad),
|
|
backendName: "webgl",
|
|
kernelFunc: avgPoolGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../avg_pool_backprop_gpu":"6KYh8","../webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9tzUH":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchMatMul", ()=>batchMatMul);
|
|
parcelHelpers.export(exports, "batchMatMulConfig", ()=>batchMatMulConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _batchMatMulImpl = require("./BatchMatMul_impl");
|
|
function batchMatMul(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { a, b } = inputs;
|
|
const { transposeA, transposeB } = attrs;
|
|
return (0, _batchMatMulImpl.batchMatMulImpl)({
|
|
a,
|
|
b,
|
|
transposeA,
|
|
transposeB,
|
|
backend
|
|
});
|
|
}
|
|
const batchMatMulConfig = {
|
|
kernelName: (0, _tfjsCore.BatchMatMul),
|
|
backendName: "webgl",
|
|
kernelFunc: batchMatMul
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./BatchMatMul_impl":"kyEQG","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2u2bT":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchNorm", ()=>batchNorm);
|
|
parcelHelpers.export(exports, "batchNormConfig", ()=>batchNormConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _batchnormGpu = require("../batchnorm_gpu");
|
|
var _batchnormPackedGpu = require("../batchnorm_packed_gpu");
|
|
const batchNorm = ({ inputs, backend, attrs })=>{
|
|
const { x, mean, variance, offset, scale } = inputs;
|
|
(0, _tfjsCore.util).assert(mean.shape.length === variance.shape.length, ()=>"Batch normalization gradient requires mean and variance to have equal ranks.");
|
|
(0, _tfjsCore.util).assert(offset == null || mean.shape.length === offset.shape.length, ()=>"Batch normalization gradient requires mean and offset to have equal ranks.");
|
|
(0, _tfjsCore.util).assert(scale == null || mean.shape.length === scale.shape.length, ()=>"Batch normalization gradient requires mean and scale to have equal ranks.");
|
|
let { varianceEpsilon } = attrs;
|
|
if (varianceEpsilon == null) varianceEpsilon = 0.001;
|
|
const finalInputs = [
|
|
x,
|
|
mean,
|
|
variance
|
|
];
|
|
let offsetShape = null;
|
|
if (offset != null) {
|
|
offsetShape = offset.shape;
|
|
finalInputs.push(offset);
|
|
}
|
|
let scaleShape = null;
|
|
if (scale != null) {
|
|
scaleShape = scale.shape;
|
|
finalInputs.push(scale);
|
|
}
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_NORMALIZATION") ? new (0, _batchnormPackedGpu.BatchNormPackedProgram)(x.shape, mean.shape, variance.shape, offsetShape, scaleShape, varianceEpsilon) : new (0, _batchnormGpu.BatchNormProgram)(x.shape, mean.shape, variance.shape, offsetShape, scaleShape, varianceEpsilon);
|
|
const output = backend.runWebGLProgram(program, finalInputs, finalInputs[0].dtype);
|
|
return output;
|
|
};
|
|
const batchNormConfig = {
|
|
kernelName: (0, _tfjsCore.FusedBatchNorm),
|
|
backendName: "webgl",
|
|
kernelFunc: batchNorm
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../batchnorm_gpu":"bs6T4","../batchnorm_packed_gpu":"eFA7W","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bs6T4":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "BatchNormProgram", ()=>BatchNormProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
class BatchNormProgram {
|
|
constructor(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon){
|
|
this.outputShape = [];
|
|
this.variableNames = [
|
|
"x",
|
|
"mean",
|
|
"variance"
|
|
];
|
|
(0, _tfjsCore.backend_util).assertAndGetBroadcastShape(xShape, meanShape);
|
|
(0, _tfjsCore.backend_util).assertAndGetBroadcastShape(xShape, varianceShape);
|
|
let offsetSnippet = "0.0";
|
|
if (offsetShape != null) {
|
|
(0, _tfjsCore.backend_util).assertAndGetBroadcastShape(xShape, offsetShape);
|
|
this.variableNames.push("offset");
|
|
offsetSnippet = "getOffsetAtOutCoords()";
|
|
}
|
|
let scaleSnippet = "1.0";
|
|
if (scaleShape != null) {
|
|
(0, _tfjsCore.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)));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eFA7W":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "BatchNormPackedProgram", ()=>BatchNormPackedProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
class BatchNormPackedProgram {
|
|
constructor(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon){
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.variableNames = [
|
|
"x",
|
|
"mean",
|
|
"variance"
|
|
];
|
|
(0, _tfjsCore.backend_util).assertAndGetBroadcastShape(xShape, meanShape);
|
|
(0, _tfjsCore.backend_util).assertAndGetBroadcastShape(xShape, varianceShape);
|
|
let offsetSnippet = "vec4(0.0)";
|
|
if (offsetShape != null) {
|
|
(0, _tfjsCore.backend_util).assertAndGetBroadcastShape(xShape, offsetShape);
|
|
this.variableNames.push("offset");
|
|
offsetSnippet = "getOffsetAtOutCoords()";
|
|
}
|
|
let scaleSnippet = "vec4(1.0)";
|
|
if (scaleShape != null) {
|
|
(0, _tfjsCore.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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bsQ5u":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchToSpaceND", ()=>batchToSpaceND);
|
|
parcelHelpers.export(exports, "batchToSpaceNDConfig", ()=>batchToSpaceNDConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reshape = require("./Reshape");
|
|
var _slice = require("./Slice");
|
|
var _transpose = require("./Transpose");
|
|
const batchToSpaceND = (args)=>{
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { blockShape, crops } = attrs;
|
|
(0, _tfjsCore.util).assert(x.shape.length <= 4, ()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");
|
|
const prod = blockShape.reduce((a, b)=>a * b);
|
|
const reshaped = (0, _tfjsCore.backend_util).getReshaped(x.shape, blockShape, prod);
|
|
const permuted = (0, _tfjsCore.backend_util).getPermuted(reshaped.length, blockShape.length);
|
|
const reshapedPermuted = (0, _tfjsCore.backend_util).getReshapedPermuted(x.shape, blockShape, prod);
|
|
const sliceBeginCoords = (0, _tfjsCore.backend_util).getSliceBeginCoords(crops, blockShape.length);
|
|
const sliceSize = (0, _tfjsCore.backend_util).getSliceSize(reshapedPermuted, crops, blockShape.length);
|
|
const toDispose = [];
|
|
const reshapedIntermediate = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: reshaped
|
|
}
|
|
});
|
|
const transposedIntermediate = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: reshapedIntermediate
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permuted
|
|
}
|
|
});
|
|
const reshapedIntermediate2 = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: transposedIntermediate
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: reshapedPermuted
|
|
}
|
|
});
|
|
const sliced = (0, _slice.slice)({
|
|
inputs: {
|
|
x: reshapedIntermediate2
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin: sliceBeginCoords,
|
|
size: sliceSize
|
|
}
|
|
});
|
|
toDispose.push(reshapedIntermediate);
|
|
toDispose.push(transposedIntermediate);
|
|
toDispose.push(reshapedIntermediate2);
|
|
toDispose.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return sliced;
|
|
};
|
|
const batchToSpaceNDConfig = {
|
|
kernelName: (0, _tfjsCore.BatchToSpaceND),
|
|
backendName: "webgl",
|
|
kernelFunc: batchToSpaceND
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Reshape":"fgZen","./Slice":"6jQ29","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6jQ29":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "slice", ()=>slice);
|
|
parcelHelpers.export(exports, "sliceConfig", ()=>sliceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _sliceGpu = require("../slice_gpu");
|
|
var _slicePackedGpu = require("../slice_packed_gpu");
|
|
function shallowSlice(x, begin, size, backend) {
|
|
const xTexData = backend.texData.get(x.dataId);
|
|
const t = backend.makeTensorInfo(size, x.dtype);
|
|
const newTexData = backend.texData.get(t.dataId);
|
|
// Copy texture data from the original tensor.
|
|
Object.assign(newTexData, xTexData);
|
|
newTexData.refCount = 1;
|
|
newTexData.shape = size;
|
|
newTexData.dtype = x.dtype;
|
|
let flatOffset = (0, _tfjsCore.slice_util).computeFlatOffset(begin, (0, _tfjsCore.util).computeStrides(x.shape));
|
|
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 = backend.dataRefCount.get(newTexData.slice.origDataId) || 1;
|
|
backend.dataRefCount.set(newTexData.slice.origDataId, refCount + 1);
|
|
return t;
|
|
}
|
|
function slice(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { begin, size } = attrs;
|
|
const [$begin, $size] = (0, _tfjsCore.slice_util).parseSliceParams(x, begin, size);
|
|
(0, _tfjsCore.slice_util).assertParamsValid(x, $begin, $size);
|
|
if ((0, _tfjsCore.util).sizeFromShape($size) === 0) return backend.makeTensorInfo($size, x.dtype, []);
|
|
// Run on cpu if dtype is string. For string, the backend represents it
|
|
// as Uint8Array[], where each Uint8Array is a character. Given that the
|
|
// computation is only on the outer array, uploading the whole data onto
|
|
// gpu is wasteful. Also, currently webgl doesn't have a design to
|
|
// upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we
|
|
// just run the kernel on cpu if dtype is string.
|
|
if (backend.shouldExecuteOnCPU([
|
|
x
|
|
]) || x.dtype === "string") {
|
|
const xTexData = backend.texData.get(x.dataId);
|
|
const outValues = (0, _shared.sliceImplCPU)(xTexData.values, $begin, $size, x.shape, x.dtype);
|
|
return backend.makeTensorInfo($size, x.dtype, outValues);
|
|
}
|
|
const { isPacked } = backend.texData.get(x.dataId);
|
|
const isContinous = (0, _tfjsCore.slice_util).isSliceContinous(x.shape, $begin, $size);
|
|
if (isPacked || !isContinous) {
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new (0, _slicePackedGpu.SlicePackedProgram)($size) : new (0, _sliceGpu.SliceProgram)($size);
|
|
const customValues = [
|
|
$begin
|
|
];
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype, customValues);
|
|
}
|
|
backend.uploadToGPU(x.dataId);
|
|
return shallowSlice(x, $begin, $size, backend);
|
|
}
|
|
const sliceConfig = {
|
|
kernelName: (0, _tfjsCore.Slice),
|
|
backendName: "webgl",
|
|
kernelFunc: slice
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../slice_gpu":"5kdG6","../slice_packed_gpu":"grMHc","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5kdG6":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "SliceProgram", ()=>SliceProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class SliceProgram {
|
|
constructor(destSize){
|
|
this.variableNames = [
|
|
"source"
|
|
];
|
|
this.outputShape = destSize;
|
|
this.rank = destSize.length;
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(this.rank);
|
|
this.customUniforms = [
|
|
{
|
|
name: "start",
|
|
arrayIndex: this.rank,
|
|
type: "int"
|
|
}
|
|
];
|
|
const sourceCoords = getCoords(this.rank);
|
|
let body;
|
|
const coordSum = destSize.map((_, i)=>{
|
|
return `sourceLoc.${coords[i]} = start[${i}] + coords.${coords[i]};`;
|
|
});
|
|
body = `
|
|
${dtype} sourceLoc;
|
|
${dtype} coords = getOutputCoords();
|
|
${coordSum.join("\n")}
|
|
`;
|
|
this.userCode = `
|
|
void main() {
|
|
${body}
|
|
setOutput(getSource(${sourceCoords}));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
const coords = [
|
|
"x",
|
|
"y",
|
|
"z",
|
|
"w",
|
|
"u",
|
|
"v"
|
|
];
|
|
function getCoords(rank) {
|
|
if (rank === 1) return "sourceLoc";
|
|
else if (rank <= 6) return coords.slice(0, rank).map((x)=>"sourceLoc." + x).join(",");
|
|
else throw Error(`Slicing for rank ${rank} is not yet supported`);
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"grMHc":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "SlicePackedProgram", ()=>SlicePackedProgram);
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class SlicePackedProgram {
|
|
constructor(destSize){
|
|
this.variableNames = [
|
|
"source"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.outputShape = destSize;
|
|
this.rank = destSize.length;
|
|
this.customUniforms = [
|
|
{
|
|
name: "start",
|
|
arrayIndex: this.rank,
|
|
type: "int"
|
|
}
|
|
];
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(this.rank);
|
|
const coords = (0, _packingUtil.getChannels)("coords", this.rank);
|
|
const sourceLoc = (0, _packingUtil.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 = `
|
|
void main() {
|
|
${dtype} coords = getOutputCoords();
|
|
${dtype} sourceLoc;
|
|
${sourceLocSetup}
|
|
vec4 result = vec4(0.);
|
|
${upperRow}
|
|
${lowerRow}
|
|
setOutput(result);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7xVX3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "bincount", ()=>bincount);
|
|
parcelHelpers.export(exports, "bincountConfig", ()=>bincountConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function bincount(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, weights } = inputs;
|
|
const { size } = attrs;
|
|
const xVals = backend.readSync(x.dataId);
|
|
const weightsVals = backend.readSync(weights.dataId);
|
|
const outVals = (0, _shared.bincountImplCPU)(xVals, weightsVals, weights.dtype, weights.shape, size);
|
|
return backend.makeTensorInfo([
|
|
size
|
|
], weights.dtype, outVals);
|
|
}
|
|
const bincountConfig = {
|
|
kernelName: (0, _tfjsCore.Bincount),
|
|
backendName: "webgl",
|
|
kernelFunc: bincount
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"87LwA":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "BITWISEAND", ()=>BITWISEAND);
|
|
parcelHelpers.export(exports, "BITWISEAND_UNPACKED", ()=>BITWISEAND_UNPACKED);
|
|
parcelHelpers.export(exports, "bitwiseAnd", ()=>bitwiseAnd);
|
|
parcelHelpers.export(exports, "bitwiseAndConfig", ()=>bitwiseAndConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const BITWISEAND = `
|
|
int r = int(a.r) & int(b.r);
|
|
int g = int(a.g) & int(b.g);
|
|
int rb = int(a.b) & int(b.b);
|
|
int ra = int(a.a) & int(b.a);
|
|
return vec4(r, g, rb, ra);
|
|
`;
|
|
const BITWISEAND_UNPACKED = `
|
|
return float(int(a.r) & int(b.r));
|
|
`;
|
|
function bitwiseAnd(args) {
|
|
const { inputs, backend } = args;
|
|
const { a, b } = inputs;
|
|
const shouldUsePackedProgram = (0, _tfjsCore.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS");
|
|
const versionNumber = (0, _tfjsCore.env)().getNumber("WEBGL_VERSION");
|
|
// The type of a and b are ensured to be `int32` in core, therefore no need to
|
|
// consider other type situations.
|
|
if (backend.shouldExecuteOnCPU([
|
|
a,
|
|
b
|
|
]) || versionNumber === 1) {
|
|
const aVals = backend.texData.get(a.dataId).values;
|
|
const bVals = backend.texData.get(b.dataId).values;
|
|
const [outValues, outShape] = (0, _shared.bitwiseAndImplCPU)(a.shape, b.shape, aVals, bVals, a.dtype);
|
|
const out = backend.makeTensorInfo(outShape, a.dtype);
|
|
const outData = backend.texData.get(out.dataId);
|
|
outData.values = outValues;
|
|
return out;
|
|
}
|
|
let program;
|
|
if (shouldUsePackedProgram) program = new (0, _binaryopPackedGpu.BinaryOpPackedProgram)(BITWISEAND, a.shape, b.shape, false);
|
|
else program = new (0, _binaryopGpu.BinaryOpProgram)(BITWISEAND_UNPACKED, a.shape, b.shape);
|
|
return backend.runWebGLProgram(program, [
|
|
a,
|
|
b
|
|
], a.dtype);
|
|
}
|
|
const bitwiseAndConfig = {
|
|
kernelName: (0, _tfjsCore.BitwiseAnd),
|
|
backendName: "webgl",
|
|
kernelFunc: bitwiseAnd
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9Zlag":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "broadcastArgs", ()=>broadcastArgs);
|
|
parcelHelpers.export(exports, "broadcastArgsConfig", ()=>broadcastArgsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function broadcastArgs(args) {
|
|
const { inputs, backend } = args;
|
|
const { s0, s1 } = inputs;
|
|
const s0Vals = backend.readSync(s0.dataId);
|
|
const s1Vals = backend.readSync(s1.dataId);
|
|
const broadcastShape = (0, _tfjsCore.backend_util).assertAndGetBroadcastShape(Array.from(s0Vals), Array.from(s1Vals));
|
|
return backend.makeTensorInfo([
|
|
broadcastShape.length
|
|
], "int32", Int32Array.from(broadcastShape));
|
|
}
|
|
const broadcastArgsConfig = {
|
|
kernelName: (0, _tfjsCore.BroadcastArgs),
|
|
backendName: "webgl",
|
|
kernelFunc: broadcastArgs
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c2JG9":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cast", ()=>cast);
|
|
parcelHelpers.export(exports, "castConfig", ()=>castConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _complex = require("./Complex");
|
|
var _identity = require("./Identity");
|
|
var _notEqual = require("./NotEqual");
|
|
var _real = require("./Real");
|
|
var _int = require("../kernel_utils/int");
|
|
function cast(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { dtype } = attrs;
|
|
// Casting to complex64.
|
|
if (dtype === "complex64") {
|
|
if (x.dtype === "complex64") return (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
// TODO(annxingyuan): Import kernel function once zeros is modularized.
|
|
const zerosTensor = _tfjsCore.zeros(x.shape);
|
|
const floatX = cast({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dtype: "float32"
|
|
}
|
|
});
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: floatX,
|
|
imag: zerosTensor
|
|
},
|
|
backend
|
|
});
|
|
zerosTensor.dispose();
|
|
backend.disposeIntermediateTensorInfo(floatX);
|
|
return result;
|
|
}
|
|
// Casting from complex64
|
|
if (x.dtype === "complex64") {
|
|
const realPart = (0, _real.real)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const result = cast({
|
|
inputs: {
|
|
x: realPart
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dtype
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(realPart);
|
|
return result;
|
|
}
|
|
if (!(0, _tfjsCore.util).hasEncodingLoss(x.dtype, dtype)) {
|
|
// We don't change the underlying data, since we cast to higher
|
|
// precision.
|
|
const result = (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
return {
|
|
dataId: result.dataId,
|
|
shape: result.shape,
|
|
dtype
|
|
};
|
|
}
|
|
if (backend.shouldExecuteOnCPU([
|
|
x
|
|
])) {
|
|
const values = backend.texData.get(x.dataId).values;
|
|
const [resultShape, resultType, resultData] = (0, _shared.castImplCPU)(values, x.shape, x.dtype, dtype);
|
|
return backend.makeTensorInfo(resultShape, resultType, resultData);
|
|
}
|
|
if (dtype === "int32") return (0, _int.int)(x, backend);
|
|
if (dtype === "bool") {
|
|
const zerosTensorInfo = backend.makeTensorInfo([], "bool", (0, _tfjsCore.util).getTypedArrayFromDType("bool", 1));
|
|
const binaryInputs = {
|
|
a: x,
|
|
b: zerosTensorInfo
|
|
};
|
|
const result = (0, _notEqual.notEqual)({
|
|
inputs: binaryInputs,
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(zerosTensorInfo);
|
|
return result;
|
|
}
|
|
throw new Error(`Error in Cast: failed to cast ${x.dtype} to ${dtype}`);
|
|
}
|
|
const castConfig = {
|
|
kernelName: (0, _tfjsCore.Cast),
|
|
backendName: "webgl",
|
|
kernelFunc: cast
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","./Complex":"55NfL","./Identity":"hY9aT","./NotEqual":"hOvsV","./Real":"4HOZy","../kernel_utils/int":"aZKXt","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hOvsV":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "notEqual", ()=>notEqual);
|
|
parcelHelpers.export(exports, "notEqualConfig", ()=>notEqualConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const NOT_EQUAL = `return float(a != b);`;
|
|
const notEqual = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: NOT_EQUAL,
|
|
cpuKernelImpl: (0, _shared.notEqualImplCPU),
|
|
dtype: "bool"
|
|
});
|
|
const notEqualConfig = {
|
|
kernelName: (0, _tfjsCore.NotEqual),
|
|
backendName: "webgl",
|
|
kernelFunc: notEqual
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4HOZy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "real", ()=>real);
|
|
parcelHelpers.export(exports, "realConfig", ()=>realConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _identity = require("./Identity");
|
|
function real(args) {
|
|
const { inputs, backend } = args;
|
|
const { input } = inputs;
|
|
const inputData = backend.texData.get(input.dataId);
|
|
return (0, _identity.identity)({
|
|
inputs: {
|
|
x: inputData.complexTensorInfos.real
|
|
},
|
|
backend
|
|
});
|
|
}
|
|
const realConfig = {
|
|
kernelName: (0, _tfjsCore.Real),
|
|
backendName: "webgl",
|
|
kernelFunc: real
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Identity":"hY9aT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aZKXt":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "int", ()=>int);
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const TO_INT = `return float(int(x));`;
|
|
function int(input, backend) {
|
|
const program = new (0, _unaryopGpu.UnaryOpProgram)(input.shape, TO_INT);
|
|
const output = backend.runWebGLProgram(program, [
|
|
input
|
|
], "int32");
|
|
return {
|
|
dataId: output.dataId,
|
|
shape: output.shape,
|
|
dtype: output.dtype
|
|
};
|
|
}
|
|
|
|
},{"../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iSroj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ceil", ()=>ceil);
|
|
parcelHelpers.export(exports, "ceilConfig", ()=>ceilConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const CEIL = `return ceil(x);`;
|
|
const ceil = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: CEIL,
|
|
packedOpSnippet: CEIL,
|
|
cpuKernelImpl: (0, _shared.ceilImplCPU)
|
|
});
|
|
const ceilConfig = {
|
|
kernelName: (0, _tfjsCore.Ceil),
|
|
backendName: "webgl",
|
|
kernelFunc: ceil
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gt2mD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "clipByValue", ()=>clipByValue);
|
|
parcelHelpers.export(exports, "clipByValueConfig", ()=>clipByValueConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _clipGpu = require("../clip_gpu");
|
|
var _clipPackedGpu = require("../clip_packed_gpu");
|
|
function clipByValue(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { clipValueMin, clipValueMax } = attrs;
|
|
let program;
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_PACK_CLIP")) program = new (0, _clipPackedGpu.ClipPackedProgram)(x.shape);
|
|
else program = new (0, _clipGpu.ClipProgram)(x.shape);
|
|
const customValues = [
|
|
[
|
|
clipValueMin
|
|
],
|
|
[
|
|
clipValueMax
|
|
]
|
|
];
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype, customValues);
|
|
}
|
|
const clipByValueConfig = {
|
|
kernelName: (0, _tfjsCore.ClipByValue),
|
|
backendName: "webgl",
|
|
kernelFunc: clipByValue
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../clip_gpu":"5PxVu","../clip_packed_gpu":"au6Kr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5PxVu":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ClipProgram", ()=>ClipProgram);
|
|
class ClipProgram {
|
|
constructor(aShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.customUniforms = [
|
|
{
|
|
name: "minVal",
|
|
type: "float"
|
|
},
|
|
{
|
|
name: "maxVal",
|
|
type: "float"
|
|
}
|
|
];
|
|
this.outputShape = aShape;
|
|
this.userCode = `
|
|
|
|
void main() {
|
|
float value = getAAtOutCoords();
|
|
if (isnan(value)) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, minVal, maxVal));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"au6Kr":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ClipPackedProgram", ()=>ClipPackedProgram);
|
|
class ClipPackedProgram {
|
|
constructor(aShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.customUniforms = [
|
|
{
|
|
name: "minVal",
|
|
type: "float"
|
|
},
|
|
{
|
|
name: "maxVal",
|
|
type: "float"
|
|
}
|
|
];
|
|
this.outputShape = aShape;
|
|
this.userCode = `
|
|
void main() {
|
|
vec4 value = getAAtOutCoords();
|
|
|
|
if (any(isnan(value))) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fwiH6":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "complexAbs", ()=>complexAbs);
|
|
parcelHelpers.export(exports, "complexAbsConfig", ()=>complexAbsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _complexAbsGpu = require("../complex_abs_gpu");
|
|
// 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.
|
|
function makeComplexComponentTensorInfo(complexTensor, complexPart) {
|
|
return {
|
|
dataId: complexPart.dataId,
|
|
dtype: complexPart.dtype,
|
|
shape: complexTensor.shape
|
|
};
|
|
}
|
|
function complexAbs(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
const xData = backend.texData.get(x.dataId);
|
|
const program = new (0, _complexAbsGpu.ComplexAbsProgram)(x.shape);
|
|
const programInputs = [
|
|
makeComplexComponentTensorInfo(x, xData.complexTensorInfos.real),
|
|
makeComplexComponentTensorInfo(x, xData.complexTensorInfos.imag)
|
|
];
|
|
return backend.runWebGLProgram(program, programInputs, programInputs[0].dtype);
|
|
}
|
|
const complexAbsConfig = {
|
|
kernelName: (0, _tfjsCore.ComplexAbs),
|
|
backendName: "webgl",
|
|
kernelFunc: complexAbs
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../complex_abs_gpu":"iVDTX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iVDTX":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ComplexAbsProgram", ()=>ComplexAbsProgram);
|
|
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))
|
|
);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2gCZH":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concat", ()=>concat);
|
|
parcelHelpers.export(exports, "concatConfig", ()=>concatConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _concatImpl = require("./Concat_impl");
|
|
var _identity = require("./Identity");
|
|
function concat(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { axis } = attrs;
|
|
const $axis = (0, _tfjsCore.util).parseAxisParam(axis, inputs[0].shape)[0];
|
|
const shapes = inputs.map((t)=>t.shape);
|
|
(0, _tfjsCore.backend_util).assertParamsConsistent(shapes, $axis);
|
|
const outShape = (0, _tfjsCore.backend_util).computeOutShape(inputs.map((t)=>t.shape), $axis);
|
|
if ((0, _tfjsCore.util).sizeFromShape(outShape) === 0) return backend.makeTensorInfo(outShape, inputs[0].dtype, []);
|
|
// Keep only non-empty tensors (ignore tensors with 0 in their shape).
|
|
const $inputs = inputs.filter((t)=>(0, _tfjsCore.util).sizeFromShape(t.shape) > 0);
|
|
if ($inputs.length === 1) return (0, _identity.identity)({
|
|
inputs: {
|
|
x: $inputs[0]
|
|
},
|
|
backend
|
|
});
|
|
return (0, _concatImpl.concatImpl)($inputs, $axis, backend);
|
|
}
|
|
const concatConfig = {
|
|
kernelName: (0, _tfjsCore.Concat),
|
|
backendName: "webgl",
|
|
kernelFunc: concat
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Concat_impl":"2G3Uy","./Identity":"hY9aT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2G3Uy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concatImpl", ()=>concatImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _concatGpu = require("../concat_gpu");
|
|
var _concatPackedGpu = require("../concat_packed_gpu");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
var _unaryopPackedGpu = require("../unaryop_packed_gpu");
|
|
var _complex = require("./Complex");
|
|
var _imag = require("./Imag");
|
|
var _real = require("./Real");
|
|
var _reshape = require("./Reshape");
|
|
function concatImpl(inputs, axis, backend) {
|
|
const dtype = inputs[0].dtype;
|
|
if (dtype === "complex64") {
|
|
const reals = inputs.map((t)=>(0, _real.real)({
|
|
inputs: {
|
|
input: t
|
|
},
|
|
backend
|
|
}));
|
|
const imags = inputs.map((t)=>(0, _imag.imag)({
|
|
inputs: {
|
|
input: t
|
|
},
|
|
backend
|
|
}));
|
|
const realConcated = concatImpl(reals, axis, backend);
|
|
const imagConcated = concatImpl(imags, axis, backend);
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: realConcated,
|
|
imag: imagConcated
|
|
},
|
|
backend
|
|
});
|
|
reals.forEach((r)=>backend.disposeIntermediateTensorInfo(r));
|
|
imags.forEach((i)=>backend.disposeIntermediateTensorInfo(i));
|
|
backend.disposeIntermediateTensorInfo(realConcated);
|
|
backend.disposeIntermediateTensorInfo(imagConcated);
|
|
return result;
|
|
}
|
|
let runOnCpu = backend.shouldExecuteOnCPU(inputs);
|
|
// Run on cpu if dtype is string. For string, the backend represents it
|
|
// as Uint8Array[], where each Uint8Array is a character. Given that the
|
|
// computation is only on the outer array, uploading the whole data onto
|
|
// gpu is wasteful. Also, currently webgl doesn't have a design to
|
|
// upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we
|
|
// just run the kernel on cpu if dtype is string.
|
|
if (dtype === "string") runOnCpu = true;
|
|
if (runOnCpu) {
|
|
// 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 tensors2D = inputs.map((t)=>{
|
|
const innerSize = (0, _tfjsCore.util).sizeFromShape(t.shape.slice(axis));
|
|
const shape = [
|
|
-1,
|
|
innerSize
|
|
];
|
|
return (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: t
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape
|
|
}
|
|
});
|
|
});
|
|
const inputsValShapes = tensors2D.map((t)=>{
|
|
return {
|
|
vals: backend.readSync(t.dataId),
|
|
shape: t.shape
|
|
};
|
|
});
|
|
// Concats 2d tensors along axis=1.
|
|
const outShape = (0, _tfjsCore.backend_util).computeOutShape(tensors2D.map((t)=>t.shape), 1 /* axis */ );
|
|
const simplyConcat = tensors2D[0].shape[0] === 1;
|
|
const outVals = (0, _shared.concatImplCPU)(inputsValShapes, outShape, dtype, simplyConcat);
|
|
const finalOutShape = (0, _tfjsCore.backend_util).computeOutShape(inputs.map((t)=>t.shape), axis);
|
|
const outInfo = backend.makeTensorInfo(finalOutShape, dtype, outVals);
|
|
tensors2D.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return outInfo;
|
|
}
|
|
// Keep only non-empty tensors (ignore tensors with 0 in their shape).
|
|
const $inputs = inputs.filter((t)=>(0, _tfjsCore.util).sizeFromShape(t.shape) > 0);
|
|
const shouldPack = (0, _tfjsCore.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS") && $inputs[0].shape.length > 1;
|
|
if ($inputs.length === 1) {
|
|
// Clone tensor.
|
|
const program = shouldPack ? new (0, _unaryopGpu.UnaryOpProgram)(inputs[0].shape, (0, _unaryopGpu.CLONE)) : new (0, _unaryopPackedGpu.UnaryOpPackedProgram)(inputs[0].shape, (0, _unaryopGpu.CLONE));
|
|
return backend.runWebGLProgram(program, inputs, dtype);
|
|
}
|
|
const maxTexturesInShader = (0, _tfjsCore.env)().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");
|
|
if ($inputs.length > maxTexturesInShader) {
|
|
const reducedInputs = [];
|
|
for(let i = 0; i < $inputs.length; i += maxTexturesInShader){
|
|
const subArray = $inputs.slice(i, i + maxTexturesInShader);
|
|
reducedInputs.push(concatImpl(subArray, axis, backend));
|
|
}
|
|
const result = concatImpl(reducedInputs, axis, backend);
|
|
for (const i of reducedInputs)backend.disposeIntermediateTensorInfo(i);
|
|
return result;
|
|
}
|
|
if (shouldPack) {
|
|
const program = new (0, _concatPackedGpu.ConcatPackedProgram)($inputs.map((t)=>t.shape), axis);
|
|
return backend.runWebGLProgram(program, $inputs, dtype);
|
|
}
|
|
const { tensors2D, outShape } = computeTensors2D($inputs, axis, backend);
|
|
const program = new (0, _concatGpu.ConcatProgram)(tensors2D.map((t)=>t.shape));
|
|
const result = backend.runWebGLProgram(program, tensors2D, dtype);
|
|
tensors2D.forEach((r)=>backend.disposeIntermediateTensorInfo(r));
|
|
const reshapedResult = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
attrs: {
|
|
shape: outShape
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
return reshapedResult;
|
|
}
|
|
function computeTensors2D(inputs, axis, backend) {
|
|
// 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 = (0, _tfjsCore.backend_util).computeOutShape(inputs.map((t)=>t.shape), axis);
|
|
const tensors2D = inputs.map((x)=>(0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
attrs: {
|
|
shape: [
|
|
-1,
|
|
(0, _tfjsCore.util).sizeFromShape(x.shape.slice(axis))
|
|
]
|
|
},
|
|
backend
|
|
}));
|
|
return {
|
|
tensors2D,
|
|
outShape
|
|
};
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../concat_gpu":"5FWMv","../concat_packed_gpu":"6p42F","../kernel_utils/shared":"e4M7v","../unaryop_gpu":"gIMrR","../unaryop_packed_gpu":"c4D5K","./Complex":"55NfL","./Imag":"3PMfw","./Real":"4HOZy","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5FWMv":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ConcatProgram", ()=>ConcatProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
class ConcatProgram {
|
|
// Concats 2d tensors along axis=1. See comments in MathBackendWebGL.concat().
|
|
constructor(shapes){
|
|
this.outputShape = [];
|
|
this.outputShape = (0, _tfjsCore.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 ")}
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6p42F":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ConcatPackedProgram", ()=>ConcatPackedProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class ConcatPackedProgram {
|
|
constructor(shapes, axis){
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.outputShape = [];
|
|
this.outputShape = (0, _tfjsCore.backend_util).computeOutShape(shapes, axis);
|
|
const shape = this.outputShape;
|
|
const rank = shape.length;
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(rank);
|
|
const coords = (0, _packingUtil.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();
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3PMfw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "imag", ()=>imag);
|
|
parcelHelpers.export(exports, "imagConfig", ()=>imagConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _identity = require("./Identity");
|
|
function imag(args) {
|
|
const { inputs, backend } = args;
|
|
const { input } = inputs;
|
|
const inputData = backend.texData.get(input.dataId);
|
|
return (0, _identity.identity)({
|
|
inputs: {
|
|
x: inputData.complexTensorInfos.imag
|
|
},
|
|
backend
|
|
});
|
|
}
|
|
const imagConfig = {
|
|
kernelName: (0, _tfjsCore.Imag),
|
|
backendName: "webgl",
|
|
kernelFunc: imag
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Identity":"hY9aT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"425yr":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2d", ()=>conv2d);
|
|
parcelHelpers.export(exports, "conv2DConfig", ()=>conv2DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convGpu = require("../conv_gpu");
|
|
var _convPackedGpu = require("../conv_packed_gpu");
|
|
var _conv2DImpl = require("./Conv2D_impl");
|
|
var _reshape = require("./Reshape");
|
|
function conv2d(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter } = inputs;
|
|
const { strides, pad, dataFormat, dilations, dimRoundingMode } = attrs;
|
|
const $dataFormat = (0, _tfjsCore.backend_util).convertConv2DDataFormat(dataFormat);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false, $dataFormat);
|
|
let out;
|
|
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")) out = (0, _conv2DImpl.conv2dByMatMul)({
|
|
x,
|
|
filter,
|
|
convInfo,
|
|
backend
|
|
});
|
|
else if (convInfo.strideWidth <= 2 && $dataFormat === "channelsLast" && (0, _tfjsCore.env)().getBool("WEBGL_EXP_CONV")) {
|
|
const program = new (0, _convPackedGpu.Conv2DPackedProgram)(convInfo);
|
|
const customValues = [
|
|
[
|
|
convInfo.padInfo.top,
|
|
convInfo.padInfo.left
|
|
],
|
|
[
|
|
convInfo.strideHeight,
|
|
convInfo.strideWidth
|
|
],
|
|
[
|
|
convInfo.dilationHeight,
|
|
convInfo.dilationWidth
|
|
],
|
|
[
|
|
convInfo.inHeight,
|
|
convInfo.inWidth
|
|
]
|
|
];
|
|
out = backend.runWebGLProgram(program, [
|
|
x,
|
|
filter
|
|
], "float32", customValues);
|
|
} else if ((0, _tfjsCore.env)().getBool("WEBGL_CONV_IM2COL")) out = (0, _conv2DImpl.conv2dWithIm2Row)({
|
|
x,
|
|
filter,
|
|
convInfo,
|
|
backend
|
|
});
|
|
else {
|
|
const program = new (0, _convGpu.Conv2DProgram)(convInfo);
|
|
out = backend.runWebGLProgram(program, [
|
|
x,
|
|
filter
|
|
], "float32");
|
|
}
|
|
const outReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: out
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: convInfo.outShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(out);
|
|
return outReshaped;
|
|
}
|
|
const conv2DConfig = {
|
|
kernelName: (0, _tfjsCore.Conv2D),
|
|
backendName: "webgl",
|
|
kernelFunc: conv2d
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_gpu":"3pfYb","../conv_packed_gpu":"hPtK0","./Conv2D_impl":"6Kgrg","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3pfYb":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Conv2DProgram", ()=>Conv2DProgram);
|
|
parcelHelpers.export(exports, "Conv3DProgram", ()=>Conv3DProgram);
|
|
class Conv2DProgram {
|
|
constructor(convInfo, addBias = false, activation = null, hasPreluActivationWeights = false, hasLeakyreluAlpha = 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 if (hasLeakyreluAlpha) activationSnippet = `float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${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");
|
|
if (hasLeakyreluAlpha) this.variableNames.push("leakyreluAlpha");
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hPtK0":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Conv2DPackedProgram", ()=>Conv2DPackedProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
class Conv2DPackedProgram {
|
|
constructor(convInfo, addBias = false, activation = null, hasPreluActivation = false, hasLeakyReluAlpha = false){
|
|
this.variableNames = [
|
|
"x",
|
|
"W"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.customUniforms = [
|
|
{
|
|
name: "pads",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "strides",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "dilations",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "inDims",
|
|
type: "ivec2"
|
|
}
|
|
];
|
|
this.outputShape = convInfo.outShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
const padLeft = convInfo.padInfo.left;
|
|
const strideWidth = convInfo.strideWidth;
|
|
const dilationWidth = convInfo.dilationWidth;
|
|
const filterHeight = convInfo.filterHeight;
|
|
const filterWidth = convInfo.filterWidth;
|
|
const texelsAcross = filterWidth;
|
|
let mainLoop = `
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;
|
|
for(let c = 0; c < filterWidth; c++)mainLoop += `
|
|
vec4 xTexelC${c * 2};
|
|
int xTexelC${c * 2}Ready;
|
|
vec4 xTexelC${c * 2 + 1};
|
|
int xTexelC${c * 2 + 1}Ready;
|
|
vec4 xC${c};`;
|
|
/**
|
|
* 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.
|
|
*/ mainLoop += `
|
|
for (int r = 0; r < ${filterHeight}; r++) {
|
|
for (int d1 = 0; d1 < ${convInfo.inChannels}; d1 += 2) {
|
|
`;
|
|
for(let c = 0; c < filterWidth; c++)mainLoop += `
|
|
xTexelC${c * 2} = vec4(0.0);
|
|
xTexelC${c * 2}Ready = 0;
|
|
xTexelC${c * 2 + 1} = vec4(0.0);
|
|
xTexelC${c * 2 + 1}Ready = 0;
|
|
xC${c} = vec4(0.0);`;
|
|
mainLoop += `
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;
|
|
for(let texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++){
|
|
const colIndex = texelC * 2;
|
|
mainLoop += `
|
|
xC = xCCorner + ${colIndex * dilationWidth};
|
|
`;
|
|
if (strideWidth === 1) {
|
|
if (colIndex < 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 (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex}Ready == 0) {
|
|
xTexelC${colIndex} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex}Ready = 1;
|
|
}
|
|
`;
|
|
// This texel has been read in previous iteration if the dilation
|
|
// is 1.
|
|
if (dilationWidth === 1 && colIndex > 0) mainLoop += `
|
|
xC${colIndex} = vec4(xTexelC${colIndex - 2}.zw, xTexelC${colIndex}.xy);
|
|
`;
|
|
else mainLoop += `
|
|
xCOffset = xC + 1 - 2;
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
previous.zw = vec2(0.0);
|
|
}
|
|
|
|
xC${colIndex} = vec4(previous.zw, xTexelC${colIndex}.xy);
|
|
} else {
|
|
xC${colIndex} = vec4(0.0, 0.0, xTexelC${colIndex}.xy);
|
|
}
|
|
`;
|
|
} else // Padding is even, so xRC corresponds to a single texel.
|
|
mainLoop += `
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${colIndex}Ready == 0) {
|
|
xTexelC${colIndex} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${colIndex}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex}Ready = 1;
|
|
}
|
|
|
|
xC${colIndex} = xTexelC${colIndex};
|
|
`;
|
|
if (colIndex + 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 ? (0, _tfjsCore.util).nearestLargerEven(dilationWidth) : dilationWidth;
|
|
if (dilationWidth % 2 === 0 && padLeft % 2 === 1 || dilationWidth % 2 !== 0 && padLeft % 2 !== 1) {
|
|
mainLoop += `
|
|
xCOffset = xC + imod(pads[1], 2) + ${nextTexelOffset};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex + 1}Ready == 0) {
|
|
xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex + 1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex + 1}Ready = 1;
|
|
}
|
|
`;
|
|
// 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 (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
xC${colIndex + 1} = vec4(previous.zw, xTexelC${colIndex + 1}.xy);
|
|
} else {
|
|
xC${colIndex + 1} = vec4(0.0, 0.0, xTexelC${colIndex + 1}.xy);
|
|
}
|
|
`;
|
|
else mainLoop += `
|
|
xC${colIndex + 1} = vec4(xTexelC${colIndex}.zw, xTexelC${colIndex + 1}.xy);
|
|
`;
|
|
} else // If dilation is 1 and padding is odd, we have already read the
|
|
// texel when constructing the previous x value. Here we can
|
|
// simply skip the texture read.
|
|
if (nextTexelOffset === 1) mainLoop += `
|
|
xC${colIndex + 1} = xTexelC${colIndex};
|
|
`;
|
|
else mainLoop += `
|
|
xCOffset = xC + ${nextTexelOffset};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex + 1}Ready == 0) {
|
|
xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex + 1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex + 1}Ready = 1;
|
|
}
|
|
|
|
xC${colIndex + 1} = xTexelC${colIndex + 1};
|
|
`;
|
|
}
|
|
}
|
|
} else if (colIndex < filterWidth) {
|
|
// Depending on whether padLeft is even or odd, we want either the
|
|
// xy or zw channels from X texels for xC${colIndex}. If padLeft is
|
|
// even, xC${colIndex +1} is simply the zw channels of texels we've
|
|
// already sampled. But if padLeft is odd, xC{$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 - strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex}Ready == 0) {
|
|
xTexelC${colIndex} = getX(batch, xR, xCOffset, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${colIndex + 1}Ready == 0) {
|
|
xTexelC${colIndex + 1} = getX(batch, xR, xC + 1, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xC + 2 >= inDims[1]) {
|
|
xTexelC${colIndex + 1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex + 1}Ready = 1;
|
|
}
|
|
|
|
xC${colIndex} = vec4(xTexelC${colIndex}.zw, xTexelC${colIndex + 1}.zw);
|
|
`;
|
|
if (colIndex + 1 < filterWidth) mainLoop += `
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${colIndex + 1} = vec4(xTexelC${colIndex + 1}.xy, final.xy);
|
|
`;
|
|
} else {
|
|
mainLoop += `
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${colIndex}Ready == 0) {
|
|
xTexelC${colIndex} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${colIndex}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex + 1}Ready == 0) {
|
|
xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex + 1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${colIndex + 1}Ready = 1;
|
|
}
|
|
|
|
xC${colIndex} = vec4(
|
|
xTexelC${colIndex}.xy, xTexelC${colIndex + 1}.xy);
|
|
`;
|
|
if (colIndex + 1 < filterWidth) mainLoop += `
|
|
xC${colIndex + 1} = vec4(xTexelC${colIndex}.zw, xTexelC${colIndex + 1}.zw);
|
|
`;
|
|
}
|
|
}
|
|
// localize the dotProd accumulation within the loop, the theory is for
|
|
// GPU with limited cache, accumulate sum across large amount of
|
|
// veriables will cause lots of cache misses. (i.e. 5x5 filter will have
|
|
// 50 variables)
|
|
if (colIndex < filterWidth) {
|
|
mainLoop += `
|
|
wTexel = getW(r, ${colIndex}, d1, d2);
|
|
dotProd += xC${colIndex}.xxzz * vec4(wTexel.xy, wTexel.xy);
|
|
if(d1 + 1 < ${convInfo.inChannels}) {
|
|
dotProd += xC${colIndex}.yyww * vec4(wTexel.zw, wTexel.zw);
|
|
}
|
|
`;
|
|
if (colIndex + 1 < filterWidth) mainLoop += `
|
|
wTexel = getW(r, ${colIndex + 1}, d1, d2);
|
|
dotProd += xC${colIndex + 1}.xxzz * vec4(wTexel.xy, wTexel.xy);
|
|
if(d1 + 1 < ${convInfo.inChannels}) {
|
|
dotProd += xC${colIndex + 1}.yyww * vec4(wTexel.zw, wTexel.zw);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
mainLoop += `
|
|
}
|
|
`;
|
|
mainLoop += `
|
|
}
|
|
`;
|
|
mainLoop += `
|
|
}
|
|
`;
|
|
let activationSnippet = "", applyActivationSnippet = "";
|
|
if (activation) {
|
|
if (hasPreluActivation) activationSnippet = `vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${activation}
|
|
}`;
|
|
else if (hasLeakyReluAlpha) activationSnippet = `vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${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");
|
|
if (hasLeakyReluAlpha) this.variableNames.push("leakyreluAlpha");
|
|
this.userCode = `
|
|
${activationSnippet}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
|
|
vec4 dotProd = vec4(0.000000000000001);
|
|
|
|
${mainLoop}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${addBiasSnippet}
|
|
${applyActivationSnippet}
|
|
setOutput(result);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6Kgrg":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
// For 1x1 kernels that iterate through every point in the input, convolution
|
|
// can be expressed as matrix multiplication (without need for memory
|
|
// remapping).
|
|
parcelHelpers.export(exports, "conv2dByMatMul", ()=>conv2dByMatMul);
|
|
// Implements the im2row algorithm as outlined in "High Performance
|
|
// Convolutional Neural Networks for Document Processing" (Suvisoft, 2006)
|
|
parcelHelpers.export(exports, "conv2dWithIm2Row", ()=>conv2dWithIm2Row);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _im2ColPackedGpu = require("../im2col_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _mulmatPackedGpu = require("../mulmat_packed_gpu");
|
|
var _webglUtil = require("../webgl_util");
|
|
var _batchMatMulImpl = require("./BatchMatMul_impl");
|
|
var _identity = require("./Identity");
|
|
var _reshape = require("./Reshape");
|
|
// Both conv2dByMatMul and conv2dWithIm2Row fuse height and width into one
|
|
// dimension to compute batchMatMul, so bias and activation weights are also
|
|
// supposed to fuse the two dimensions into one.
|
|
//
|
|
// This function computes the target shape for fusing height and width
|
|
// dimensions. Returning null means the shape is already compatible.
|
|
//
|
|
// Even though the bias is not supposed to be a 3-D or a 4-D (including
|
|
// batch) tensor and PReLU activiation weights is not supposed to be a 4-D
|
|
// tensor, we still need to support them, because we haven't disabled
|
|
// them for NHWC format.
|
|
// https://github.com/tensorflow/tfjs/blob/b53bd47e880367ae57493f0ea628abaf08db2d5d/tfjs-core/src/ops/fused/conv2d.ts#L181-L196
|
|
function getShapeForBatchMatMul(shape, isChannelsLast) {
|
|
const length = shape.length;
|
|
if (length >= 3) return isChannelsLast ? [
|
|
...shape.slice(0, -3),
|
|
shape[length - 3] * shape[length - 2],
|
|
shape[length - 1]
|
|
] : [
|
|
...shape.slice(0, -3),
|
|
shape[length - 3],
|
|
shape[length - 2] * shape[length - 1]
|
|
];
|
|
else if (!isChannelsLast && length === 1 && shape[0] > 1) return [
|
|
shape[0],
|
|
1
|
|
];
|
|
else return null;
|
|
}
|
|
function conv2dByMatMul({ x, filter, convInfo, backend, bias = null, preluActivationWeights = null, leakyreluAlpha = 0, activation = null }) {
|
|
// Reshapes conv2D input to 2D tensors, uses matMul and then reshape the
|
|
// result from 2D to 4D.
|
|
const xShape = x.shape;
|
|
const xTexData = backend.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;
|
|
let out;
|
|
const intermediates = [];
|
|
if (preluActivationWeights != null) {
|
|
const targetShape = getShapeForBatchMatMul(preluActivationWeights.shape, isChannelsLast);
|
|
if (targetShape != null) {
|
|
preluActivationWeights = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: preluActivationWeights
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: targetShape
|
|
}
|
|
});
|
|
intermediates.push(preluActivationWeights);
|
|
}
|
|
}
|
|
if (bias != null) {
|
|
const targetShape = getShapeForBatchMatMul(bias.shape, isChannelsLast);
|
|
if (targetShape != null) {
|
|
bias = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: bias
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: targetShape
|
|
}
|
|
});
|
|
intermediates.push(bias);
|
|
}
|
|
}
|
|
// TODO: Once reduction ops are packed, batchMatMul will always be packed
|
|
// and we can remove this condition.
|
|
const batchMatMulWillBeUnpacked = (outerShapeX === 1 || outerShapeFilter === 1) && sharedMatMulDim > (0, _batchMatMulImpl.MATMUL_SHARED_DIM_THRESHOLD);
|
|
// The algorithm in the if condition assumes (1) the output will be packed,
|
|
// (2) x is packed, (3) x isChannelsLast, (4) x's packed texture is already
|
|
// on GPU, (5) col is odd, (6) the width, height and inChannels are the same
|
|
// for xTexData.shape and xShape.
|
|
const canOptimize = !batchMatMulWillBeUnpacked && xTexData.isPacked && isChannelsLast && xTexData.texture != null && xShape[2] % 2 !== 0 && (0, _tfjsCore.util).arraysEqual(xTexData.shape.slice(-3), xShape.slice(-3));
|
|
if (canOptimize) {
|
|
// We avoid expensive packed 2x2 reshape by padding col count to next,
|
|
// even number. When col 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 next even col. We make the odd-cols tensor to look like
|
|
// even-cols tensor before the operation and, after the batchMatMul,
|
|
// fix the even-cols result to have odd number of cols.
|
|
const targetShape = xShape[0] * xShape[1] * (xShape[2] + 1);
|
|
const xReshaped = {
|
|
dataId: x.dataId,
|
|
shape: [
|
|
1,
|
|
targetShape,
|
|
convInfo.inChannels
|
|
],
|
|
dtype: x.dtype
|
|
};
|
|
// xTexData.shape gets referenced from GPGPUBinary.inShapeInfos.
|
|
// Decrementing col count, after batchMatMul->...->compileProgram leads to
|
|
// invalid col 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 col 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]++;
|
|
(0, _tfjsCore.util).assert(_webglUtil.isReshapeFree(xTexData.shape, xReshaped.shape), ()=>`packed reshape ${xTexData.shape} to ${xReshaped.shape} isn't free`);
|
|
const filterReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: filter
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
1,
|
|
convInfo.inChannels,
|
|
convInfo.outChannels
|
|
]
|
|
}
|
|
});
|
|
intermediates.push(filterReshaped);
|
|
const pointwiseConv = (0, _batchMatMulImpl.batchMatMulImpl)({
|
|
a: xReshaped,
|
|
b: filterReshaped,
|
|
backend,
|
|
transposeA,
|
|
transposeB,
|
|
bias,
|
|
activation,
|
|
preluActivationWeights,
|
|
leakyreluAlpha
|
|
});
|
|
const pointwiseConvTexData = backend.texData.get(pointwiseConv.dataId);
|
|
(0, _tfjsCore.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;
|
|
out = (0, _identity.identity)({
|
|
inputs: {
|
|
x: pointwiseConv
|
|
},
|
|
backend
|
|
});
|
|
out.shape = convInfo.outShape;
|
|
intermediates.push(pointwiseConv);
|
|
} else {
|
|
const numCols = convInfo.outHeight * convInfo.outWidth;
|
|
const xReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: isChannelsLast ? [
|
|
convInfo.batchSize,
|
|
numCols,
|
|
convInfo.inChannels
|
|
] : [
|
|
convInfo.batchSize,
|
|
convInfo.inChannels,
|
|
numCols
|
|
]
|
|
}
|
|
});
|
|
const filterReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: filter
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
1,
|
|
convInfo.inChannels,
|
|
convInfo.outChannels
|
|
]
|
|
}
|
|
});
|
|
const result = (0, _batchMatMulImpl.batchMatMulImpl)({
|
|
a: isChannelsLast ? xReshaped : filterReshaped,
|
|
b: isChannelsLast ? filterReshaped : xReshaped,
|
|
transposeA: !isChannelsLast,
|
|
transposeB,
|
|
backend,
|
|
bias,
|
|
activation,
|
|
preluActivationWeights,
|
|
leakyreluAlpha
|
|
});
|
|
out = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: convInfo.outShape
|
|
}
|
|
});
|
|
intermediates.push(xReshaped);
|
|
intermediates.push(filterReshaped);
|
|
intermediates.push(result);
|
|
}
|
|
for (const i of intermediates)backend.disposeIntermediateTensorInfo(i);
|
|
return out;
|
|
}
|
|
function conv2dWithIm2Row({ x, filter, convInfo, backend, bias = null, preluActivationWeights = null, leakyreluAlpha = 0, activation = null }) {
|
|
// 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 = [
|
|
convInfo.batchSize,
|
|
sharedDim,
|
|
numCols
|
|
];
|
|
const transposeA = true;
|
|
const transposeB = false;
|
|
const intermediates = [];
|
|
if (preluActivationWeights != null) {
|
|
const targetShape = getShapeForBatchMatMul(preluActivationWeights.shape, isChannelsLast);
|
|
if (targetShape != null) {
|
|
preluActivationWeights = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: preluActivationWeights
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: targetShape
|
|
}
|
|
});
|
|
intermediates.push(preluActivationWeights);
|
|
}
|
|
}
|
|
if (bias != null) {
|
|
const targetShape = getShapeForBatchMatMul(bias.shape, isChannelsLast);
|
|
if (targetShape != null) {
|
|
bias = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: bias
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: targetShape
|
|
}
|
|
});
|
|
intermediates.push(bias);
|
|
}
|
|
}
|
|
const w2Row = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: filter
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
1,
|
|
sharedDim,
|
|
(0, _tfjsCore.util).sizeFromShape(filter.shape) / sharedDim
|
|
]
|
|
}
|
|
});
|
|
intermediates.push(w2Row);
|
|
const im2ColProgram = new (0, _im2ColPackedGpu.Im2ColPackedProgram)(x2ColShape, convInfo);
|
|
const customValues = [
|
|
x.shape,
|
|
[
|
|
convInfo.padInfo.top,
|
|
convInfo.padInfo.left
|
|
],
|
|
[
|
|
convInfo.strideHeight,
|
|
convInfo.strideWidth
|
|
],
|
|
[
|
|
convInfo.dilationHeight,
|
|
convInfo.dilationWidth
|
|
],
|
|
[
|
|
convInfo.inChannels
|
|
],
|
|
[
|
|
convInfo.filterWidth * convInfo.inChannels
|
|
],
|
|
[
|
|
convInfo.outWidth
|
|
]
|
|
];
|
|
const im2Col = backend.runWebGLProgram(im2ColProgram, [
|
|
x
|
|
], "float32", customValues);
|
|
const im2ColReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: im2Col
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: x2ColShape
|
|
}
|
|
});
|
|
intermediates.push(im2Col);
|
|
intermediates.push(im2ColReshaped);
|
|
const hasBias = bias != null;
|
|
const hasPreluActivationWeights = preluActivationWeights != null;
|
|
const hasLeakyreluAlpha = activation === "leakyrelu";
|
|
const fusedActivation = activation ? (0, _kernelFuncsUtils.mapActivationToShaderProgram)(activation, true) : null;
|
|
const matmulProgram = new (0, _mulmatPackedGpu.MatMulPackedProgram)(isChannelsLast ? im2ColReshaped.shape : w2Row.shape, isChannelsLast ? w2Row.shape : im2ColReshaped.shape, isChannelsLast ? [
|
|
convInfo.batchSize,
|
|
numCols,
|
|
convInfo.outChannels
|
|
] : [
|
|
convInfo.batchSize,
|
|
convInfo.outChannels,
|
|
numCols
|
|
], transposeA, transposeB, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
|
|
const inputs = isChannelsLast ? [
|
|
im2ColReshaped,
|
|
w2Row
|
|
] : [
|
|
w2Row,
|
|
im2ColReshaped
|
|
];
|
|
if (bias) inputs.push(bias);
|
|
if (hasPreluActivationWeights) inputs.push(preluActivationWeights);
|
|
if (hasLeakyreluAlpha) {
|
|
const $leakyreluAlpha = backend.makeTensorInfo([], "float32", (0, _tfjsCore.util).createScalarValue(leakyreluAlpha, "float32"));
|
|
inputs.push($leakyreluAlpha);
|
|
intermediates.push($leakyreluAlpha);
|
|
}
|
|
const product = backend.runWebGLProgram(matmulProgram, inputs, "float32");
|
|
const out = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: product
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: convInfo.outShape
|
|
}
|
|
});
|
|
intermediates.push(product);
|
|
for (const i of intermediates)backend.disposeIntermediateTensorInfo(i);
|
|
return out;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../im2col_packed_gpu":"hGWmW","../kernel_utils/kernel_funcs_utils":"grPtN","../mulmat_packed_gpu":"cdOmp","../webgl_util":"fjf7t","./BatchMatMul_impl":"kyEQG","./Identity":"hY9aT","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hGWmW":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Im2ColPackedProgram", ()=>Im2ColPackedProgram);
|
|
var _glslVersion = require("./glsl_version");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
class Im2ColPackedProgram {
|
|
constructor(outputShape, convInfo){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.customUniforms = [
|
|
{
|
|
name: "inputShape",
|
|
type: "ivec4"
|
|
},
|
|
{
|
|
name: "pad",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "stride",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "dilation",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "inChannels",
|
|
type: "int"
|
|
},
|
|
{
|
|
name: "itemsPerBlockRow",
|
|
type: "int"
|
|
},
|
|
{
|
|
name: "outWidth",
|
|
type: "int"
|
|
}
|
|
];
|
|
this.outputShape = outputShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
const { dataFormat } = convInfo;
|
|
const glsl = (0, _glslVersion.getGlslDifferences)();
|
|
const isChannelsLast = dataFormat === "channelsLast";
|
|
const rowDim = isChannelsLast ? 1 : 2;
|
|
const colDim = isChannelsLast ? 2 : 3;
|
|
const boundsCheckingSnippet = this.enableShapeUniforms ? "if(blockIndex < outShape[2] && pos < outShape[1]) {" : `if(blockIndex < ${outputShape[2]} && pos < ${outputShape[1]}) {`;
|
|
let unrolled = ``;
|
|
for(let row = 0; row <= 1; row++)for(let col = 0; col <= 1; col++)unrolled += `
|
|
blockIndex = rc.z + ${col};
|
|
pos = rc.y + ${row};
|
|
|
|
${boundsCheckingSnippet}
|
|
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
|
|
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
|
|
|
|
if(d0 < inputShape[${rowDim}] && d0 >= 0) {
|
|
// Use custom imod instead mod. On Intel GPU, mod may generate
|
|
// unexpected value.
|
|
// https://github.com/tensorflow/tfjs/issues/5447
|
|
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
|
|
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
|
|
inChannels);
|
|
|
|
if(d1 < inputShape[${colDim}] && d1 >= 0) {
|
|
|
|
ch = imod(pos, inChannels);
|
|
|
|
if (${isChannelsLast}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${row * 2 + col}] = getChannel(
|
|
getA(rc.x, d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${row * 2 + col}] = getChannel(
|
|
getA(rc.x, ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;
|
|
this.userCode = `
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
${unrolled}
|
|
|
|
${glsl.output} = result;
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./glsl_version":"kG2vE","./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iNkBM":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2DBackpropFilter", ()=>conv2DBackpropFilter);
|
|
parcelHelpers.export(exports, "conv2DBackpropFilterConfig", ()=>conv2DBackpropFilterConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convBackpropGpu = require("../conv_backprop_gpu");
|
|
function conv2DBackpropFilter(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, dy } = inputs;
|
|
const { strides, pad, dataFormat, dimRoundingMode, filterShape } = attrs;
|
|
const $dataFormat = (0, _tfjsCore.backend_util).convertConv2DDataFormat(dataFormat);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filterShape, strides, 1 /* dilations */ , pad, dimRoundingMode, false, $dataFormat);
|
|
const program = new (0, _convBackpropGpu.Conv2DDerFilterProgram)(convInfo);
|
|
return backend.runWebGLProgram(program, [
|
|
x,
|
|
dy
|
|
], "float32");
|
|
}
|
|
const conv2DBackpropFilterConfig = {
|
|
kernelName: (0, _tfjsCore.Conv2DBackpropFilter),
|
|
backendName: "webgl",
|
|
kernelFunc: conv2DBackpropFilter
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_backprop_gpu":"1yzYs","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1yzYs":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Conv2DDerFilterProgram", ()=>Conv2DDerFilterProgram);
|
|
parcelHelpers.export(exports, "Conv2DDerInputProgram", ()=>Conv2DDerInputProgram);
|
|
parcelHelpers.export(exports, "Conv3DDerFilterProgram", ()=>Conv3DDerFilterProgram);
|
|
parcelHelpers.export(exports, "Conv3DDerInputProgram", ()=>Conv3DDerInputProgram);
|
|
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;
|
|
}
|
|
|
|
${isChannelsLast ? `float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);` : `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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jm349":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2DBackpropInput", ()=>conv2DBackpropInput);
|
|
parcelHelpers.export(exports, "conv2DBackpropInputConfig", ()=>conv2DBackpropInputConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convBackpropGpu = require("../conv_backprop_gpu");
|
|
var _convBackpropPackedGpu = require("../conv_backprop_packed_gpu");
|
|
function conv2DBackpropInput(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, filter } = inputs;
|
|
const { inputShape, strides, pad, dataFormat, dimRoundingMode } = attrs;
|
|
const $dataFormat = (0, _tfjsCore.backend_util).convertConv2DDataFormat(dataFormat);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(inputShape, filter.shape, strides, 1 /* dilations */ , pad, dimRoundingMode, false, $dataFormat);
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_PACK_CONV2DTRANSPOSE") && $dataFormat === "channelsLast") {
|
|
const customValues = [
|
|
[
|
|
convInfo.strideHeight,
|
|
convInfo.strideWidth
|
|
]
|
|
];
|
|
const program = new (0, _convBackpropPackedGpu.Conv2DDerInputPackedProgram)(convInfo);
|
|
return backend.runWebGLProgram(program, [
|
|
dy,
|
|
filter
|
|
], "float32", customValues);
|
|
} else {
|
|
const program = new (0, _convBackpropGpu.Conv2DDerInputProgram)(convInfo);
|
|
return backend.runWebGLProgram(program, [
|
|
dy,
|
|
filter
|
|
], "float32");
|
|
}
|
|
}
|
|
const conv2DBackpropInputConfig = {
|
|
kernelName: (0, _tfjsCore.Conv2DBackpropInput),
|
|
backendName: "webgl",
|
|
kernelFunc: conv2DBackpropInput
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_backprop_gpu":"1yzYs","../conv_backprop_packed_gpu":"3Ktdq","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3Ktdq":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Conv2DDerInputPackedProgram", ()=>Conv2DDerInputPackedProgram);
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
class Conv2DDerInputPackedProgram {
|
|
constructor(convInfo){
|
|
this.variableNames = [
|
|
"dy",
|
|
"W"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.customUniforms = [
|
|
{
|
|
name: "strides",
|
|
type: "vec2"
|
|
}
|
|
];
|
|
this.outputShape = convInfo.inShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
const filterHeight = convInfo.filterHeight;
|
|
const filterWidth = convInfo.filterWidth;
|
|
const padTop = filterHeight - 1 - convInfo.padInfo.top;
|
|
const padLeft = filterWidth - 1 - convInfo.padInfo.left;
|
|
this.userCode = `
|
|
const ivec2 pads = ivec2(${padTop}, ${padLeft});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
|
|
ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
vec4 result = vec4(0.);
|
|
for (int wR = 0; wR < ${filterHeight}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / strides[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++) {
|
|
int wCPerm = ${filterWidth} - 1 - wC;
|
|
|
|
float dyC = float(dyCCorner + wC) / strides[1];
|
|
bool idyCVal = (dyC >= 0.0) && (dyC < ${convInfo.outWidth}.0)
|
|
&& (fract(dyC) == 0.0);
|
|
int idyC = int(dyC);
|
|
|
|
float dyC2 = float(dyCCorner + wC + 1) / strides[1];
|
|
bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${convInfo.outWidth}.0)
|
|
&& (fract(dyC2) == 0.0);
|
|
int idyC2 = int(dyC2);
|
|
|
|
if (idyCVal && idyCVal2) {
|
|
for (int d2 = 0; d2 < ${convInfo.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC, d2);
|
|
vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
|
|
dySample : getDy(batch, idyR, idyC2, d2);
|
|
|
|
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.xy += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
|
|
dyValue = mod(float(idyC2), 2.) == 0. ?
|
|
dySample2.xy : dySample2.zw;
|
|
result.zw += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
} else if (idyCVal) {
|
|
for (int d2 = 0; d2 < ${convInfo.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC, d2);
|
|
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.xy += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
} else if (idyCVal2) {
|
|
for (int d2 = 0; d2 < ${convInfo.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC2, d2);
|
|
vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.zw += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c8Gvg":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3D", ()=>conv3D);
|
|
parcelHelpers.export(exports, "conv3DConfig", ()=>conv3DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convGpu = require("../conv_gpu");
|
|
function conv3D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter } = inputs;
|
|
const { strides, pad, dilations } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv3DInfo(x.shape, filter.shape, strides, dilations, pad);
|
|
const program = new (0, _convGpu.Conv3DProgram)(convInfo);
|
|
return backend.runWebGLProgram(program, [
|
|
x,
|
|
filter
|
|
], "float32");
|
|
}
|
|
const conv3DConfig = {
|
|
kernelName: (0, _tfjsCore.Conv3D),
|
|
backendName: "webgl",
|
|
kernelFunc: conv3D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_gpu":"3pfYb","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lV1Z3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3DBackpropFilterV2", ()=>conv3DBackpropFilterV2);
|
|
parcelHelpers.export(exports, "conv3DBackpropFilterV2Config", ()=>conv3DBackpropFilterV2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convBackpropGpu = require("../conv_backprop_gpu");
|
|
function conv3DBackpropFilterV2(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, dy } = inputs;
|
|
const { strides, pad, filterShape } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv3DInfo(x.shape, filterShape, strides, 1 /* dilations */ , pad);
|
|
const program = new (0, _convBackpropGpu.Conv3DDerFilterProgram)(convInfo);
|
|
return backend.runWebGLProgram(program, [
|
|
x,
|
|
dy
|
|
], "float32");
|
|
}
|
|
const conv3DBackpropFilterV2Config = {
|
|
kernelName: (0, _tfjsCore.Conv3DBackpropFilterV2),
|
|
backendName: "webgl",
|
|
kernelFunc: conv3DBackpropFilterV2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_backprop_gpu":"1yzYs","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fnJFd":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3DBackpropInput", ()=>conv3DBackpropInput);
|
|
parcelHelpers.export(exports, "conv3DBackpropInputConfig", ()=>conv3DBackpropInputConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convBackpropGpu = require("../conv_backprop_gpu");
|
|
function conv3DBackpropInput(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, filter } = inputs;
|
|
const { pad, strides, inputShape } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv3DInfo(inputShape, filter.shape, strides, 1 /* dilations */ , pad);
|
|
const program = new (0, _convBackpropGpu.Conv3DDerInputProgram)(convInfo);
|
|
return backend.runWebGLProgram(program, [
|
|
dy,
|
|
filter
|
|
], "float32");
|
|
}
|
|
const conv3DBackpropInputConfig = {
|
|
kernelName: (0, _tfjsCore.Conv3DBackpropInputV2),
|
|
backendName: "webgl",
|
|
kernelFunc: conv3DBackpropInput
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_backprop_gpu":"1yzYs","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2H7EX":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cos", ()=>cos);
|
|
parcelHelpers.export(exports, "cosConfig", ()=>cosConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const COS = (0, _kernelFuncsUtils.CHECK_NAN_SNIPPET_UNARY) + `
|
|
return cos(x);
|
|
`;
|
|
const COS_PACKED = `
|
|
vec4 result = cos(x);
|
|
bvec4 isNaN = isnan(x);
|
|
${(0, _binaryopPackedGpu.CHECK_NAN_SNIPPET_PACKED)}
|
|
return result;
|
|
`;
|
|
const cos = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: COS,
|
|
packedOpSnippet: COS_PACKED
|
|
});
|
|
const cosConfig = {
|
|
kernelName: (0, _tfjsCore.Cos),
|
|
backendName: "webgl",
|
|
kernelFunc: cos
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_packed_gpu":"hkzp7","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jBLJs":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cosh", ()=>cosh);
|
|
parcelHelpers.export(exports, "coshConfig", ()=>coshConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const COSH = `
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`;
|
|
const cosh = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: COSH
|
|
});
|
|
const coshConfig = {
|
|
kernelName: (0, _tfjsCore.Cosh),
|
|
backendName: "webgl",
|
|
kernelFunc: cosh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aCuUK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cropAndResize", ()=>cropAndResize);
|
|
parcelHelpers.export(exports, "cropAndResizeConfig", ()=>cropAndResizeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cropAndResizeGpu = require("../crop_and_resize_gpu");
|
|
const cropAndResize = (args)=>{
|
|
const { inputs, backend, attrs } = args;
|
|
const { image, boxes, boxInd } = inputs;
|
|
const { cropSize, method, extrapolationValue } = attrs;
|
|
const program = new (0, _cropAndResizeGpu.CropAndResizeProgram)(image.shape, boxes.shape, cropSize, method, extrapolationValue);
|
|
return backend.runWebGLProgram(program, [
|
|
image,
|
|
boxes,
|
|
boxInd
|
|
], "float32");
|
|
};
|
|
const cropAndResizeConfig = {
|
|
kernelName: (0, _tfjsCore.CropAndResize),
|
|
backendName: "webgl",
|
|
kernelFunc: cropAndResize
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../crop_and_resize_gpu":"86aq9","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"86aq9":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "CropAndResizeProgram", ()=>CropAndResizeProgram);
|
|
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);
|
|
}
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fIbv6":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cumprod", ()=>cumprod);
|
|
parcelHelpers.export(exports, "cumprodConfig", ()=>cumprodConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cumGpu = require("../cum_gpu");
|
|
var _cumImpl = require("./Cum_impl");
|
|
function cumprod(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, exclusive, reverse } = attrs;
|
|
return (0, _cumImpl.cumImpl)((0, _cumGpu.CumOpType).Prod, x, backend, axis, exclusive, reverse);
|
|
}
|
|
const cumprodConfig = {
|
|
kernelName: (0, _tfjsCore.Cumprod),
|
|
backendName: "webgl",
|
|
kernelFunc: cumprod
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cum_gpu":"2Zgho","./Cum_impl":"4IsXf","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2Zgho":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "CumOpType", ()=>CumOpType);
|
|
parcelHelpers.export(exports, "CumProgram", ()=>CumProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
var CumOpType;
|
|
(function(CumOpType) {
|
|
CumOpType["Prod"] = "*";
|
|
CumOpType["Sum"] = "+";
|
|
})(CumOpType || (CumOpType = {}));
|
|
class CumProgram {
|
|
constructor(op, outputShape, exclusive, reverse){
|
|
this.op = op;
|
|
this.outputShape = outputShape;
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
this.customUniforms = [
|
|
{
|
|
name: "index",
|
|
type: "float"
|
|
}
|
|
];
|
|
const rank = this.outputShape.length;
|
|
const initVal = this.op === CumOpType.Prod ? "1.0" : "0.0";
|
|
const val = exclusive ? initVal : `getX(${getCoords(rank, "coords", this.op)})`;
|
|
const length = this.outputShape[this.outputShape.length - 1];
|
|
let condition = "";
|
|
let idxString = "";
|
|
// When exclusive is set, the cum op becomes roll op that copies the
|
|
// value from the previous index based on the direction specified by the
|
|
// reverse flag.
|
|
if (exclusive) {
|
|
condition = reverse ? `end != ${length - 1}` : "end != 0";
|
|
idxString = reverse ? "end + 1" : "end - 1";
|
|
} else {
|
|
condition = reverse ? `end + pow2 < ${length}` : "end >= pow2";
|
|
idxString = reverse ? "end + pow2" : "end - pow2";
|
|
}
|
|
this.userCode = `
|
|
void main() {
|
|
${(0, _shaderCompiler.getCoordsDataType)(rank)} coords = getOutputCoords();
|
|
int end = ${getFinalCoord(rank, "coords", this.op)};
|
|
float val = ${val};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${condition}) {
|
|
int idx = ${idxString};
|
|
${getFinalCoord(rank, "coords", this.op)} = idx;
|
|
val ${this.op}= getX(${getCoords(rank, "coords", this.op)});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
function getCoords(rank, name, op) {
|
|
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 new Error(`Cumulative ${op} for rank ${rank} is not yet supported`);
|
|
}
|
|
function getFinalCoord(rank, name, op) {
|
|
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 new Error(`Cumulative ${op} for rank ${rank} is not yet supported`);
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4IsXf":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cumImpl", ()=>cumImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cumGpu = require("../cum_gpu");
|
|
var _identity = require("./Identity");
|
|
var _transpose = require("./Transpose");
|
|
function cumImpl(op, x, backend, axis, exclusive, reverse) {
|
|
const xRank = x.shape.length;
|
|
const permutation = (0, _tfjsCore.backend_util).getAxesPermutation([
|
|
axis
|
|
], xRank);
|
|
let permutedX = x;
|
|
if (permutation != null) permutedX = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutation
|
|
}
|
|
});
|
|
const permutedAxis = (0, _tfjsCore.backend_util).getInnerMostAxes(1, xRank)[0];
|
|
if (permutedAxis !== xRank - 1) throw new Error(`WebGL cumprod shader expects an inner-most axis=${x.shape.length - 1} ` + `but got axis=${axis}`);
|
|
const size = permutedX.shape[permutedAxis];
|
|
let result = (0, _identity.identity)({
|
|
inputs: {
|
|
x: permutedX
|
|
},
|
|
backend
|
|
});
|
|
// Use cum parallel algorithm, inspired by:
|
|
// https://developer.nvidia.com/gpugems/gpugems3/part-vi-gpu-computing/chapter-39-parallel-prefix-sum-scan-cuda
|
|
// Note: although the algorithm is called sum, it works for any associtative
|
|
// operator with an identity.
|
|
for(let i = 0; i <= Math.ceil(Math.log2(size)) - 1; i++){
|
|
const program = new (0, _cumGpu.CumProgram)(op, permutedX.shape, false, reverse);
|
|
const customValues = [
|
|
[
|
|
i
|
|
]
|
|
];
|
|
const prevResult = result;
|
|
result = backend.runWebGLProgram(program, [
|
|
result
|
|
], result.dtype, customValues);
|
|
backend.disposeIntermediateTensorInfo(prevResult);
|
|
}
|
|
// For exclusive cum, shift the end result in the direction of product or sum
|
|
// and add 1 for product or 0 for sum to the front index.
|
|
if (exclusive) {
|
|
const program = new (0, _cumGpu.CumProgram)(op, permutedX.shape, exclusive, reverse);
|
|
const prevResult = result;
|
|
result = backend.runWebGLProgram(program, [
|
|
result
|
|
], result.dtype);
|
|
backend.disposeIntermediateTensorInfo(prevResult);
|
|
}
|
|
if (permutation != null) {
|
|
const reversePermutation = (0, _tfjsCore.backend_util).getUndoAxesPermutation(permutation);
|
|
const reverseTransposedResult = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: reversePermutation
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
backend.disposeIntermediateTensorInfo(permutedX);
|
|
return reverseTransposedResult;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cum_gpu":"2Zgho","./Identity":"hY9aT","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"l2jIP":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cumsum", ()=>cumsum);
|
|
parcelHelpers.export(exports, "cumsumConfig", ()=>cumsumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cumGpu = require("../cum_gpu");
|
|
var _cumImpl = require("./Cum_impl");
|
|
function cumsum(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, exclusive, reverse } = attrs;
|
|
return (0, _cumImpl.cumImpl)((0, _cumGpu.CumOpType).Sum, x, backend, axis, exclusive, reverse);
|
|
}
|
|
const cumsumConfig = {
|
|
kernelName: (0, _tfjsCore.Cumsum),
|
|
backendName: "webgl",
|
|
kernelFunc: cumsum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cum_gpu":"2Zgho","./Cum_impl":"4IsXf","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7qaEa":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "denseBincount", ()=>denseBincount);
|
|
parcelHelpers.export(exports, "denseBincountConfig", ()=>denseBincountConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function denseBincount(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, weights } = inputs;
|
|
const { size, binaryOutput } = attrs;
|
|
if (x.shape.length === 1) {
|
|
const xVals = backend.readSync(x.dataId);
|
|
const weightsVals = backend.readSync(weights.dataId);
|
|
const outVals = (0, _shared.bincountImplCPU)(xVals, weightsVals, weights.dtype, weights.shape, size);
|
|
return backend.makeTensorInfo([
|
|
size
|
|
], weights.dtype, outVals);
|
|
} else if (x.shape.length === 2) {
|
|
const xBuf = backend.bufferSync(x);
|
|
const weightsBuf = backend.bufferSync(weights);
|
|
const outBuf = (0, _shared.bincountReduceImplCPU)(xBuf, weightsBuf, size, binaryOutput);
|
|
return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);
|
|
}
|
|
throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank` + `${x.shape.length}.`);
|
|
}
|
|
const denseBincountConfig = {
|
|
kernelName: (0, _tfjsCore.DenseBincount),
|
|
backendName: "webgl",
|
|
kernelFunc: denseBincount
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"926cY":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthToSpace", ()=>depthToSpace);
|
|
parcelHelpers.export(exports, "depthToSpaceConfig", ()=>depthToSpaceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _depthToSpaceGpu = require("../depth_to_space_gpu");
|
|
function depthToSpace(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { blockSize, dataFormat } = attrs;
|
|
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 (0, _depthToSpaceGpu.DepthToSpaceProgram)(outputShape, blockSize, dataFormat);
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
const depthToSpaceConfig = {
|
|
kernelName: (0, _tfjsCore.DepthToSpace),
|
|
backendName: "webgl",
|
|
kernelFunc: depthToSpace
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../depth_to_space_gpu":"Zy6T9","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"Zy6T9":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DepthToSpaceProgram", ()=>DepthToSpaceProgram);
|
|
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)`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9xbgW":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNative", ()=>depthwiseConv2dNative);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeConfig", ()=>depthwiseConv2dNativeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convGpuDepthwise = require("../conv_gpu_depthwise");
|
|
var _convPackedGpuDepthwise = require("../conv_packed_gpu_depthwise");
|
|
function depthwiseConv2dNative(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter } = inputs;
|
|
const { strides, pad, dilations, dimRoundingMode } = attrs;
|
|
let $dilations = dilations;
|
|
if ($dilations == null) $dilations = [
|
|
1,
|
|
1
|
|
];
|
|
(0, _tfjsCore.util).assert((0, _tfjsCore.backend_util).eitherStridesOrDilationsAreOne(strides, $dilations), ()=>"Error in depthwiseConv2d: Either strides or dilations must be " + `1. Got strides ${strides} and dilations '${$dilations}'`);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filter.shape, strides, $dilations, pad, dimRoundingMode, true);
|
|
let program;
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_PACK_DEPTHWISECONV") && convInfo.strideWidth <= 2 && convInfo.outChannels / convInfo.inChannels === 1) program = new (0, _convPackedGpuDepthwise.DepthwiseConvPacked2DProgram)(convInfo);
|
|
else program = new (0, _convGpuDepthwise.DepthwiseConv2DProgram)(convInfo);
|
|
const customValues = [
|
|
[
|
|
convInfo.padInfo.top,
|
|
convInfo.padInfo.left
|
|
],
|
|
[
|
|
convInfo.strideHeight,
|
|
convInfo.strideWidth
|
|
],
|
|
[
|
|
convInfo.dilationHeight,
|
|
convInfo.dilationWidth
|
|
],
|
|
[
|
|
convInfo.inHeight,
|
|
convInfo.inWidth
|
|
]
|
|
];
|
|
return backend.runWebGLProgram(program, [
|
|
x,
|
|
filter
|
|
], "float32", customValues);
|
|
}
|
|
const depthwiseConv2dNativeConfig = {
|
|
kernelName: (0, _tfjsCore.DepthwiseConv2dNative),
|
|
backendName: "webgl",
|
|
kernelFunc: depthwiseConv2dNative
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_gpu_depthwise":"31MV7","../conv_packed_gpu_depthwise":"aG31s","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"31MV7":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DepthwiseConv2DProgram", ()=>DepthwiseConv2DProgram);
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
class DepthwiseConv2DProgram {
|
|
constructor(convInfo, addBias = false, activation = null, hasPreluActivation = false, hasLeakyReluAlpha = false){
|
|
this.variableNames = [
|
|
"x",
|
|
"W"
|
|
];
|
|
this.customUniforms = [
|
|
{
|
|
name: "pads",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "strides",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "dilations",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "inDims",
|
|
type: "ivec2"
|
|
}
|
|
];
|
|
this.outputShape = convInfo.outShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
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 if (hasLeakyReluAlpha) activationSnippet = `float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${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");
|
|
if (hasLeakyReluAlpha) this.variableNames.push("leakyreluAlpha");
|
|
this.userCode = `
|
|
${activationSnippet}
|
|
|
|
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 * dilations[0];
|
|
|
|
if (xR < 0 || xR >= inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${filterWidth}; wC++) {
|
|
int xC = xCCorner + wC * dilations[1];
|
|
|
|
if (xC < 0 || xC >= inDims[1]) {
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aG31s":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DepthwiseConvPacked2DProgram", ()=>DepthwiseConvPacked2DProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gpgpuMath = require("./gpgpu_math");
|
|
class DepthwiseConvPacked2DProgram {
|
|
constructor(convInfo, addBias = false, activation = null, hasPreluActivation = false, hasLeakyReluAlpha = false){
|
|
this.variableNames = [
|
|
"x",
|
|
"W"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.customUniforms = [
|
|
{
|
|
name: "pads",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "strides",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "dilations",
|
|
type: "ivec2"
|
|
},
|
|
{
|
|
name: "inDims",
|
|
type: "ivec2"
|
|
}
|
|
];
|
|
this.outputShape = convInfo.outShape;
|
|
this.enableShapeUniforms = (0, _gpgpuMath.useShapeUniforms)(this.outputShape.length);
|
|
const channelMul = convInfo.outChannels / convInfo.inChannels;
|
|
const padLeft = convInfo.padInfo.left;
|
|
const strideWidth = convInfo.strideWidth;
|
|
const dilationWidth = convInfo.dilationWidth;
|
|
const filterHeight = convInfo.filterHeight;
|
|
const filterWidth = convInfo.filterWidth;
|
|
const texelsAcross = filterWidth;
|
|
let mainLoop = `
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;
|
|
for(let c = 0; c < filterWidth; c++)mainLoop += `
|
|
vec4 xTexelC${c * 2};
|
|
int xTexelC${c * 2}Ready;
|
|
vec4 xTexelC${c * 2 + 1};
|
|
int xTexelC${c * 2 + 1}Ready;
|
|
vec4 xC${c};`;
|
|
/**
|
|
* 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.
|
|
*/ mainLoop += `
|
|
for (int r = 0; r < ${filterHeight}; r++) {
|
|
`;
|
|
for(let c = 0; c < filterWidth; c++)mainLoop += `
|
|
xTexelC${c * 2} = vec4(0.0);
|
|
xTexelC${c * 2}Ready = 0;
|
|
xTexelC${c * 2 + 1} = vec4(0.0);
|
|
xTexelC${c * 2 + 1}Ready = 0;
|
|
xC${c} = vec4(0.0);`;
|
|
mainLoop += `
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;
|
|
for(let texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++){
|
|
const colIndex = texelC * 2;
|
|
mainLoop += `
|
|
xC = xCCorner + ${colIndex * dilationWidth};
|
|
`;
|
|
if (strideWidth === 1) {
|
|
if (colIndex < 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 (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex}Ready == 0) {
|
|
xTexelC${colIndex} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex}Ready = 1;
|
|
}
|
|
`;
|
|
// This texel has been read in previous iteration if the dilation
|
|
// is 1.
|
|
if (dilationWidth === 1 && colIndex > 0) mainLoop += `
|
|
xC${colIndex} = vec4(xTexelC${colIndex - 2}.zw, xTexelC${colIndex}.xy);
|
|
`;
|
|
else mainLoop += `
|
|
xCOffset = xC + 1 - 2;
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
previous.zw = vec2(0.0);
|
|
}
|
|
|
|
xC${colIndex} = vec4(previous.zw, xTexelC${colIndex}.xy);
|
|
} else {
|
|
xC${colIndex} = vec4(0.0, 0.0, xTexelC${colIndex}.xy);
|
|
}
|
|
`;
|
|
} else // Padding is even, so xRC corresponds to a single texel.
|
|
mainLoop += `
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${colIndex}Ready == 0) {
|
|
xTexelC${colIndex} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${colIndex}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex}Ready = 1;
|
|
}
|
|
|
|
xC${colIndex} = xTexelC${colIndex};
|
|
`;
|
|
if (colIndex + 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 ? (0, _tfjsCore.util).nearestLargerEven(dilationWidth) : dilationWidth;
|
|
if (dilationWidth % 2 === 0 && padLeft % 2 === 1 || dilationWidth % 2 !== 0 && padLeft % 2 !== 1) {
|
|
mainLoop += `
|
|
xCOffset = xC + imod(pads[1], 2) + ${nextTexelOffset};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex + 1}Ready == 0) {
|
|
xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex + 1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex + 1}Ready = 1;
|
|
}
|
|
`;
|
|
// 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 (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
xC${colIndex + 1} = vec4(previous.zw, xTexelC${colIndex + 1}.xy);
|
|
} else {
|
|
xC${colIndex + 1} = vec4(0.0, 0.0, xTexelC${colIndex + 1}.xy);
|
|
}
|
|
`;
|
|
else mainLoop += `
|
|
xC${colIndex + 1} = vec4(xTexelC${colIndex}.zw, xTexelC${colIndex + 1}.xy);
|
|
`;
|
|
} else // If dilation is 1 and padding is odd, we have already read the
|
|
// texel when constructing the previous x value. Here we can
|
|
// simply skip the texture read.
|
|
if (nextTexelOffset === 1) mainLoop += `
|
|
xC${colIndex + 1} = xTexelC${colIndex};
|
|
`;
|
|
else mainLoop += `
|
|
xCOffset = xC + ${nextTexelOffset};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex + 1}Ready == 0) {
|
|
xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex + 1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex + 1}Ready = 1;
|
|
}
|
|
|
|
xC${colIndex + 1} = xTexelC${colIndex + 1};
|
|
`;
|
|
}
|
|
}
|
|
} else if (colIndex < filterWidth) {
|
|
// Depending on whether padLeft is even or odd, we want either the
|
|
// xy or zw channels from X texels for xC${colIndex}. If padLeft is
|
|
// even, xC${colIndex +1} is simply the zw channels of texels we've
|
|
// already sampled. But if padLeft is odd, xC{$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 - strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex}Ready == 0) {
|
|
xTexelC${colIndex} = getX(batch, xR, xCOffset, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${colIndex + 1}Ready == 0) {
|
|
xTexelC${colIndex + 1} = getX(batch, xR, xC + 1, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xC + 2 >= inDims[1]) {
|
|
xTexelC${colIndex + 1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex + 1}Ready = 1;
|
|
}
|
|
|
|
xC${colIndex} = vec4(xTexelC${colIndex}.zw, xTexelC${colIndex + 1}.zw);
|
|
`;
|
|
if (colIndex + 1 < filterWidth) mainLoop += `
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${colIndex + 1} = vec4(xTexelC${colIndex + 1}.xy, final.xy);
|
|
`;
|
|
} else {
|
|
mainLoop += `
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${colIndex}Ready == 0) {
|
|
xTexelC${colIndex} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${colIndex}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${colIndex}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${colIndex + 1}Ready == 0) {
|
|
xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${colIndex + 1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${colIndex + 1}Ready = 1;
|
|
}
|
|
|
|
xC${colIndex} = vec4(
|
|
xTexelC${colIndex}.xy, xTexelC${colIndex + 1}.xy);
|
|
`;
|
|
if (colIndex + 1 < filterWidth) mainLoop += `
|
|
xC${colIndex + 1} = vec4(xTexelC${colIndex}.zw, xTexelC${colIndex + 1}.zw);
|
|
`;
|
|
}
|
|
}
|
|
// localize the dotProd accumulation within the loop, the theory is for
|
|
// GPU with limited cache, accumulate sum across large amount of
|
|
// veriables will cause lots of cache misses. (i.e. 5x5 filter will have
|
|
// 50 variables)
|
|
if (colIndex < filterWidth) {
|
|
mainLoop += `
|
|
wTexel = getW(r, ${colIndex}, d1, q);
|
|
dotProd += xC${colIndex} * vec4(wTexel.xz, wTexel.xz);
|
|
`;
|
|
if (colIndex + 1 < filterWidth) mainLoop += `
|
|
wTexel = getW(r, ${colIndex + 1}, d1, q);
|
|
dotProd += xC${colIndex + 1} * vec4(wTexel.xz, wTexel.xz);
|
|
`;
|
|
}
|
|
}
|
|
mainLoop += `
|
|
}
|
|
`;
|
|
mainLoop += `
|
|
}
|
|
`;
|
|
let activationSnippet = "", applyActivationSnippet = "";
|
|
if (activation) {
|
|
if (hasPreluActivation) activationSnippet = `vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${activation}
|
|
}`;
|
|
else if (hasLeakyReluAlpha) activationSnippet = `vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${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");
|
|
if (hasLeakyReluAlpha) this.variableNames.push("leakyreluAlpha");
|
|
this.userCode = `
|
|
${activationSnippet}
|
|
|
|
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;
|
|
|
|
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
|
|
vec4 dotProd = vec4(0.000000000000001);
|
|
|
|
${mainLoop}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${addBiasSnippet}
|
|
${applyActivationSnippet}
|
|
setOutput(result);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./gpgpu_math":"btJo5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aWI5l":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropFilter", ()=>depthwiseConv2dNativeBackpropFilter);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropFilterConfig", ()=>depthwiseConv2dNativeBackpropFilterConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convBackpropGpuDepthwise = require("../conv_backprop_gpu_depthwise");
|
|
function depthwiseConv2dNativeBackpropFilter(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, dy } = inputs;
|
|
const { strides, dilations, pad, dimRoundingMode, filterShape } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filterShape, strides, dilations, pad, dimRoundingMode, true);
|
|
const program = new (0, _convBackpropGpuDepthwise.DepthwiseConv2DDerFilterProgram)(convInfo);
|
|
return backend.runWebGLProgram(program, [
|
|
x,
|
|
dy
|
|
], "float32");
|
|
}
|
|
const depthwiseConv2dNativeBackpropFilterConfig = {
|
|
kernelName: (0, _tfjsCore.DepthwiseConv2dNativeBackpropFilter),
|
|
backendName: "webgl",
|
|
kernelFunc: depthwiseConv2dNativeBackpropFilter
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_backprop_gpu_depthwise":"8UMrV","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8UMrV":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DepthwiseConv2DDerFilterProgram", ()=>DepthwiseConv2DDerFilterProgram);
|
|
parcelHelpers.export(exports, "DepthwiseConv2DDerInputProgram", ()=>DepthwiseConv2DDerInputProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6HZVm":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropInput", ()=>depthwiseConv2dNativeBackpropInput);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropInputConfig", ()=>depthwiseConv2dNativeBackpropInputConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convBackpropGpuDepthwise = require("../conv_backprop_gpu_depthwise");
|
|
function depthwiseConv2dNativeBackpropInput(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, filter } = inputs;
|
|
const { strides, dilations, pad, dimRoundingMode, inputShape } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(inputShape, filter.shape, strides, dilations, pad, dimRoundingMode, true);
|
|
const program = new (0, _convBackpropGpuDepthwise.DepthwiseConv2DDerInputProgram)(convInfo);
|
|
return backend.runWebGLProgram(program, [
|
|
dy,
|
|
filter
|
|
], "float32");
|
|
}
|
|
const depthwiseConv2dNativeBackpropInputConfig = {
|
|
kernelName: (0, _tfjsCore.DepthwiseConv2dNativeBackpropInput),
|
|
backendName: "webgl",
|
|
kernelFunc: depthwiseConv2dNativeBackpropInput
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_backprop_gpu_depthwise":"8UMrV","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7TZuU":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "diag", ()=>diag);
|
|
parcelHelpers.export(exports, "diagConfig", ()=>diagConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _diagGpu = require("../diag_gpu");
|
|
var _reshape = require("./Reshape");
|
|
function diag(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
const outShape = [
|
|
...x.shape,
|
|
...x.shape
|
|
];
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const flat = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
xSize
|
|
]
|
|
}
|
|
});
|
|
const program = new (0, _diagGpu.DiagProgram)(xSize);
|
|
const res = backend.runWebGLProgram(program, [
|
|
flat
|
|
], flat.dtype);
|
|
const out = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: res
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(flat);
|
|
backend.disposeIntermediateTensorInfo(res);
|
|
return out;
|
|
}
|
|
const diagConfig = {
|
|
kernelName: (0, _tfjsCore.Diag),
|
|
backendName: "webgl",
|
|
kernelFunc: diag
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../diag_gpu":"aR5cG","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aR5cG":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DiagProgram", ()=>DiagProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lLrqs":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "dilation2D", ()=>dilation2D);
|
|
parcelHelpers.export(exports, "dilation2DConfig", ()=>dilation2DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _dilationGpu = require("../dilation_gpu");
|
|
var _reshape = require("./Reshape");
|
|
function dilation2D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter } = inputs;
|
|
const { strides, pad, dilations } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computeDilation2DInfo(x.shape, filter.shape, strides, pad, "NHWC" /* dataFormat */ , dilations);
|
|
let out;
|
|
const program = new (0, _dilationGpu.Dilation2DProgram)(convInfo);
|
|
out = backend.runWebGLProgram(program, [
|
|
x,
|
|
filter
|
|
], "float32");
|
|
const outReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: out
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: convInfo.outShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(out);
|
|
return outReshaped;
|
|
}
|
|
const dilation2DConfig = {
|
|
kernelName: (0, _tfjsCore.Dilation2D),
|
|
backendName: "webgl",
|
|
kernelFunc: dilation2D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../dilation_gpu":"3pogG","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3pogG":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "Dilation2DProgram", ()=>Dilation2DProgram);
|
|
class Dilation2DProgram {
|
|
constructor(convInfo){
|
|
this.variableNames = [
|
|
"x",
|
|
"W"
|
|
];
|
|
this.outputShape = convInfo.outShape;
|
|
const { inHeight, inWidth, padInfo, strideHeight, strideWidth, filterHeight, filterWidth, dilationHeight, dilationWidth } = convInfo;
|
|
const { top: padTop, left: padLeft } = padInfo;
|
|
this.userCode = `
|
|
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
|
|
const ivec2 pads = ivec2(${padTop}, ${padLeft});
|
|
const float neg_infinity = -3.4e38;
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.w;
|
|
ivec2 outTopLeftCorner =
|
|
coords.yz * strides - pads;
|
|
int hBeg = outTopLeftCorner.x;
|
|
int wBeg = outTopLeftCorner.y;
|
|
|
|
float curVal = neg_infinity;
|
|
for (int h = 0; h < ${filterHeight}; h++) {
|
|
int hIn = hBeg + h * ${dilationHeight};
|
|
|
|
if (hIn >= 0 && hIn < ${inHeight}) {
|
|
for (int w = 0; w < ${filterWidth}; w++) {
|
|
int wIn = wBeg + w * ${dilationWidth};
|
|
|
|
if (wIn >= 0 && wIn < ${inWidth}) {
|
|
float xVal = getX(batch, hIn, wIn, d1);
|
|
float wVal = getW(h, w, d1);
|
|
|
|
float val = xVal + wVal;
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = curVal;
|
|
setOutput(result);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hmWYw":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "einsum", ()=>einsum);
|
|
parcelHelpers.export(exports, "einsumConfig", ()=>einsumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _multiply = require("./Multiply");
|
|
var _reshape = require("./Reshape");
|
|
var _sum = require("./Sum");
|
|
var _transpose = require("./Transpose");
|
|
function einsum(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { equation } = attrs;
|
|
const tensors = inputs;
|
|
const { allDims, summedDims, idDims } = (0, _tfjsCore.backend_util).decodeEinsumEquation(equation, tensors.length);
|
|
(0, _tfjsCore.backend_util).checkEinsumDimSizes(allDims.length, idDims, tensors);
|
|
const { path, steps } = (0, _tfjsCore.backend_util).getEinsumComputePath(summedDims, idDims);
|
|
const nSteps = steps.length;
|
|
let out = null;
|
|
let numDimsRemaining = allDims.length;
|
|
const tensorsToDispose = [];
|
|
for(let i = 0; i < nSteps; ++i){
|
|
for (const idTerm of steps[i]){
|
|
const { permutationIndices: perm, expandDims: dimsToExpand } = (0, _tfjsCore.backend_util).getEinsumPermutation(numDimsRemaining, idDims[idTerm]);
|
|
let x;
|
|
if ((0, _tfjsCore.backend_util).isIdentityPermutation(perm)) x = tensors[idTerm];
|
|
else {
|
|
x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: tensors[idTerm]
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm
|
|
}
|
|
});
|
|
tensorsToDispose.push(x);
|
|
}
|
|
const targetShape = x.shape.slice();
|
|
for(let k = 0; k < dimsToExpand.length; ++k)targetShape.splice(dimsToExpand[k], 0, 1);
|
|
if (!(0, _tfjsCore.util).arraysEqual(x.shape, targetShape)) {
|
|
x = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: targetShape
|
|
}
|
|
});
|
|
tensorsToDispose.push(x);
|
|
}
|
|
if (out === null) out = x;
|
|
else {
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
out = (0, _multiply.multiply)({
|
|
inputs: {
|
|
a: x,
|
|
b: out
|
|
},
|
|
backend
|
|
});
|
|
tensorsToDispose.push(out);
|
|
}
|
|
}
|
|
if (i < nSteps - 1) {
|
|
if (path[i] >= 0) {
|
|
out = (0, _sum.sum)({
|
|
inputs: {
|
|
x: out
|
|
},
|
|
backend,
|
|
attrs: {
|
|
axis: path[i] - (allDims.length - numDimsRemaining),
|
|
keepDims: false
|
|
}
|
|
});
|
|
tensorsToDispose.push(out);
|
|
}
|
|
numDimsRemaining--;
|
|
}
|
|
}
|
|
// Clean up intermediate tensors.
|
|
for (const tensorInfo of tensorsToDispose){
|
|
if (tensorInfo === out) continue;
|
|
backend.disposeIntermediateTensorInfo(tensorInfo);
|
|
}
|
|
return out;
|
|
}
|
|
const einsumConfig = {
|
|
kernelName: (0, _tfjsCore.Einsum),
|
|
backendName: "webgl",
|
|
kernelFunc: einsum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Multiply":"5ePR8","./Reshape":"fgZen","./Sum":"c4eiD","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fJBTw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "eluConfig", ()=>eluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const ELU = `return (x >= 0.0) ? x : (exp(x) - 1.0);`;
|
|
const ELU_PACKED = `
|
|
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;
|
|
`;
|
|
const elu = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ELU,
|
|
packedOpSnippet: ELU_PACKED
|
|
});
|
|
const eluConfig = {
|
|
kernelName: (0, _tfjsCore.Elu),
|
|
backendName: "webgl",
|
|
kernelFunc: elu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hjBqq":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "eluGrad", ()=>eluGrad);
|
|
parcelHelpers.export(exports, "eluGradConfig", ()=>eluGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
const ELU_DER = `return (b >= 0.0) ? a : a * (b + 1.0);`;
|
|
const ELU_DER_PACKED = `
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`;
|
|
const eluGrad = (args)=>{
|
|
const { inputs, backend } = args;
|
|
const { dy, y } = inputs;
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new (0, _binaryopPackedGpu.BinaryOpPackedProgram)(ELU_DER_PACKED, dy.shape, y.shape) : new (0, _binaryopGpu.BinaryOpProgram)(ELU_DER, dy.shape, y.shape);
|
|
return backend.runWebGLProgram(program, [
|
|
dy,
|
|
y
|
|
], dy.dtype);
|
|
};
|
|
const eluGradConfig = {
|
|
kernelName: (0, _tfjsCore.EluGrad),
|
|
backendName: "webgl",
|
|
kernelFunc: eluGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dNiJE":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "equal", ()=>equal);
|
|
parcelHelpers.export(exports, "equalConfig", ()=>equalConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const PACKED_EQUAL = `
|
|
return vec4(equal(a, b));
|
|
`;
|
|
const EQUAL = `return float(a == b);`;
|
|
const equal = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: EQUAL,
|
|
packedOpSnippet: PACKED_EQUAL,
|
|
dtype: "bool",
|
|
cpuKernelImpl: (0, _shared.equalImplCPU)
|
|
});
|
|
const equalConfig = {
|
|
kernelName: (0, _tfjsCore.Equal),
|
|
backendName: "webgl",
|
|
kernelFunc: equal
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ahvKl":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "erf", ()=>erf);
|
|
parcelHelpers.export(exports, "erfConfig", ()=>erfConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
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 = ${(0, _tfjsCore.backend_util).ERF_P};
|
|
float a1 = ${(0, _tfjsCore.backend_util).ERF_A1};
|
|
float a2 = ${(0, _tfjsCore.backend_util).ERF_A2};
|
|
float a3 = ${(0, _tfjsCore.backend_util).ERF_A3};
|
|
float a4 = ${(0, _tfjsCore.backend_util).ERF_A4};
|
|
float a5 = ${(0, _tfjsCore.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 erf = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ERF
|
|
});
|
|
const erfConfig = {
|
|
kernelName: (0, _tfjsCore.Erf),
|
|
backendName: "webgl",
|
|
kernelFunc: erf
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"i4xew":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "EXP", ()=>EXP);
|
|
parcelHelpers.export(exports, "exp", ()=>exp);
|
|
parcelHelpers.export(exports, "expConfig", ()=>expConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const EXP = (0, _kernelFuncsUtils.CHECK_NAN_SNIPPET_UNARY) + `
|
|
return exp(x);
|
|
`;
|
|
const EXP_PACKED = `
|
|
vec4 result = exp(x);
|
|
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 exp = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: EXP,
|
|
packedOpSnippet: EXP_PACKED,
|
|
cpuKernelImpl: (0, _shared.expImplCPU),
|
|
dtype: "float32"
|
|
});
|
|
const expConfig = {
|
|
kernelName: (0, _tfjsCore.Exp),
|
|
backendName: "webgl",
|
|
kernelFunc: exp
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5OvP3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "expandDims", ()=>expandDims);
|
|
parcelHelpers.export(exports, "expandDimsConfig", ()=>expandDimsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reshape = require("./Reshape");
|
|
function expandDims(args) {
|
|
const { inputs, attrs, backend } = args;
|
|
const { dim } = attrs;
|
|
const { input } = inputs;
|
|
const inputRank = input.shape.length;
|
|
const newShape = input.shape.slice();
|
|
let $dim = dim;
|
|
if (dim < 0) {
|
|
// Negative value is counted from the tail of rank.
|
|
(0, _tfjsCore.util).assert(-(inputRank + 1) <= dim, ()=>`Axis must be in the interval [${-(inputRank + 1)}, ${inputRank}]`);
|
|
$dim = inputRank + dim + 1;
|
|
}
|
|
newShape.splice($dim, 0, 1);
|
|
return (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: input
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: newShape
|
|
}
|
|
});
|
|
}
|
|
const expandDimsConfig = {
|
|
kernelName: (0, _tfjsCore.ExpandDims),
|
|
backendName: "webgl",
|
|
kernelFunc: expandDims
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"baClA":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "expm1", ()=>expm1);
|
|
parcelHelpers.export(exports, "expm1Config", ()=>expm1Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const EXPM1 = `return exp(x) - 1.0;`;
|
|
const expm1 = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: EXPM1,
|
|
packedOpSnippet: EXPM1,
|
|
cpuKernelImpl: (0, _shared.expm1ImplCPU)
|
|
});
|
|
const expm1Config = {
|
|
kernelName: (0, _tfjsCore.Expm1),
|
|
backendName: "webgl",
|
|
kernelFunc: expm1
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"zq0LC":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fft", ()=>fft);
|
|
parcelHelpers.export(exports, "fftConfig", ()=>fftConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fftImpl = require("./FFT_impl");
|
|
function fft(args) {
|
|
const { inputs, backend } = args;
|
|
const { input } = inputs;
|
|
return (0, _fftImpl.fftImpl)(input, false, backend);
|
|
}
|
|
const fftConfig = {
|
|
kernelName: (0, _tfjsCore.FFT),
|
|
backendName: "webgl",
|
|
kernelFunc: fft
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./FFT_impl":"ji88K","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ji88K":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fftImpl", ()=>fftImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fftGpu = require("../fft_gpu");
|
|
var _complex = require("./Complex");
|
|
var _reshape = require("./Reshape");
|
|
function fftImpl(x, inverse, backend) {
|
|
const xData = backend.texData.get(x.dataId);
|
|
const inputSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
// Collapse all outer dimensions to a single batch dimension.
|
|
const innerDimensionSize = x.shape[x.shape.length - 1];
|
|
const batch = inputSize / innerDimensionSize;
|
|
const input2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
batch,
|
|
innerDimensionSize
|
|
]
|
|
}
|
|
});
|
|
const xShape = input2D.shape;
|
|
const realProgram = new (0, _fftGpu.FFTProgram)("real", xShape, inverse);
|
|
const imagProgram = new (0, _fftGpu.FFTProgram)("imag", xShape, inverse);
|
|
const inputs = [
|
|
{
|
|
dataId: xData.complexTensorInfos.real.dataId,
|
|
dtype: xData.complexTensorInfos.real.dtype,
|
|
shape: xShape
|
|
},
|
|
{
|
|
dataId: xData.complexTensorInfos.imag.dataId,
|
|
dtype: xData.complexTensorInfos.imag.dtype,
|
|
shape: xShape
|
|
}
|
|
];
|
|
const realPart = backend.runWebGLProgram(realProgram, inputs, "float32");
|
|
const imagPart = backend.runWebGLProgram(imagProgram, inputs, "float32");
|
|
const complexOutput = (0, _complex.complex)({
|
|
inputs: {
|
|
real: realPart,
|
|
imag: imagPart
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(realPart);
|
|
backend.disposeIntermediateTensorInfo(imagPart);
|
|
const complexOutputReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: complexOutput
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: x.shape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(input2D);
|
|
backend.disposeIntermediateTensorInfo(complexOutput);
|
|
return complexOutputReshaped;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../fft_gpu":"9R9lf","./Complex":"55NfL","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9R9lf":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "FFTProgram", ()=>FFTProgram);
|
|
class FFTProgram {
|
|
constructor(component, 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";
|
|
let opString;
|
|
if (component === "real") opString = "return real * expR - imag * expI;";
|
|
else if (component === "imag") opString = "return real * expI + imag * expR;";
|
|
else throw new Error(`FFT component must be either "real" or "imag", got ${component}.`);
|
|
this.userCode = `
|
|
const float exponentMultiplier = ${exponentMultiplierSnippet};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${opString}
|
|
}
|
|
|
|
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]));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6Rawr":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fill", ()=>fill);
|
|
parcelHelpers.export(exports, "fillConfig", ()=>fillConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fillGpu = require("../fill_gpu");
|
|
function fill(args) {
|
|
const { backend, attrs } = args;
|
|
const { shape, value } = attrs;
|
|
let { dtype } = attrs;
|
|
dtype = dtype || (0, _tfjsCore.util).inferDtype(value);
|
|
if (dtype === "string") {
|
|
// String type should be handled in CPU memory.
|
|
const values = (0, _tfjsCore.util).getArrayFromDType(dtype, (0, _tfjsCore.util).sizeFromShape(shape));
|
|
values.fill(value);
|
|
return backend.makeTensorInfo(shape, dtype, values);
|
|
} else {
|
|
const program = new (0, _fillGpu.FillProgram)(shape, value);
|
|
const customValues = [
|
|
[
|
|
value
|
|
]
|
|
];
|
|
return backend.runWebGLProgram(program, [], dtype, customValues);
|
|
}
|
|
}
|
|
const fillConfig = {
|
|
kernelName: (0, _tfjsCore.Fill),
|
|
backendName: "webgl",
|
|
kernelFunc: fill
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../fill_gpu":"hKTOw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hKTOw":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "FillProgram", ()=>FillProgram);
|
|
class FillProgram {
|
|
constructor(shape, value){
|
|
this.outputShape = [];
|
|
this.customUniforms = [
|
|
{
|
|
name: "value",
|
|
type: "float"
|
|
}
|
|
];
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
this.outputShape = shape;
|
|
this.userCode = `
|
|
void main() {
|
|
// Input can be obtained from uniform value.
|
|
setOutput(value);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8QDUY":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "flipLeftRightConfig", ()=>flipLeftRightConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _flipLeftRightGpu = require("../flip_left_right_gpu");
|
|
const flipLeftRightConfig = {
|
|
kernelName: (0, _tfjsCore.FlipLeftRight),
|
|
backendName: "webgl",
|
|
kernelFunc: ({ inputs, backend })=>{
|
|
const { image } = inputs;
|
|
const webglBackend = backend;
|
|
const program = new (0, _flipLeftRightGpu.FlipLeftRightProgram)(image.shape);
|
|
const output = webglBackend.runWebGLProgram(program, [
|
|
image
|
|
], image.dtype);
|
|
return output;
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../flip_left_right_gpu":"1eMG5","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1eMG5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "FlipLeftRightProgram", ()=>FlipLeftRightProgram);
|
|
class FlipLeftRightProgram {
|
|
constructor(imageShape){
|
|
this.variableNames = [
|
|
"Image"
|
|
];
|
|
this.outputShape = [];
|
|
const imageWidth = imageShape[2];
|
|
this.outputShape = imageShape;
|
|
this.userCode = `
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
|
|
int coordX = ${imageWidth} - x - 1;
|
|
float outputValue;
|
|
if(coordX >= 0 && coordX < ${imageWidth}) {
|
|
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
|
|
} else {
|
|
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hB9uc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "floor", ()=>floor);
|
|
parcelHelpers.export(exports, "floorConfig", ()=>floorConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const FLOOR = `return floor(x);`;
|
|
const floor = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: FLOOR,
|
|
packedOpSnippet: FLOOR,
|
|
cpuKernelImpl: (0, _shared.floorImplCPU)
|
|
});
|
|
const floorConfig = {
|
|
kernelName: (0, _tfjsCore.Floor),
|
|
backendName: "webgl",
|
|
kernelFunc: floor
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g0Hz7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "floorDiv", ()=>floorDiv);
|
|
parcelHelpers.export(exports, "floorDivConfig", ()=>floorDivConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
// 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 INT_DIV_PACKED = `
|
|
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 floorDiv = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: INT_DIV,
|
|
packedOpSnippet: INT_DIV_PACKED,
|
|
dtype: "int32"
|
|
});
|
|
const floorDivConfig = {
|
|
kernelName: (0, _tfjsCore.FloorDiv),
|
|
backendName: "webgl",
|
|
kernelFunc: floorDiv
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bNE2l":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fromPixelsConfig", ()=>fromPixelsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _texUtil = require("../tex_util");
|
|
var _fromPixelsGpu = require("./FromPixels_utils/from_pixels_gpu");
|
|
var _fromPixelsPackedGpu = require("./FromPixels_utils/from_pixels_packed_gpu");
|
|
const fromPixelsConfig = {
|
|
kernelName: (0, _tfjsCore.FromPixels),
|
|
backendName: "webgl",
|
|
kernelFunc: fromPixels
|
|
};
|
|
let fromPixels2DContext;
|
|
let willReadFrequently = (0, _tfjsCore.env)().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
|
|
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) {
|
|
const newWillReadFrequently = (0, _tfjsCore.env)().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
|
|
if (fromPixels2DContext == null || newWillReadFrequently !== willReadFrequently) {
|
|
willReadFrequently = newWillReadFrequently;
|
|
fromPixels2DContext = document.createElement("canvas").getContext("2d", {
|
|
willReadFrequently
|
|
});
|
|
}
|
|
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 = (0, _texUtil.TextureUsage).PIXELS;
|
|
backend.gpgpu.uploadPixelDataToTexture(backend.getTexture(tempPixelHandle.dataId), pixels);
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK") ? new (0, _fromPixelsPackedGpu.FromPixelsPackedProgram)(outShape) : new (0, _fromPixelsGpu.FromPixelsProgram)(outShape);
|
|
const res = backend.runWebGLProgram(program, [
|
|
tempPixelHandle
|
|
], "int32");
|
|
backend.disposeData(tempPixelHandle.dataId);
|
|
return res;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../tex_util":"1oYRe","./FromPixels_utils/from_pixels_gpu":"779bc","./FromPixels_utils/from_pixels_packed_gpu":"a4kH1","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"779bc":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "FromPixelsProgram", ()=>FromPixelsProgram);
|
|
var _glslVersion = require("../../glsl_version");
|
|
class FromPixelsProgram {
|
|
constructor(outputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
const glsl = (0, _glslVersion.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));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"../../glsl_version":"kG2vE","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a4kH1":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "FromPixelsPackedProgram", ()=>FromPixelsPackedProgram);
|
|
var _glslVersion = require("../../glsl_version");
|
|
class FromPixelsPackedProgram {
|
|
constructor(outputShape){
|
|
this.variableNames = [
|
|
"A"
|
|
];
|
|
this.packedInputs = false;
|
|
this.packedOutput = true;
|
|
const glsl = (0, _glslVersion.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;
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"../../glsl_version":"kG2vE","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5vkH0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fusedConv2d", ()=>fusedConv2d);
|
|
parcelHelpers.export(exports, "fusedConv2DConfig", ()=>fusedConv2DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convGpu = require("../conv_gpu");
|
|
var _convPackedGpu = require("../conv_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _conv2DImpl = require("./Conv2D_impl");
|
|
var _reshape = require("./Reshape");
|
|
function fusedConv2d(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter, bias, preluActivationWeights } = inputs;
|
|
const { strides, pad, dataFormat, dilations, dimRoundingMode, activation, leakyreluAlpha } = attrs;
|
|
const $dataFormat = (0, _tfjsCore.backend_util).convertConv2DDataFormat(dataFormat);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false, $dataFormat);
|
|
let out;
|
|
const intermediates = [];
|
|
const hasBias = bias != null;
|
|
const hasPreluActivationWeights = preluActivationWeights != null;
|
|
const hasLeakyreluAlpha = activation === "leakyrelu";
|
|
const prepareInputs = ()=>{
|
|
const inputs = [
|
|
x,
|
|
filter
|
|
];
|
|
// If the input is a 1-D tensor, align it with the channels.
|
|
//
|
|
// For fusedConv2d, the inputs (x, W, bias, preluActivationWeights) are
|
|
// supposed to be aligned with the dataFormat. The 4-D tensor inputs or
|
|
// scalar inputs are originally aligned, but the 1-D tensor inputs are
|
|
// supposed to be aligned with the channels (only bias and PReLU activation
|
|
// weights could be a 1-D tensor).
|
|
const alignInputWithDataFormat = (input, dataFormat)=>{
|
|
if (dataFormat === "NCHW" && input.shape.length === 1 && input.shape[0] !== 1) {
|
|
const alignedInput = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: input
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
input.shape[0],
|
|
1,
|
|
1
|
|
]
|
|
}
|
|
});
|
|
intermediates.push(alignedInput);
|
|
return alignedInput;
|
|
}
|
|
return input;
|
|
};
|
|
if (hasBias) inputs.push(alignInputWithDataFormat(bias, dataFormat));
|
|
if (hasPreluActivationWeights) inputs.push(alignInputWithDataFormat(preluActivationWeights, dataFormat));
|
|
if (hasLeakyreluAlpha) {
|
|
const $leakyreluAlpha = backend.makeTensorInfo([], "float32", (0, _tfjsCore.util).createScalarValue(leakyreluAlpha, "float32"));
|
|
inputs.push($leakyreluAlpha);
|
|
intermediates.push($leakyreluAlpha);
|
|
}
|
|
return inputs;
|
|
};
|
|
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")) out = (0, _conv2DImpl.conv2dByMatMul)({
|
|
x,
|
|
filter,
|
|
convInfo,
|
|
backend,
|
|
bias,
|
|
activation,
|
|
preluActivationWeights,
|
|
leakyreluAlpha
|
|
});
|
|
else if (convInfo.strideWidth <= 2 && $dataFormat === "channelsLast" && (0, _tfjsCore.env)().getBool("WEBGL_EXP_CONV")) {
|
|
const fusedActivation = activation ? (0, _kernelFuncsUtils.mapActivationToShaderProgram)(activation, true) : null;
|
|
const program = new (0, _convPackedGpu.Conv2DPackedProgram)(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
|
|
const customValues = [
|
|
[
|
|
convInfo.padInfo.top,
|
|
convInfo.padInfo.left
|
|
],
|
|
[
|
|
convInfo.strideHeight,
|
|
convInfo.strideWidth
|
|
],
|
|
[
|
|
convInfo.dilationHeight,
|
|
convInfo.dilationWidth
|
|
],
|
|
[
|
|
convInfo.inHeight,
|
|
convInfo.inWidth
|
|
]
|
|
];
|
|
const inputs = prepareInputs();
|
|
out = backend.runWebGLProgram(program, inputs, "float32", customValues);
|
|
} else if ((0, _tfjsCore.env)().getBool("WEBGL_CONV_IM2COL")) out = (0, _conv2DImpl.conv2dWithIm2Row)({
|
|
x,
|
|
filter,
|
|
convInfo,
|
|
backend,
|
|
bias,
|
|
activation,
|
|
preluActivationWeights,
|
|
leakyreluAlpha
|
|
});
|
|
else {
|
|
const fusedActivation = activation ? (0, _kernelFuncsUtils.mapActivationToShaderProgram)(activation, false) : null;
|
|
const program = new (0, _convGpu.Conv2DProgram)(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
|
|
const inputs = prepareInputs();
|
|
out = backend.runWebGLProgram(program, inputs, "float32");
|
|
}
|
|
const outReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: out
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: convInfo.outShape
|
|
}
|
|
});
|
|
intermediates.push(out);
|
|
intermediates.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return outReshaped;
|
|
}
|
|
const fusedConv2DConfig = {
|
|
kernelName: (0, _tfjsCore.FusedConv2D),
|
|
backendName: "webgl",
|
|
kernelFunc: fusedConv2d
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_gpu":"3pfYb","../conv_packed_gpu":"hPtK0","../kernel_utils/kernel_funcs_utils":"grPtN","./Conv2D_impl":"6Kgrg","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5SfAK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fusedDepthwiseConv2D", ()=>fusedDepthwiseConv2D);
|
|
parcelHelpers.export(exports, "fusedDepthwiseConv2DConfig", ()=>fusedDepthwiseConv2DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _convGpuDepthwise = require("../conv_gpu_depthwise");
|
|
var _convPackedGpuDepthwise = require("../conv_packed_gpu_depthwise");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
function fusedDepthwiseConv2D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter, bias, preluActivationWeights } = inputs;
|
|
const { strides, pad, dilations, dimRoundingMode, activation, leakyreluAlpha } = attrs;
|
|
const intermediates = [];
|
|
let $dilations = dilations;
|
|
if ($dilations == null) $dilations = [
|
|
1,
|
|
1
|
|
];
|
|
(0, _tfjsCore.util).assert((0, _tfjsCore.backend_util).eitherStridesOrDilationsAreOne(strides, $dilations), ()=>"Error in depthwiseConv2d: Either strides or dilations must be " + `1. Got strides ${strides} and dilations '${$dilations}'`);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filter.shape, strides, $dilations, pad, dimRoundingMode, true);
|
|
const shouldPackDepthwiseConv = (0, _tfjsCore.env)().getBool("WEBGL_PACK_DEPTHWISECONV") && convInfo.strideWidth <= 2 && convInfo.outChannels / convInfo.inChannels === 1;
|
|
const fusedActivation = activation ? (0, _kernelFuncsUtils.mapActivationToShaderProgram)(activation, shouldPackDepthwiseConv) : null;
|
|
const programInputs = [
|
|
x,
|
|
filter
|
|
];
|
|
const hasBias = bias != null;
|
|
const hasPreluActivationWeights = preluActivationWeights != null;
|
|
const hasLeakyreluAlpha = activation === "leakyrelu";
|
|
if (hasBias) programInputs.push(bias);
|
|
if (hasPreluActivationWeights) programInputs.push(preluActivationWeights);
|
|
if (hasLeakyreluAlpha) {
|
|
const $leakyreluAlpha = backend.makeTensorInfo([], "float32", (0, _tfjsCore.util).createScalarValue(leakyreluAlpha, "float32"));
|
|
programInputs.push($leakyreluAlpha);
|
|
intermediates.push($leakyreluAlpha);
|
|
}
|
|
let program;
|
|
if (shouldPackDepthwiseConv) program = new (0, _convPackedGpuDepthwise.DepthwiseConvPacked2DProgram)(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
|
|
else program = new (0, _convGpuDepthwise.DepthwiseConv2DProgram)(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
|
|
const customValues = [
|
|
[
|
|
convInfo.padInfo.top,
|
|
convInfo.padInfo.left
|
|
],
|
|
[
|
|
convInfo.strideHeight,
|
|
convInfo.strideWidth
|
|
],
|
|
[
|
|
convInfo.dilationHeight,
|
|
convInfo.dilationWidth
|
|
],
|
|
[
|
|
convInfo.inHeight,
|
|
convInfo.inWidth
|
|
]
|
|
];
|
|
const result = backend.runWebGLProgram(program, programInputs, "float32", customValues);
|
|
intermediates.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return result;
|
|
}
|
|
const fusedDepthwiseConv2DConfig = {
|
|
kernelName: (0, _tfjsCore.FusedDepthwiseConv2D),
|
|
backendName: "webgl",
|
|
kernelFunc: fusedDepthwiseConv2D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../conv_gpu_depthwise":"31MV7","../conv_packed_gpu_depthwise":"aG31s","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4xUDy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gatherNd", ()=>gatherNd);
|
|
parcelHelpers.export(exports, "gatherNdConfig", ()=>gatherNdConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gatherNdGpu = require("../gather_nd_gpu");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _reshape = require("./Reshape");
|
|
function gatherNd(args) {
|
|
const { inputs, backend } = args;
|
|
const { params, indices } = inputs;
|
|
const indicesShape = indices.shape;
|
|
const sliceRank = indicesShape[indicesShape.length - 1];
|
|
const paramsSize = (0, _tfjsCore.util).sizeFromShape(params.shape);
|
|
const [resultShape, numSlices, sliceSize, strides] = (0, _tfjsCore.backend_util).prepareAndValidate(params, indices);
|
|
const flattenIndices = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: indices
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
numSlices,
|
|
sliceRank
|
|
]
|
|
}
|
|
});
|
|
const flattenX = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: params
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
(0, _tfjsCore.util).sizeFromShape(params.shape) / sliceSize,
|
|
sliceSize
|
|
]
|
|
}
|
|
});
|
|
if (backend.shouldExecuteOnCPU([
|
|
params,
|
|
indices
|
|
]) || params.dtype === "string") {
|
|
const indicesData = backend.readSync(indices.dataId);
|
|
const paramsBuf = backend.bufferSync(params);
|
|
const outValue = (0, _shared.gatherNdImplCPU)(indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize, strides, params.shape, paramsSize);
|
|
return backend.makeTensorInfo(resultShape, params.dtype, outValue.values);
|
|
}
|
|
const program = new (0, _gatherNdGpu.GatherNDProgram)(sliceRank, strides, [
|
|
numSlices,
|
|
sliceSize
|
|
], params.shape);
|
|
const res = backend.runWebGLProgram(program, [
|
|
flattenX,
|
|
flattenIndices
|
|
], flattenX.dtype);
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: res
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: resultShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(flattenIndices);
|
|
backend.disposeIntermediateTensorInfo(flattenX);
|
|
backend.disposeIntermediateTensorInfo(res);
|
|
return reshaped;
|
|
}
|
|
const gatherNdConfig = {
|
|
kernelName: (0, _tfjsCore.GatherNd),
|
|
backendName: "webgl",
|
|
kernelFunc: gatherNd
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../gather_nd_gpu":"8orFL","../kernel_utils/shared":"e4M7v","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8orFL":[function(require,module,exports) {
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "GatherNDProgram", ()=>GatherNDProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class GatherNDProgram {
|
|
constructor(sliceDim, strides, shape, paramsShape){
|
|
this.sliceDim = sliceDim;
|
|
this.strides = strides;
|
|
this.paramsShape = paramsShape;
|
|
this.variableNames = [
|
|
"x",
|
|
"indices"
|
|
];
|
|
this.outputShape = shape;
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(shape.length);
|
|
let mainLoop = `
|
|
int index;`;
|
|
for(let j = 0; j < this.sliceDim; j++)mainLoop += `
|
|
index = round(getIndices(coords[0], ${j}));
|
|
out_of_bounds = out_of_bounds || index < 0;
|
|
out_of_bounds = out_of_bounds || index >= ${this.paramsShape[j]};
|
|
flattenIndex += index * ${this.strides[j]};`;
|
|
this.userCode = `
|
|
void main() {
|
|
${dtype} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
bool out_of_bounds = false;
|
|
|
|
${mainLoop}
|
|
|
|
setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cBFXe":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gatherV2", ()=>gatherV2);
|
|
parcelHelpers.export(exports, "gatherV2Config", ()=>gatherV2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gatherGpu = require("../gather_gpu");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _reshape = require("./Reshape");
|
|
function gatherV2(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, indices } = inputs;
|
|
const { axis, batchDims } = attrs;
|
|
const parsedAxis = (0, _tfjsCore.util).parseAxisParam(axis, x.shape)[0];
|
|
if ((0, _tfjsCore.env)().get("DEBUG")) {
|
|
// In debug mode, throw error when any index is out of bound.
|
|
// Otherwise, just fill out of bounds with zeroes.
|
|
const indicesVals = backend.readSync(indices.dataId);
|
|
const axisDim = x.shape[parsedAxis];
|
|
for(let i = 0; i < indicesVals.length; ++i){
|
|
const index = indicesVals[i];
|
|
(0, _tfjsCore.util).assert(index <= axisDim - 1 && index >= 0, ()=>`GatherV2: the index value ${index} is not in [0, ${axisDim - 1}]`);
|
|
}
|
|
}
|
|
const shapeInfo = (0, _tfjsCore.backend_util).segment_util.collectGatherOpShapeInfo(x, indices, parsedAxis, batchDims);
|
|
const indicesSize = (0, _tfjsCore.util).sizeFromShape(indices.shape);
|
|
const toDispose = [];
|
|
const flattenX = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
shapeInfo.batchSize,
|
|
shapeInfo.outerSize,
|
|
shapeInfo.dimSize,
|
|
shapeInfo.sliceSize
|
|
]
|
|
}
|
|
});
|
|
const flattenIndex = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: indices
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
shapeInfo.batchSize,
|
|
indicesSize / shapeInfo.batchSize
|
|
]
|
|
}
|
|
});
|
|
toDispose.push(flattenX);
|
|
toDispose.push(flattenIndex);
|
|
const flattenOutputShape = [
|
|
shapeInfo.batchSize,
|
|
shapeInfo.outerSize,
|
|
indicesSize / shapeInfo.batchSize,
|
|
shapeInfo.sliceSize
|
|
];
|
|
if (backend.shouldExecuteOnCPU([
|
|
x,
|
|
indices
|
|
]) || x.dtype === "string") {
|
|
const indicesBuf = backend.bufferSync(flattenIndex);
|
|
const xBuf = backend.bufferSync(flattenX);
|
|
const outBuf = (0, _shared.gatherV2ImplCPU)(xBuf, indicesBuf, flattenOutputShape);
|
|
toDispose.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return backend.makeTensorInfo(shapeInfo.outputShape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const program = new (0, _gatherGpu.GatherProgram)(flattenX.shape, flattenOutputShape);
|
|
const res = backend.runWebGLProgram(program, [
|
|
flattenX,
|
|
flattenIndex
|
|
], flattenX.dtype);
|
|
toDispose.push(res);
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: res
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: shapeInfo.outputShape
|
|
}
|
|
});
|
|
toDispose.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return reshaped;
|
|
}
|
|
const gatherV2Config = {
|
|
kernelName: (0, _tfjsCore.GatherV2),
|
|
backendName: "webgl",
|
|
kernelFunc: gatherV2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../gather_gpu":"dakUw","../kernel_utils/shared":"e4M7v","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dakUw":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "GatherProgram", ()=>GatherProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class GatherProgram {
|
|
constructor(aShape, outputShape){
|
|
this.variableNames = [
|
|
"A",
|
|
"indices"
|
|
];
|
|
this.outputShape = outputShape;
|
|
this.rank = outputShape.length;
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(this.rank);
|
|
const sourceCoords = getSourceCoords(aShape, 2);
|
|
this.userCode = `
|
|
void main() {
|
|
${dtype} resRC = getOutputCoords();
|
|
int index = int(getIndices(resRC.x, resRC.z));
|
|
float inBounds = (index >= 0) && (index < ${aShape[2]}) ? 1.0 : 0.0;
|
|
setOutput(inBounds * getA(${sourceCoords}));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
// The input and output are always flattened into rank 4 tensors.
|
|
function getSourceCoords(aShape, axis) {
|
|
const currentCoords = [
|
|
"resRC.x",
|
|
"resRC.y",
|
|
"resRC.z",
|
|
"resRC.w"
|
|
];
|
|
const sourceCoords = [];
|
|
for(let i = 0; i < aShape.length; i++)if (i === 2) sourceCoords.push("index");
|
|
else sourceCoords.push(`${currentCoords[i]}`);
|
|
return sourceCoords.join();
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eDhqn":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "greater", ()=>greater);
|
|
parcelHelpers.export(exports, "greaterConfig", ()=>greaterConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const GREATER = `return float(a > b);`;
|
|
const GREATER_PACKED = `
|
|
return vec4(greaterThan(a, b));
|
|
`;
|
|
const greater = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: GREATER,
|
|
packedOpSnippet: GREATER_PACKED,
|
|
cpuKernelImpl: (0, _shared.greaterImplCPU),
|
|
dtype: "bool"
|
|
});
|
|
const greaterConfig = {
|
|
kernelName: (0, _tfjsCore.Greater),
|
|
backendName: "webgl",
|
|
kernelFunc: greater
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1w6uF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "greaterEqual", ()=>greaterEqual);
|
|
parcelHelpers.export(exports, "greaterEqualConfig", ()=>greaterEqualConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const GREATER_EQUAL = `return float(a >= b);`;
|
|
const GREATER_EQUAL_PACKED = `
|
|
return vec4(greaterThanEqual(a, b));
|
|
`;
|
|
const greaterEqual = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: GREATER_EQUAL,
|
|
packedOpSnippet: GREATER_EQUAL_PACKED,
|
|
dtype: "bool",
|
|
cpuKernelImpl: (0, _shared.greaterEqualImplCPU)
|
|
});
|
|
const greaterEqualConfig = {
|
|
kernelName: (0, _tfjsCore.GreaterEqual),
|
|
backendName: "webgl",
|
|
kernelFunc: greaterEqual
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1mdy7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ifft", ()=>ifft);
|
|
parcelHelpers.export(exports, "ifftConfig", ()=>ifftConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fftImpl = require("./FFT_impl");
|
|
function ifft(args) {
|
|
const { inputs, backend } = args;
|
|
const { input } = inputs;
|
|
return (0, _fftImpl.fftImpl)(input, true, backend);
|
|
}
|
|
const ifftConfig = {
|
|
kernelName: (0, _tfjsCore.IFFT),
|
|
backendName: "webgl",
|
|
kernelFunc: ifft
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./FFT_impl":"ji88K","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aWWtq":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isFinite", ()=>isFinite);
|
|
parcelHelpers.export(exports, "isFiniteConfig", ()=>isFiniteConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const IS_FINITE = `return float(!isnan(x) && !isinf(x));`;
|
|
const isFinite = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: IS_FINITE,
|
|
dtype: "bool"
|
|
});
|
|
const isFiniteConfig = {
|
|
kernelName: (0, _tfjsCore.IsFinite),
|
|
backendName: "webgl",
|
|
kernelFunc: isFinite
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bxXPH":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isInf", ()=>isInf);
|
|
parcelHelpers.export(exports, "isInfConfig", ()=>isInfConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const IS_INF = `return float(isinf(x));`;
|
|
const isInf = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: IS_INF,
|
|
dtype: "bool"
|
|
});
|
|
const isInfConfig = {
|
|
kernelName: (0, _tfjsCore.IsInf),
|
|
backendName: "webgl",
|
|
kernelFunc: isInf
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jUwW0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isNaN", ()=>isNaN);
|
|
parcelHelpers.export(exports, "isNaNConfig", ()=>isNaNConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const IS_NAN = `return float(isnan(x));`;
|
|
const isNaN = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: IS_NAN,
|
|
dtype: "bool"
|
|
});
|
|
const isNaNConfig = {
|
|
kernelName: (0, _tfjsCore.IsNan),
|
|
backendName: "webgl",
|
|
kernelFunc: isNaN
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"htToM":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "less", ()=>less);
|
|
parcelHelpers.export(exports, "lessConfig", ()=>lessConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const LESS = `return float(a < b);`;
|
|
const LESS_PACKED = `
|
|
return vec4(lessThan(a, b));
|
|
`;
|
|
const less = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: LESS,
|
|
packedOpSnippet: LESS_PACKED,
|
|
cpuKernelImpl: (0, _shared.lessImplCPU),
|
|
dtype: "bool"
|
|
});
|
|
const lessConfig = {
|
|
kernelName: (0, _tfjsCore.Less),
|
|
backendName: "webgl",
|
|
kernelFunc: less
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eXbD5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "LESS_EQUAL", ()=>LESS_EQUAL);
|
|
parcelHelpers.export(exports, "LESS_EQUAL_PACKED", ()=>LESS_EQUAL_PACKED);
|
|
parcelHelpers.export(exports, "lessEqual", ()=>lessEqual);
|
|
parcelHelpers.export(exports, "lessEqualConfig", ()=>lessEqualConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const LESS_EQUAL = `return float(a <= b);`;
|
|
const LESS_EQUAL_PACKED = `
|
|
return vec4(lessThanEqual(a, b));
|
|
`;
|
|
const lessEqual = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: LESS_EQUAL,
|
|
packedOpSnippet: LESS_EQUAL_PACKED,
|
|
cpuKernelImpl: (0, _shared.lessEqualImplCPU),
|
|
dtype: "bool"
|
|
});
|
|
const lessEqualConfig = {
|
|
kernelName: (0, _tfjsCore.LessEqual),
|
|
backendName: "webgl",
|
|
kernelFunc: lessEqual
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kM2RJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "linSpace", ()=>linSpace);
|
|
parcelHelpers.export(exports, "linSpaceConfig", ()=>linSpaceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function linSpace(args) {
|
|
const { backend, attrs } = args;
|
|
const { start, stop, num } = attrs;
|
|
// TODO: Use CPU implementation due to the precision problem in Safari.
|
|
const outVals = (0, _shared.linSpaceImplCPU)(start, stop, num);
|
|
return backend.makeTensorInfo([
|
|
outVals.length
|
|
], "float32", outVals);
|
|
}
|
|
const linSpaceConfig = {
|
|
kernelName: (0, _tfjsCore.LinSpace),
|
|
backendName: "webgl",
|
|
kernelFunc: linSpace
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fVZGS":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "log", ()=>log);
|
|
parcelHelpers.export(exports, "logConfig", ()=>logConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
// Windows chrome return 0 if the input is negative value. We will specifically
|
|
// return NaN if the input is 0 to solve compatiblity issue.
|
|
const LOG = (0, _kernelFuncsUtils.CHECK_NAN_SNIPPET_UNARY) + `
|
|
return x < 0.0 ? 0./0. : log(x);
|
|
`;
|
|
const LOG_PACKED = `
|
|
vec4 result = log(x);
|
|
bvec4 isNaN = isnan(x);
|
|
result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
|
|
result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
|
|
result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
|
|
result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
|
|
return result;
|
|
`;
|
|
const log = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: LOG,
|
|
packedOpSnippet: LOG_PACKED,
|
|
cpuKernelImpl: (0, _shared.logImplCPU)
|
|
});
|
|
const logConfig = {
|
|
kernelName: (0, _tfjsCore.Log),
|
|
backendName: "webgl",
|
|
kernelFunc: log
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"czYhe":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "log1p", ()=>log1p);
|
|
parcelHelpers.export(exports, "log1pConfig", ()=>log1pConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const LOG1P = (0, _kernelFuncsUtils.CHECK_NAN_SNIPPET_UNARY) + `
|
|
return log(1.0 + x);
|
|
`;
|
|
const log1p = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: LOG1P
|
|
});
|
|
const log1pConfig = {
|
|
kernelName: (0, _tfjsCore.Log1p),
|
|
backendName: "webgl",
|
|
kernelFunc: log1p
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"37RLf":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalAnd", ()=>logicalAnd);
|
|
parcelHelpers.export(exports, "logicalAndConfig", ()=>logicalAndConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const LOGICAL_AND = `return float(a >= 1.0 && b >= 1.0);`;
|
|
const LOGICAL_AND_PACKED = `
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`;
|
|
const logicalAnd = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: LOGICAL_AND,
|
|
packedOpSnippet: LOGICAL_AND_PACKED,
|
|
dtype: "bool"
|
|
});
|
|
const logicalAndConfig = {
|
|
kernelName: (0, _tfjsCore.LogicalAnd),
|
|
backendName: "webgl",
|
|
kernelFunc: logicalAnd
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b9oed":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalNot", ()=>logicalNot);
|
|
parcelHelpers.export(exports, "logicalNotConfig", ()=>logicalNotConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const LOGICAL_NOT = `return float(!(x >= 1.0));`;
|
|
const logicalNot = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: LOGICAL_NOT
|
|
});
|
|
const logicalNotConfig = {
|
|
kernelName: (0, _tfjsCore.LogicalNot),
|
|
backendName: "webgl",
|
|
kernelFunc: logicalNot
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4Kv3V":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalOr", ()=>logicalOr);
|
|
parcelHelpers.export(exports, "logicalOrConfig", ()=>logicalOrConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const LOGICAL_OR = `return float(a >= 1.0 || b >= 1.0);`;
|
|
const LOGICAL_OR_PACKED = `
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`;
|
|
const logicalOr = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: LOGICAL_OR,
|
|
packedOpSnippet: LOGICAL_OR_PACKED,
|
|
dtype: "bool"
|
|
});
|
|
const logicalOrConfig = {
|
|
kernelName: (0, _tfjsCore.LogicalOr),
|
|
backendName: "webgl",
|
|
kernelFunc: logicalOr
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6ZjnF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "lrn", ()=>lrn);
|
|
parcelHelpers.export(exports, "LRNConfig", ()=>LRNConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _lrnGpu = require("../lrn_gpu");
|
|
var _lrnPackedGpu = require("../lrn_packed_gpu");
|
|
const lrn = (args)=>{
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { depthRadius, bias, alpha, beta } = attrs;
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_NORMALIZATION") ? new (0, _lrnPackedGpu.LRNPackedProgram)(x.shape, depthRadius, bias, alpha, beta) : new (0, _lrnGpu.LRNProgram)(x.shape, depthRadius, bias, alpha, beta);
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
};
|
|
const LRNConfig = {
|
|
kernelName: (0, _tfjsCore.LRN),
|
|
backendName: "webgl",
|
|
kernelFunc: lrn
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../lrn_gpu":"lrUAN","../lrn_packed_gpu":"7G0Pe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lrUAN":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "LRNProgram", ()=>LRNProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7G0Pe":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "LRNPackedProgram", ()=>LRNPackedProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"BMOEB":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "lrnGrad", ()=>lrnGrad);
|
|
parcelHelpers.export(exports, "LRNGradConfig", ()=>LRNGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _lrnGradGpu = require("../lrn_grad_gpu");
|
|
const lrnGrad = (args)=>{
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, y, dy } = inputs;
|
|
const { depthRadius, bias, alpha, beta } = attrs;
|
|
const program = new (0, _lrnGradGpu.LRNGradProgram)(x.shape, depthRadius, bias, alpha, beta);
|
|
return backend.runWebGLProgram(program, [
|
|
x,
|
|
y,
|
|
dy
|
|
], x.dtype);
|
|
};
|
|
const LRNGradConfig = {
|
|
kernelName: (0, _tfjsCore.LRNGrad),
|
|
backendName: "webgl",
|
|
kernelFunc: lrnGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../lrn_grad_gpu":"dolDe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dolDe":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "LRNGradProgram", ()=>LRNGradProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"11YMi":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "max", ()=>max);
|
|
parcelHelpers.export(exports, "maxConfig", ()=>maxConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _maxImpl = require("./Max_impl");
|
|
var _transposeImpl = require("./Transpose_impl");
|
|
function max(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { reductionIndices, keepDims } = attrs;
|
|
const xRank = x.shape.length;
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(reductionIndices, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
const maxInputIsTransposed = permutedAxes != null;
|
|
const shouldExecuteOnCPU = backend.shouldExecuteOnCPU([
|
|
x
|
|
]);
|
|
let maxInput = x;
|
|
if (maxInputIsTransposed) {
|
|
if (shouldExecuteOnCPU) {
|
|
const xTexData = backend.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 = (0, _transposeImpl.transposeImplCPU)(values, x.shape, x.dtype, permutedAxes, newShape);
|
|
maxInput = backend.makeTensorInfo(newShape, x.dtype);
|
|
const maxInputData = backend.texData.get(maxInput.dataId);
|
|
maxInputData.values = maxInputValues;
|
|
} else maxInput = (0, _transposeImpl.transposeImpl)(x, permutedAxes, backend);
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, xRank);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("max", axes, xRank);
|
|
const [maxOutShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(maxInput.shape, axes);
|
|
let outShape = maxOutShape;
|
|
if (keepDims) // rather than reshape at the end, set the target shape here.
|
|
outShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(maxOutShape, origAxes);
|
|
let out;
|
|
if (shouldExecuteOnCPU) {
|
|
const xTexData = backend.texData.get(maxInput.dataId);
|
|
const values = xTexData.values;
|
|
const outValues = (0, _shared.maxImplCPU)(values, (0, _tfjsCore.util).sizeFromShape(reduceShape), outShape, x.dtype);
|
|
out = backend.makeTensorInfo(outShape, x.dtype);
|
|
const outData = backend.texData.get(out.dataId);
|
|
outData.values = outValues;
|
|
} else out = (0, _maxImpl.maxImpl)(maxInput, reduceShape, outShape, backend);
|
|
if (maxInputIsTransposed) backend.disposeIntermediateTensorInfo(maxInput);
|
|
return out;
|
|
}
|
|
const maxConfig = {
|
|
kernelName: (0, _tfjsCore.Max),
|
|
backendName: "webgl",
|
|
kernelFunc: max
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","./Max_impl":"8LQsj","./Transpose_impl":"arYj9","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8LQsj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxImpl", ()=>maxImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reduce = require("../kernel_utils/reduce");
|
|
var _reshape = require("../kernels/Reshape");
|
|
function maxImpl(x, reduceShape, outShape, backend) {
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const batchSize = xSize / inSize;
|
|
const reshapedInput = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
attrs: {
|
|
shape: [
|
|
batchSize,
|
|
inSize
|
|
]
|
|
},
|
|
backend
|
|
});
|
|
const reduced = (0, _reduce.reduce)(reshapedInput, x.dtype, "max", backend);
|
|
const reshapedOutput = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
attrs: {
|
|
shape: outShape
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(reshapedInput);
|
|
backend.disposeIntermediateTensorInfo(reduced);
|
|
return reshapedOutput;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/reduce":"dr0Xl","../kernels/Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9B0Ki":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maximum", ()=>maximum);
|
|
parcelHelpers.export(exports, "maximumConfig", ()=>maximumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const MAXIMUM = (0, _binaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
return max(a, b);
|
|
`;
|
|
const MAXIMUM_PACKED = `
|
|
vec4 result = vec4(max(a, b));
|
|
bvec4 isNaNA = isnan(a);
|
|
bvec4 isNaNB = isnan(b);
|
|
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
|
|
` + (0, _binaryopPackedGpu.CHECK_NAN_SNIPPET_PACKED) + `
|
|
return result;
|
|
`;
|
|
const maximum = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: MAXIMUM,
|
|
packedOpSnippet: MAXIMUM_PACKED,
|
|
cpuKernelImpl: (0, _shared.maximumImplCPU)
|
|
});
|
|
const maximumConfig = {
|
|
kernelName: (0, _tfjsCore.Maximum),
|
|
backendName: "webgl",
|
|
kernelFunc: maximum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"74RsU":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPool", ()=>maxPool);
|
|
parcelHelpers.export(exports, "maxPoolConfig", ()=>maxPoolConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _poolGpu = require("../pool_gpu");
|
|
var _webglUtil = require("../webgl_util");
|
|
var _identity = require("./Identity");
|
|
function maxPool(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
(0, _webglUtil.assertNotComplex)(x, "maxPool");
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
const dilations = 1;
|
|
(0, _tfjsCore.util).assert((0, _tfjsCore.backend_util).eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in maxPool: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
|
|
if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 && (0, _tfjsCore.util).arraysEqual(convInfo.inShape, convInfo.outShape)) return (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
const maxPoolProgram = new (0, _poolGpu.Pool2DProgram)(convInfo, "max", false);
|
|
return backend.runWebGLProgram(maxPoolProgram, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
const maxPoolConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPool),
|
|
backendName: "webgl",
|
|
kernelFunc: maxPool
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../pool_gpu":"b1t1V","../webgl_util":"fjf7t","./Identity":"hY9aT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iXVcU":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPool3d", ()=>maxPool3d);
|
|
parcelHelpers.export(exports, "maxPool3DConfig", ()=>maxPool3DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _poolGpu = require("../pool_gpu");
|
|
function maxPool3d(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { filterSize, strides, pad, dataFormat, dimRoundingMode } = attrs;
|
|
const dilations = [
|
|
1,
|
|
1,
|
|
1
|
|
];
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode, dataFormat);
|
|
const maxPoolProgram = new (0, _poolGpu.Pool3DProgram)(convInfo, "max", false);
|
|
return backend.runWebGLProgram(maxPoolProgram, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
const maxPool3DConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPool3D),
|
|
backendName: "webgl",
|
|
kernelFunc: maxPool3d
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../pool_gpu":"b1t1V","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eejL1":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPool3DGrad", ()=>maxPool3DGrad);
|
|
parcelHelpers.export(exports, "maxPool3DGradConfig", ()=>maxPool3DGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _maxPoolBackpropGpu = require("../max_pool_backprop_gpu");
|
|
var _poolGpu = require("../pool_gpu");
|
|
function maxPool3DGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, input } = inputs;
|
|
const x = input;
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
const dilations = [
|
|
1,
|
|
1,
|
|
1
|
|
];
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
|
|
const maxPool3dPositionsProgram = new (0, _poolGpu.Pool3DProgram)(convInfo, "max", true);
|
|
const maxPool3dPositions = backend.runWebGLProgram(maxPool3dPositionsProgram, [
|
|
x
|
|
], x.dtype);
|
|
const maxPoolBackpropProgram = new (0, _maxPoolBackpropGpu.MaxPool3DBackpropProgram)(convInfo);
|
|
const result = backend.runWebGLProgram(maxPoolBackpropProgram, [
|
|
dy,
|
|
maxPool3dPositions
|
|
], x.dtype);
|
|
backend.disposeIntermediateTensorInfo(maxPool3dPositions);
|
|
return result;
|
|
}
|
|
const maxPool3DGradConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPool3DGrad),
|
|
backendName: "webgl",
|
|
kernelFunc: maxPool3DGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../max_pool_backprop_gpu":"6LIcT","../pool_gpu":"b1t1V","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6LIcT":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MaxPool2DBackpropProgram", ()=>MaxPool2DBackpropProgram);
|
|
parcelHelpers.export(exports, "MaxPool3DBackpropProgram", ()=>MaxPool3DBackpropProgram);
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eaA7G":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPoolGrad", ()=>maxPoolGrad);
|
|
parcelHelpers.export(exports, "maxPoolGradConfig", ()=>maxPoolGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _maxPoolBackpropGpu = require("../max_pool_backprop_gpu");
|
|
var _poolGpu = require("../pool_gpu");
|
|
var _webglUtil = require("../webgl_util");
|
|
function maxPoolGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, input, output } = inputs;
|
|
const x = input;
|
|
(0, _webglUtil.assertNotComplex)([
|
|
input,
|
|
output
|
|
], "maxPoolGrad");
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, 1 /* dilations */ , pad, dimRoundingMode);
|
|
const getPositions = true;
|
|
const maxPoolPositionsProgram = new (0, _poolGpu.Pool2DProgram)(convInfo, "max", getPositions);
|
|
const maxPoolPositions = backend.runWebGLProgram(maxPoolPositionsProgram, [
|
|
x
|
|
], x.dtype);
|
|
const maxPoolBackPropProgram = new (0, _maxPoolBackpropGpu.MaxPool2DBackpropProgram)(convInfo);
|
|
const result = backend.runWebGLProgram(maxPoolBackPropProgram, [
|
|
dy,
|
|
maxPoolPositions
|
|
], x.dtype);
|
|
backend.disposeIntermediateTensorInfo(maxPoolPositions);
|
|
return result;
|
|
}
|
|
const maxPoolGradConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPoolGrad),
|
|
backendName: "webgl",
|
|
kernelFunc: maxPoolGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../max_pool_backprop_gpu":"6LIcT","../pool_gpu":"b1t1V","../webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jaMAy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPoolWithArgmaxConfig", ()=>maxPoolWithArgmaxConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _maxPoolWithArgmaxImpl = require("./MaxPoolWithArgmax_impl");
|
|
const maxPoolWithArgmaxConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPoolWithArgmax),
|
|
backendName: "webgl",
|
|
kernelFunc: ({ inputs, attrs, backend })=>{
|
|
const { x } = inputs;
|
|
const { filterSize, strides, pad, includeBatchInIndex } = attrs;
|
|
const webglBackend = backend;
|
|
(0, _tfjsCore.util).assert(x.shape.length === 4, ()=>`Error in maxPool: input must be rank 4 but got rank ${x.shape.length}.`);
|
|
const dilations = [
|
|
1,
|
|
1
|
|
];
|
|
(0, _tfjsCore.util).assert((0, _tfjsCore.backend_util).eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in maxPool: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, dilations, pad);
|
|
const [result, indexes] = (0, _maxPoolWithArgmaxImpl.maxPoolWithArgmaxImpl)(x, includeBatchInIndex, convInfo, webglBackend);
|
|
return [
|
|
result,
|
|
indexes
|
|
];
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./MaxPoolWithArgmax_impl":"k4DUz","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"k4DUz":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPoolWithArgmaxImpl", ()=>maxPoolWithArgmaxImpl);
|
|
var _poolGpu = require("../pool_gpu");
|
|
function maxPoolWithArgmaxImpl(x, includeBatchInIndex, convInfo, backend) {
|
|
let program = new (0, _poolGpu.Pool2DProgram)(convInfo, "max", false);
|
|
const poolOutput = backend.runWebGLProgram(program, [
|
|
x
|
|
], "float32");
|
|
program = new (0, _poolGpu.Pool2DProgram)(convInfo, "max", true, true, includeBatchInIndex);
|
|
const indexOutput = backend.runWebGLProgram(program, [
|
|
x
|
|
], "float32");
|
|
return [
|
|
poolOutput,
|
|
indexOutput
|
|
];
|
|
}
|
|
|
|
},{"../pool_gpu":"b1t1V","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4HPXU":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "meanConfig", ()=>meanConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _meanImpl = require("./Mean_impl");
|
|
var _transposeImpl = require("./Transpose_impl");
|
|
const meanConfig = {
|
|
kernelName: (0, _tfjsCore.Mean),
|
|
backendName: "webgl",
|
|
kernelFunc: ({ inputs, attrs, backend })=>{
|
|
const { x } = inputs;
|
|
const { keepDims, axis } = attrs;
|
|
const webglBackend = backend;
|
|
const xRank = x.shape.length;
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
const meanInputIsTransposed = permutedAxes != null;
|
|
const shouldExecuteOnCPU = webglBackend.shouldExecuteOnCPU([
|
|
x
|
|
]);
|
|
const intermediates = [];
|
|
let meanInput = x;
|
|
if (meanInputIsTransposed) {
|
|
if (shouldExecuteOnCPU) {
|
|
const xTexData = webglBackend.texData.get(meanInput.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 meanInputValues = (0, _transposeImpl.transposeImplCPU)(values, x.shape, x.dtype, permutedAxes, newShape);
|
|
meanInput = webglBackend.makeTensorInfo(newShape, x.dtype);
|
|
const meanInputData = webglBackend.texData.get(meanInput.dataId);
|
|
meanInputData.values = meanInputValues;
|
|
} else meanInput = (0, _transposeImpl.transposeImpl)(x, permutedAxes, webglBackend);
|
|
intermediates.push(meanInput);
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, xRank);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("sum", axes, xRank);
|
|
const [meanOutShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(meanInput.shape, axes);
|
|
let outShape = meanOutShape;
|
|
if (keepDims) // rather than reshape at the end, set the target shape here.
|
|
outShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(meanOutShape, origAxes);
|
|
const out = (0, _meanImpl.meanImpl)(meanInput, reduceShape, outShape, webglBackend);
|
|
for (const i of intermediates)webglBackend.disposeIntermediateTensorInfo(i);
|
|
return out;
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Mean_impl":"iSHQB","./Transpose_impl":"arYj9","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iSHQB":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "meanImpl", ()=>meanImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reduce = require("../kernel_utils/reduce");
|
|
var _reshape = require("../kernels/Reshape");
|
|
function meanImpl(x, reduceShape, outShape, backend) {
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const batchSize = xSize / inSize;
|
|
const reshapedInput = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
attrs: {
|
|
shape: [
|
|
batchSize,
|
|
inSize
|
|
]
|
|
},
|
|
backend
|
|
});
|
|
const reduced = (0, _reduce.reduce)(reshapedInput, "float32", "mean", backend);
|
|
const reshapedOutput = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
attrs: {
|
|
shape: outShape
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(reshapedInput);
|
|
backend.disposeIntermediateTensorInfo(reduced);
|
|
return reshapedOutput;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/reduce":"dr0Xl","../kernels/Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"pHfvF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "min", ()=>min);
|
|
parcelHelpers.export(exports, "minConfig", ()=>minConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reduce = require("../kernel_utils/reduce");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function min(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
const xRank = x.shape.length;
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
let permutedX = x;
|
|
if (permutedAxes != null) {
|
|
permutedX = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, x.shape.length);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("min", axes, xRank);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(permutedX.shape, axes);
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const a2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: permutedX
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
-1,
|
|
inSize
|
|
]
|
|
}
|
|
});
|
|
const reduced = (0, _reduce.reduce)(a2D, a2D.dtype, "min", backend);
|
|
let res;
|
|
if (keepDims) {
|
|
const newShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(outShape, origAxes);
|
|
res = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: newShape
|
|
}
|
|
});
|
|
} else res = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(a2D);
|
|
backend.disposeIntermediateTensorInfo(reduced);
|
|
if (permutedAxes != null) backend.disposeIntermediateTensorInfo(permutedX);
|
|
return res;
|
|
}
|
|
const minConfig = {
|
|
kernelName: (0, _tfjsCore.Min),
|
|
backendName: "webgl",
|
|
kernelFunc: min
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/reduce":"dr0Xl","./Reshape":"fgZen","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5hTEN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "minimum", ()=>minimum);
|
|
parcelHelpers.export(exports, "minimumConfig", ()=>minimumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopGpu = require("../binaryop_gpu");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const MINIMUM = (0, _binaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
return min(a, b);
|
|
`;
|
|
const MINIMUM_PACKED = `
|
|
vec4 result = vec4(min(a, b));
|
|
bvec4 isNaNA = isnan(a);
|
|
bvec4 isNaNB = isnan(b);
|
|
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
|
|
` + (0, _binaryopPackedGpu.CHECK_NAN_SNIPPET_PACKED) + `
|
|
return result;
|
|
`;
|
|
const minimum = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: MINIMUM,
|
|
packedOpSnippet: MINIMUM_PACKED,
|
|
cpuKernelImpl: (0, _shared.minimumImplCPU)
|
|
});
|
|
const minimumConfig = {
|
|
kernelName: (0, _tfjsCore.Minimum),
|
|
backendName: "webgl",
|
|
kernelFunc: minimum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_gpu":"d0A5z","../binaryop_packed_gpu":"hkzp7","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fGu7V":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mirrorPadKernelFunc", ()=>mirrorPadKernelFunc);
|
|
parcelHelpers.export(exports, "mirrorPadConfig", ()=>mirrorPadConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _mirrorPadGpu = require("../mirror_pad_gpu");
|
|
var _mirrorPadPackedGpu = require("../mirror_pad_packed_gpu");
|
|
const mirrorPadKernelFunc = ({ inputs, backend, attrs })=>{
|
|
const { x } = inputs;
|
|
const { paddings, mode } = attrs;
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new (0, _mirrorPadPackedGpu.MirrorPadPackedProgram)(x.shape, paddings, mode) : new (0, _mirrorPadGpu.MirrorPadProgram)(x.shape, paddings, mode);
|
|
const output = backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
return output;
|
|
};
|
|
const mirrorPadConfig = {
|
|
kernelName: (0, _tfjsCore.MirrorPad),
|
|
backendName: "webgl",
|
|
kernelFunc: mirrorPadKernelFunc
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../mirror_pad_gpu":"1S45c","../mirror_pad_packed_gpu":"fauBg","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1S45c":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MirrorPadProgram", ()=>MirrorPadProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class MirrorPadProgram {
|
|
constructor(xShape, paddings, mode){
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
this.outputShape = paddings.map((p, i)=>p[0] + xShape[i] + p[1]);
|
|
const rank = xShape.length;
|
|
const dtype = (0, _shaderCompiler.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);
|
|
const offset = mode === "reflect" ? 0 : 1;
|
|
if (rank === 1) {
|
|
this.userCode = `
|
|
int start = ${start};
|
|
int end = ${end};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${offset};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${offset};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;
|
|
return;
|
|
}
|
|
this.userCode = `
|
|
${dtype} start = ${dtype}(${start});
|
|
${dtype} end = ${dtype}(${end});
|
|
|
|
void main() {
|
|
${dtype} outC = getOutputCoords();
|
|
for (int i = 0; i < ${rank}; i++) {
|
|
if (outC[i] < start[i]) {
|
|
outC[i] = start[i] * 2 - outC[i] - ${offset};
|
|
} else if(outC[i] >= end[i]) {
|
|
outC[i] = (end[i] - 1) * 2 - outC[i] + ${offset};
|
|
}
|
|
}
|
|
${dtype} coords = outC - start;
|
|
setOutput(getX(${unpackedCoords}));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fauBg":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Example shader code for
|
|
* `mirrorPad(tf.tensor1d([1, 2, 3], 'int32'), [[2, 2]], 'reflect')`
|
|
* ```
|
|
* const int start = int(2);
|
|
* const int end = int(5);
|
|
*
|
|
* void main() {
|
|
* int outputLoc = getOutputCoords();
|
|
* vec4 result = vec4(0.);
|
|
*
|
|
* int rc = outputLoc;
|
|
*
|
|
* int source = rc;
|
|
* if (source < start) {
|
|
* source = start * 2 - source - 0;
|
|
* } else if (source >= end) {
|
|
* source = (end - 1) * 2 - source + 0;
|
|
* }
|
|
* source -= start;
|
|
*
|
|
* result[0] = getChannel(getX(source), source);
|
|
* rc += 1;
|
|
* if(rc < 6) {
|
|
* int source = rc;
|
|
* if (source < start) {
|
|
* source = start * 2 - source - 0;
|
|
* } else if (source >= end) {
|
|
* source = (end - 1) * 2 - source + 0;
|
|
* }
|
|
* source -= start;
|
|
*
|
|
* result[1] = getChannel(getX(source), source);
|
|
* }
|
|
*
|
|
* setOutput(result);
|
|
* }
|
|
* ```
|
|
*/ parcelHelpers.export(exports, "MirrorPadPackedProgram", ()=>MirrorPadPackedProgram);
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class MirrorPadPackedProgram {
|
|
constructor(xShape, paddings, mode){
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.outputShape = paddings.map((p, i)=>p[0] + xShape[i] + p[1]);
|
|
const rank = xShape.length;
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(rank);
|
|
const start = paddings.map((p)=>p[0]).join(",");
|
|
const end = paddings.map((p, i)=>p[0] + xShape[i]).join(",");
|
|
const coords = (0, _packingUtil.getChannels)("rc", rank);
|
|
const source = (0, _packingUtil.getChannels)("source", rank);
|
|
const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;
|
|
const innerDims = rank === 1 ? "source" : `vec2(${source.slice(-2).join()})`;
|
|
const offset = mode === "reflect" ? 0 : 1;
|
|
let mainLoop = "";
|
|
if (rank === 1) {
|
|
const padSetup = `
|
|
${dtype} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${offset};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${offset};
|
|
}
|
|
source -= start;
|
|
`;
|
|
mainLoop = `
|
|
${dtype} rc = outputLoc;
|
|
${padSetup}
|
|
result[0] = getChannel(getX(${source.join()}), ${innerDims});
|
|
${coords[rank - 1]} += 1;
|
|
if(${cLimit}) {
|
|
${padSetup}
|
|
result[1] = getChannel(getX(${source.join()}), ${innerDims});
|
|
}
|
|
`;
|
|
} else {
|
|
const padSetup = `
|
|
${dtype} source = rc;
|
|
${dtype} lt = ${dtype}(lessThan(source, start));
|
|
${dtype} gte = ${dtype}(greaterThanEqual(source, end));
|
|
${dtype} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${offset}) +
|
|
gte * ((end - 1) * 2 - source + ${offset});
|
|
source -= start;
|
|
`;
|
|
mainLoop = `
|
|
${dtype} rc = outputLoc;
|
|
${padSetup}
|
|
result[0] = getChannel(getX(${source.join()}), ${innerDims});
|
|
${coords[rank - 1]} += 1;
|
|
if(${cLimit}) {
|
|
${padSetup}
|
|
result[1] = getChannel(getX(${source.join()}), ${innerDims});
|
|
}
|
|
rc = outputLoc;
|
|
${coords[rank - 2]} += 1;
|
|
if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {
|
|
${padSetup}
|
|
result[2] = getChannel(getX(${source.join()}), ${innerDims});
|
|
${coords[rank - 1]} += 1;
|
|
if(${cLimit}) {
|
|
${padSetup}
|
|
result[3] = getChannel(getX(${source.join()}), ${innerDims});
|
|
}
|
|
}
|
|
`;
|
|
}
|
|
this.userCode = `
|
|
const ${dtype} start = ${dtype}(${start});
|
|
const ${dtype} end = ${dtype}(${end});
|
|
|
|
void main() {
|
|
${dtype} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${mainLoop}
|
|
setOutput(result);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"f0WUU":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mod", ()=>mod);
|
|
parcelHelpers.export(exports, "modConfig", ()=>modConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const MOD = `if (b == 0.0) return NAN;
|
|
return mod(a, b);`;
|
|
const MOD_PACKED = `
|
|
vec4 result = mod(a, b);
|
|
bvec4 isNaN = equal(b, vec4(0.0));
|
|
` + (0, _binaryopPackedGpu.CHECK_NAN_SNIPPET_PACKED) + `
|
|
return result;
|
|
`;
|
|
const mod = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: MOD,
|
|
packedOpSnippet: MOD_PACKED
|
|
});
|
|
const modConfig = {
|
|
kernelName: (0, _tfjsCore.Mod),
|
|
backendName: "webgl",
|
|
kernelFunc: mod
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_packed_gpu":"hkzp7","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"wTvWa":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "multinomial", ()=>multinomial);
|
|
parcelHelpers.export(exports, "multinomialConfig", ()=>multinomialConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _multinomialGpu = require("../multinomial_gpu");
|
|
var _softmax = require("./Softmax");
|
|
function multinomial(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { logits } = inputs;
|
|
const { numSamples, seed, normalized } = attrs;
|
|
const probs = normalized ? logits : (0, _softmax.softmax)({
|
|
inputs: {
|
|
logits
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dim: logits.shape.length - 1
|
|
}
|
|
});
|
|
const batchSize = probs.shape[0];
|
|
const numOutcomes = probs.shape[1];
|
|
const program = new (0, _multinomialGpu.MultinomialProgram)(batchSize, numOutcomes, numSamples);
|
|
const customValues = [
|
|
[
|
|
seed
|
|
]
|
|
];
|
|
const res = backend.runWebGLProgram(program, [
|
|
probs
|
|
], "int32", customValues);
|
|
if (!normalized) backend.disposeIntermediateTensorInfo(probs);
|
|
return res;
|
|
}
|
|
const multinomialConfig = {
|
|
kernelName: (0, _tfjsCore.Multinomial),
|
|
backendName: "webgl",
|
|
kernelFunc: multinomial
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../multinomial_gpu":"6mU57","./Softmax":"cHx7b","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6mU57":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MultinomialProgram", ()=>MultinomialProgram);
|
|
class MultinomialProgram {
|
|
constructor(batchSize, numOutcomes, numSamples){
|
|
this.variableNames = [
|
|
"probs"
|
|
];
|
|
this.customUniforms = [
|
|
{
|
|
name: "seed",
|
|
type: "float"
|
|
}
|
|
];
|
|
this.outputShape = [
|
|
batchSize,
|
|
numSamples
|
|
];
|
|
this.userCode = `
|
|
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}));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cHx7b":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "softmax", ()=>softmax);
|
|
parcelHelpers.export(exports, "softmaxConfig", ()=>softmaxConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _exp = require("./Exp");
|
|
var _max = require("./Max");
|
|
var _realDiv = require("./RealDiv");
|
|
var _reshape = require("./Reshape");
|
|
var _sub = require("./Sub");
|
|
var _sum = require("./Sum");
|
|
function softmax(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { logits } = inputs;
|
|
const { dim } = attrs;
|
|
const axes = (0, _tfjsCore.util).parseAxisParam([
|
|
dim
|
|
], logits.shape);
|
|
const maxLogit = (0, _max.max)({
|
|
inputs: {
|
|
x: logits
|
|
},
|
|
backend,
|
|
attrs: {
|
|
reductionIndices: axes,
|
|
keepDims: false
|
|
}
|
|
});
|
|
const expandedShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(maxLogit.shape, axes);
|
|
const maxLogitsReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: maxLogit
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: expandedShape
|
|
}
|
|
});
|
|
const a = (0, _sub.sub)({
|
|
inputs: {
|
|
a: logits,
|
|
b: maxLogitsReshaped
|
|
},
|
|
backend
|
|
});
|
|
const b = (0, _exp.exp)({
|
|
inputs: {
|
|
x: a
|
|
},
|
|
backend
|
|
});
|
|
const sumExp = (0, _sum.sum)({
|
|
inputs: {
|
|
x: b
|
|
},
|
|
backend,
|
|
attrs: {
|
|
axis: axes,
|
|
keepDims: false
|
|
}
|
|
});
|
|
const sumExpReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: sumExp
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: expandedShape
|
|
}
|
|
});
|
|
const res = (0, _realDiv.realDiv)({
|
|
inputs: {
|
|
a: b,
|
|
b: sumExpReshaped
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(maxLogit);
|
|
backend.disposeIntermediateTensorInfo(maxLogitsReshaped);
|
|
backend.disposeIntermediateTensorInfo(a);
|
|
backend.disposeIntermediateTensorInfo(b);
|
|
backend.disposeIntermediateTensorInfo(sumExp);
|
|
backend.disposeIntermediateTensorInfo(sumExpReshaped);
|
|
return res;
|
|
}
|
|
const softmaxConfig = {
|
|
kernelName: (0, _tfjsCore.Softmax),
|
|
backendName: "webgl",
|
|
kernelFunc: softmax
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Exp":"i4xew","./Max":"11YMi","./RealDiv":"cbtMz","./Reshape":"fgZen","./Sub":"gV1EU","./Sum":"c4eiD","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cbtMz":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "realDiv", ()=>realDiv);
|
|
parcelHelpers.export(exports, "realDivConfig", ()=>realDivConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
// 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 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 DIV_PACKED = `
|
|
// 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 realDiv = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: DIV,
|
|
packedOpSnippet: DIV_PACKED,
|
|
checkOutOfBounds: true
|
|
});
|
|
const realDivConfig = {
|
|
kernelName: (0, _tfjsCore.RealDiv),
|
|
backendName: "webgl",
|
|
kernelFunc: realDiv
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gV1EU":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sub", ()=>sub);
|
|
parcelHelpers.export(exports, "subConfig", ()=>subConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const SUB = "return a - b;";
|
|
const sub = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: SUB,
|
|
packedOpSnippet: SUB,
|
|
supportsComplex: true,
|
|
cpuKernelImpl: (0, _shared.subImplCPU)
|
|
});
|
|
const subConfig = {
|
|
kernelName: (0, _tfjsCore.Sub),
|
|
backendName: "webgl",
|
|
kernelFunc: sub
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6P8i7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
// This doesn't use unaryKernelFunc because negImplCPU is not of type
|
|
// SimpleUnaryKernelImplCPU.
|
|
parcelHelpers.export(exports, "neg", ()=>neg);
|
|
parcelHelpers.export(exports, "negConfig", ()=>negConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
var _unaryopPackedGpu = require("../unaryop_packed_gpu");
|
|
const NEG = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
return -x;
|
|
`;
|
|
const NEG_PACKED = `
|
|
vec4 result = -x;
|
|
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;
|
|
`;
|
|
function neg(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
if (backend.shouldExecuteOnCPU([
|
|
x
|
|
])) {
|
|
const xData = backend.texData.get(x.dataId);
|
|
const [outValues, newShape] = (0, _shared.negImplCPU)(xData.values, x.shape, x.dtype);
|
|
return backend.makeTensorInfo(newShape, x.dtype, outValues);
|
|
}
|
|
let program;
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_PACK_UNARY_OPERATIONS")) program = new (0, _unaryopPackedGpu.UnaryOpPackedProgram)(x.shape, NEG_PACKED);
|
|
else program = new (0, _unaryopGpu.UnaryOpProgram)(x.shape, NEG);
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
const negConfig = {
|
|
kernelName: (0, _tfjsCore.Neg),
|
|
backendName: "webgl",
|
|
kernelFunc: neg
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../unaryop_gpu":"gIMrR","../unaryop_packed_gpu":"c4D5K","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fEqP1":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV3", ()=>nonMaxSuppressionV3);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV3Config", ()=>nonMaxSuppressionV3Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const nonMaxSuppressionV3Impl = (0, _tfjsCore.kernel_impls).nonMaxSuppressionV3Impl;
|
|
function nonMaxSuppressionV3(args) {
|
|
(0, _tfjsCore.backend_util).warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
|
|
const { inputs, backend, attrs } = args;
|
|
const { boxes, scores } = inputs;
|
|
const { maxOutputSize, iouThreshold, scoreThreshold } = attrs;
|
|
const boxesVals = backend.readSync(boxes.dataId);
|
|
const scoresVals = backend.readSync(scores.dataId);
|
|
const { selectedIndices } = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);
|
|
return backend.makeTensorInfo([
|
|
selectedIndices.length
|
|
], "int32", new Int32Array(selectedIndices));
|
|
}
|
|
const nonMaxSuppressionV3Config = {
|
|
kernelName: (0, _tfjsCore.NonMaxSuppressionV3),
|
|
backendName: "webgl",
|
|
kernelFunc: nonMaxSuppressionV3
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5Qv9T":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV4", ()=>nonMaxSuppressionV4);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV4Config", ()=>nonMaxSuppressionV4Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const nonMaxSuppressionV4Impl = (0, _tfjsCore.kernel_impls).nonMaxSuppressionV4Impl;
|
|
function nonMaxSuppressionV4(args) {
|
|
(0, _tfjsCore.backend_util).warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
|
|
const { inputs, backend, attrs } = args;
|
|
const { boxes, scores } = inputs;
|
|
const { maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize } = attrs;
|
|
const boxesVals = backend.readSync(boxes.dataId);
|
|
const scoresVals = backend.readSync(scores.dataId);
|
|
const { selectedIndices, validOutputs } = nonMaxSuppressionV4Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize);
|
|
return [
|
|
backend.makeTensorInfo([
|
|
selectedIndices.length
|
|
], "int32", new Int32Array(selectedIndices)),
|
|
backend.makeTensorInfo([], "int32", new Int32Array([
|
|
validOutputs
|
|
]))
|
|
];
|
|
}
|
|
const nonMaxSuppressionV4Config = {
|
|
kernelName: (0, _tfjsCore.NonMaxSuppressionV4),
|
|
backendName: "webgl",
|
|
kernelFunc: nonMaxSuppressionV4
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"T9Z8C":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV5", ()=>nonMaxSuppressionV5);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV5Config", ()=>nonMaxSuppressionV5Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const nonMaxSuppressionV5Impl = (0, _tfjsCore.kernel_impls).nonMaxSuppressionV5Impl;
|
|
function nonMaxSuppressionV5(args) {
|
|
(0, _tfjsCore.backend_util).warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
|
|
const { inputs, backend, attrs } = args;
|
|
const { boxes, scores } = inputs;
|
|
const { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma } = attrs;
|
|
const boxesVals = backend.readSync(boxes.dataId);
|
|
const scoresVals = backend.readSync(scores.dataId);
|
|
const maxOutputSizeVal = maxOutputSize;
|
|
const iouThresholdVal = iouThreshold;
|
|
const scoreThresholdVal = scoreThreshold;
|
|
const softNmsSigmaVal = softNmsSigma;
|
|
const { selectedIndices, selectedScores } = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal, scoreThresholdVal, softNmsSigmaVal);
|
|
return [
|
|
backend.makeTensorInfo([
|
|
selectedIndices.length
|
|
], "int32", new Int32Array(selectedIndices)),
|
|
backend.makeTensorInfo([
|
|
selectedScores.length
|
|
], "float32", new Float32Array(selectedScores))
|
|
];
|
|
}
|
|
const nonMaxSuppressionV5Config = {
|
|
kernelName: (0, _tfjsCore.NonMaxSuppressionV5),
|
|
backendName: "webgl",
|
|
kernelFunc: nonMaxSuppressionV5
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6SVa6":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "oneHot", ()=>oneHot);
|
|
parcelHelpers.export(exports, "oneHotConfig", ()=>oneHotConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _onehotGpu = require("../onehot_gpu");
|
|
var _reshape = require("./Reshape");
|
|
const oneHot = (args)=>{
|
|
const { inputs, backend, attrs } = args;
|
|
const { indices } = inputs;
|
|
const { dtype, depth, onValue, offValue } = attrs;
|
|
const indicesSize = (0, _tfjsCore.util).sizeFromShape(indices.shape);
|
|
const program = new (0, _onehotGpu.OneHotProgram)(indicesSize, depth, onValue, offValue);
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: indices
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
indicesSize
|
|
]
|
|
}
|
|
});
|
|
const result = backend.runWebGLProgram(program, [
|
|
reshaped
|
|
], dtype);
|
|
backend.disposeIntermediateTensorInfo(reshaped);
|
|
const outShape = [
|
|
...indices.shape,
|
|
depth
|
|
];
|
|
const out = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
return out;
|
|
};
|
|
const oneHotConfig = {
|
|
kernelName: (0, _tfjsCore.OneHot),
|
|
backendName: "webgl",
|
|
kernelFunc: oneHot
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../onehot_gpu":"9D6me","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9D6me":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "OneHotProgram", ()=>OneHotProgram);
|
|
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)));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cH3Uy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "onesLike", ()=>onesLike);
|
|
parcelHelpers.export(exports, "onesLikeConfig", ()=>onesLikeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _complex = require("./Complex");
|
|
var _fill = require("./Fill");
|
|
var _imag = require("./Imag");
|
|
var _real = require("./Real");
|
|
var _zerosLike = require("./ZerosLike");
|
|
function onesLike(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
if (x.dtype === "string") throw new Error("onesLike is not supported under string dtype");
|
|
else if (x.dtype === "complex64") {
|
|
const realPart = (0, _real.real)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const r = onesLike({
|
|
inputs: {
|
|
x: realPart
|
|
},
|
|
backend
|
|
});
|
|
const imagPart = (0, _imag.imag)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const i = (0, _zerosLike.zerosLike)({
|
|
inputs: {
|
|
x: imagPart
|
|
},
|
|
backend
|
|
});
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: r,
|
|
imag: i
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(realPart);
|
|
backend.disposeIntermediateTensorInfo(r);
|
|
backend.disposeIntermediateTensorInfo(imagPart);
|
|
backend.disposeIntermediateTensorInfo(i);
|
|
return result;
|
|
} else // TODO(cais, smilkov): Add WebGL shader for onesLike:
|
|
// https://github.com/tensorflow/tfjs/issues/1293
|
|
return (0, _fill.fill)({
|
|
attrs: {
|
|
shape: x.shape,
|
|
dtype: x.dtype,
|
|
value: 1
|
|
},
|
|
backend
|
|
});
|
|
}
|
|
const onesLikeConfig = {
|
|
kernelName: (0, _tfjsCore.OnesLike),
|
|
backendName: "webgl",
|
|
kernelFunc: onesLike
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Complex":"55NfL","./Fill":"6Rawr","./Imag":"3PMfw","./Real":"4HOZy","./ZerosLike":"28sQG","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"28sQG":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "zerosLike", ()=>zerosLike);
|
|
parcelHelpers.export(exports, "zerosLikeConfig", ()=>zerosLikeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _complex = require("./Complex");
|
|
var _fill = require("./Fill");
|
|
var _imag = require("./Imag");
|
|
var _real = require("./Real");
|
|
function zerosLike(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
if (x.dtype === "complex64") {
|
|
const realPart = (0, _real.real)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const r = zerosLike({
|
|
inputs: {
|
|
x: realPart
|
|
},
|
|
backend
|
|
});
|
|
const imagPart = (0, _imag.imag)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const i = zerosLike({
|
|
inputs: {
|
|
x: imagPart
|
|
},
|
|
backend
|
|
});
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: r,
|
|
imag: i
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(realPart);
|
|
backend.disposeIntermediateTensorInfo(r);
|
|
backend.disposeIntermediateTensorInfo(imagPart);
|
|
backend.disposeIntermediateTensorInfo(i);
|
|
return result;
|
|
} else return (0, _fill.fill)({
|
|
attrs: {
|
|
shape: x.shape,
|
|
dtype: x.dtype,
|
|
value: x.dtype === "string" ? "" : 0
|
|
},
|
|
backend
|
|
});
|
|
}
|
|
const zerosLikeConfig = {
|
|
kernelName: (0, _tfjsCore.ZerosLike),
|
|
backendName: "webgl",
|
|
kernelFunc: zerosLike
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Complex":"55NfL","./Fill":"6Rawr","./Imag":"3PMfw","./Real":"4HOZy","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"73QIj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pack", ()=>pack);
|
|
parcelHelpers.export(exports, "packConfig", ()=>packConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _concat = require("./Concat");
|
|
var _expandDims = require("./ExpandDims");
|
|
function pack(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { axis } = attrs;
|
|
if (inputs.length === 1) return (0, _expandDims.expandDims)({
|
|
inputs: {
|
|
input: inputs[0]
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dim: axis
|
|
}
|
|
});
|
|
const shape = inputs[0].shape;
|
|
const dtype = inputs[0].dtype;
|
|
inputs.forEach((t)=>{
|
|
(0, _tfjsCore.util).assertShapesMatch(shape, t.shape, "All tensors passed to stack must have matching shapes");
|
|
(0, _tfjsCore.util).assert(dtype === t.dtype, ()=>"All tensors passed to stack must have matching dtypes");
|
|
});
|
|
const intermediateTensorInfos = [];
|
|
const expandedTensors = inputs.map((t)=>{
|
|
const expandedT = (0, _expandDims.expandDims)({
|
|
inputs: {
|
|
input: t
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dim: axis
|
|
}
|
|
});
|
|
intermediateTensorInfos.push(expandedT);
|
|
return expandedT;
|
|
});
|
|
const result = (0, _concat.concat)({
|
|
inputs: expandedTensors,
|
|
backend,
|
|
attrs: {
|
|
axis
|
|
}
|
|
});
|
|
intermediateTensorInfos.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return result;
|
|
}
|
|
const packConfig = {
|
|
kernelName: (0, _tfjsCore.Pack),
|
|
backendName: "webgl",
|
|
kernelFunc: pack
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Concat":"2gCZH","./ExpandDims":"5OvP3","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bOlXa":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "padV2", ()=>padV2);
|
|
parcelHelpers.export(exports, "padV2Config", ()=>padV2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _padGpu = require("../pad_gpu");
|
|
var _padPackedGpu = require("../pad_packed_gpu");
|
|
var _fill = require("./Fill");
|
|
const padV2 = (args)=>{
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { paddings, constantValue } = attrs;
|
|
if ((0, _tfjsCore.util).sizeFromShape(x.shape) === 0) {
|
|
// Short-circuit the computation, since x doesn't have value, only
|
|
// the shape is used to compute output shape to pad.
|
|
const outputShape = paddings.map((p, i)=>p[0] + x.shape[i] + p[1]);
|
|
return (0, _fill.fill)({
|
|
backend,
|
|
attrs: {
|
|
shape: outputShape,
|
|
value: constantValue,
|
|
dtype: x.dtype
|
|
}
|
|
});
|
|
}
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new (0, _padPackedGpu.PadPackedProgram)(x.shape, paddings, constantValue) : new (0, _padGpu.PadProgram)(x.shape, paddings, constantValue);
|
|
const customValues = [
|
|
[
|
|
constantValue
|
|
]
|
|
];
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype, customValues);
|
|
};
|
|
const padV2Config = {
|
|
kernelName: (0, _tfjsCore.PadV2),
|
|
backendName: "webgl",
|
|
kernelFunc: padV2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../pad_gpu":"1vFyL","../pad_packed_gpu":"9Lzxa","./Fill":"6Rawr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1vFyL":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "PadProgram", ()=>PadProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class PadProgram {
|
|
constructor(xShape, paddings, constantValue){
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
this.customUniforms = [
|
|
{
|
|
name: "value",
|
|
type: "float"
|
|
}
|
|
];
|
|
this.outputShape = paddings.map((p, i)=>p[0] + xShape[i] + p[1]);
|
|
const rank = xShape.length;
|
|
const type = (0, _shaderCompiler.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(value);
|
|
} 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(value);
|
|
} else {
|
|
${type} coords = outC - start;
|
|
setOutput(getX(${unpackedCoords}));
|
|
}
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9Lzxa":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "PadPackedProgram", ()=>PadPackedProgram);
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class PadPackedProgram {
|
|
constructor(xShape, paddings, constantValue){
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.customUniforms = [
|
|
{
|
|
name: "value",
|
|
type: "float"
|
|
}
|
|
];
|
|
this.outputShape = paddings.map((p, i)=>p[0] + xShape[i] + p[1]);
|
|
const rank = xShape.length;
|
|
const dtype = (0, _shaderCompiler.getCoordsDataType)(rank);
|
|
const start = paddings.map((p)=>p[0]).join(",");
|
|
const end = paddings.map((p, i)=>p[0] + xShape[i]).join(",");
|
|
const coords = (0, _packingUtil.getChannels)("rc", rank);
|
|
const source = (0, _packingUtil.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(value);
|
|
} 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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5GYaP":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pow", ()=>pow);
|
|
parcelHelpers.export(exports, "powConfig", ()=>powConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
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 POW_PACKED = `
|
|
// 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;
|
|
|
|
bvec4 isNaN1 = lessThan(a, vec4(0.0));
|
|
bvec4 isNaN2 = lessThan(floor(b), b);
|
|
bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);
|
|
` + (0, _binaryopPackedGpu.CHECK_NAN_SNIPPET_PACKED) + `
|
|
return result;
|
|
`;
|
|
const pow = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: POW,
|
|
packedOpSnippet: POW_PACKED
|
|
});
|
|
const powConfig = {
|
|
kernelName: (0, _tfjsCore.Pow),
|
|
backendName: "webgl",
|
|
kernelFunc: pow
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_packed_gpu":"hkzp7","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1BmsY":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "prod", ()=>prod);
|
|
parcelHelpers.export(exports, "prodConfig", ()=>prodConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reduce = require("../kernel_utils/reduce");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function prod(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
const xRank = x.shape.length;
|
|
const toDispose = [];
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
let permutedX = x;
|
|
if (permutedAxes != null) {
|
|
permutedX = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, xRank);
|
|
toDispose.push(permutedX);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("prod", axes, xRank);
|
|
let res;
|
|
if (backend.shouldExecuteOnCPU([
|
|
permutedX
|
|
])) {
|
|
const xVals = backend.texData.get(permutedX.dataId).values;
|
|
const { outVals, outShape, outDtype } = (0, _shared.prodImplCPU)(permutedX.shape, permutedX.dtype, xVals, axes);
|
|
res = backend.makeTensorInfo(outShape, outDtype, outVals);
|
|
} else {
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(permutedX.shape, axes);
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const a2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: permutedX
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
-1,
|
|
inSize
|
|
]
|
|
}
|
|
});
|
|
const outputDType = (0, _tfjsCore.sumOutType)(x.dtype);
|
|
const reduced = (0, _reduce.reduce)(a2D, outputDType, "prod", backend);
|
|
res = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: reduced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
toDispose.push(a2D);
|
|
toDispose.push(reduced);
|
|
}
|
|
if (keepDims) {
|
|
toDispose.push(res);
|
|
const newShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(res.shape, origAxes);
|
|
res = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: res
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: newShape
|
|
}
|
|
});
|
|
}
|
|
toDispose.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return res;
|
|
}
|
|
const prodConfig = {
|
|
kernelName: (0, _tfjsCore.Prod),
|
|
backendName: "webgl",
|
|
kernelFunc: prod
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/reduce":"dr0Xl","../kernel_utils/shared":"e4M7v","./Reshape":"fgZen","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dhNCK":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedGather", ()=>raggedGather);
|
|
parcelHelpers.export(exports, "raggedGatherConfig", ()=>raggedGatherConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function raggedGather(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { paramsNestedSplits, paramsDenseValues, indices } = inputs;
|
|
const { outputRaggedRank } = attrs;
|
|
const $paramsNestedSplits = paramsNestedSplits.map((t)=>backend.readSync(t.dataId));
|
|
const $paramsNestedSplitsShapes = paramsNestedSplits.map((t)=>t.shape);
|
|
const $paramsDenseValues = backend.readSync(paramsDenseValues.dataId);
|
|
const $indices = backend.readSync(indices.dataId);
|
|
const [outputNestedSplits, outputDenseValues, outputDenseValuesShape] = (0, _shared.raggedGatherImplCPU)($paramsNestedSplits, $paramsNestedSplitsShapes, $paramsDenseValues, paramsDenseValues.shape, paramsDenseValues.dtype, $indices, indices.shape, outputRaggedRank);
|
|
const outputNestedSplitsTensors = outputNestedSplits.map((splits)=>backend.makeTensorInfo([
|
|
splits.length
|
|
], "int32", splits));
|
|
const outputDenseValuesTensor = backend.makeTensorInfo(outputDenseValuesShape, paramsDenseValues.dtype, outputDenseValues);
|
|
return outputNestedSplitsTensors.concat([
|
|
outputDenseValuesTensor
|
|
]);
|
|
}
|
|
const raggedGatherConfig = {
|
|
kernelName: (0, _tfjsCore.RaggedGather),
|
|
backendName: "webgl",
|
|
kernelFunc: raggedGather
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"e99uc":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedRange", ()=>raggedRange);
|
|
parcelHelpers.export(exports, "raggedRangeConfig", ()=>raggedRangeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function raggedRange(args) {
|
|
const { inputs, backend } = args;
|
|
const { starts, limits, deltas } = inputs;
|
|
const $starts = backend.readSync(starts.dataId);
|
|
const $limits = backend.readSync(limits.dataId);
|
|
const $deltas = backend.readSync(deltas.dataId);
|
|
const [rtNestedSplitsData, rtDenseValuesData] = (0, _shared.raggedRangeImplCPU)($starts, starts.shape, starts.dtype, $limits, limits.shape, $deltas, deltas.shape);
|
|
const rtNestedSplits = backend.makeTensorInfo([
|
|
rtNestedSplitsData.length
|
|
], "int32", rtNestedSplitsData);
|
|
const rtDenseValues = backend.makeTensorInfo([
|
|
rtDenseValuesData.length
|
|
], starts.dtype, rtDenseValuesData);
|
|
return [
|
|
rtNestedSplits,
|
|
rtDenseValues
|
|
];
|
|
}
|
|
const raggedRangeConfig = {
|
|
kernelName: (0, _tfjsCore.RaggedRange),
|
|
backendName: "webgl",
|
|
kernelFunc: raggedRange
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c17RR":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedTensorToTensor", ()=>raggedTensorToTensor);
|
|
parcelHelpers.export(exports, "raggedTensorToTensorConfig", ()=>raggedTensorToTensorConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function raggedTensorToTensor(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { shape, values, defaultValue, rowPartitionTensors } = inputs;
|
|
const { rowPartitionTypes } = attrs;
|
|
const $shape = backend.readSync(shape.dataId);
|
|
const $values = backend.readSync(values.dataId);
|
|
const $defaultValue = backend.readSync(defaultValue.dataId);
|
|
const $rowPartitionValues = rowPartitionTensors.map((t)=>backend.readSync(t.dataId));
|
|
const rowPartitionValuesShapes = rowPartitionTensors.map((t)=>t.shape);
|
|
const [outputShape, output] = (0, _shared.raggedTensorToTensorImplCPU)($shape, shape.shape, $values, values.shape, values.dtype, $defaultValue, defaultValue.shape, $rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes);
|
|
return backend.makeTensorInfo(outputShape, values.dtype, output);
|
|
}
|
|
const raggedTensorToTensorConfig = {
|
|
kernelName: (0, _tfjsCore.RaggedTensorToTensor),
|
|
backendName: "webgl",
|
|
kernelFunc: raggedTensorToTensor
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4ulNZ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "range", ()=>range);
|
|
parcelHelpers.export(exports, "rangeConfig", ()=>rangeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const range = (args)=>{
|
|
const { backend, attrs } = args;
|
|
const { start, stop, step, dtype } = attrs;
|
|
const values = (0, _shared.rangeImplCPU)(start, stop, step, dtype);
|
|
return backend.makeTensorInfo([
|
|
values.length
|
|
], dtype, values);
|
|
};
|
|
const rangeConfig = {
|
|
kernelName: (0, _tfjsCore.Range),
|
|
backendName: "webgl",
|
|
kernelFunc: range
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5wKjZ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reciprocal", ()=>reciprocal);
|
|
parcelHelpers.export(exports, "reciprocalConfig", ()=>reciprocalConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const RECIPROCAL = `return 1.0 / x;`;
|
|
const reciprocal = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: RECIPROCAL
|
|
});
|
|
const reciprocalConfig = {
|
|
kernelName: (0, _tfjsCore.Reciprocal),
|
|
backendName: "webgl",
|
|
kernelFunc: reciprocal
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fTpFl":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "relu", ()=>relu);
|
|
parcelHelpers.export(exports, "reluConfig", ()=>reluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const RELU = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`;
|
|
const RELU_PACKED = `
|
|
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 relu = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: RELU,
|
|
packedOpSnippet: RELU_PACKED
|
|
});
|
|
const reluConfig = {
|
|
kernelName: (0, _tfjsCore.Relu),
|
|
backendName: "webgl",
|
|
kernelFunc: relu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"inRmD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "relu6", ()=>relu6);
|
|
parcelHelpers.export(exports, "relu6Config", ()=>relu6Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
const RELU6 = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`;
|
|
const RELU6_PACKED = `
|
|
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 relu6 = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: RELU6,
|
|
packedOpSnippet: RELU6_PACKED
|
|
});
|
|
const relu6Config = {
|
|
kernelName: (0, _tfjsCore.Relu6),
|
|
backendName: "webgl",
|
|
kernelFunc: relu6
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iNia7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeBilinear", ()=>resizeBilinear);
|
|
parcelHelpers.export(exports, "resizeBilinearConfig", ()=>resizeBilinearConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _resizeBilinearGpu = require("../resize_bilinear_gpu");
|
|
var _resizeBilinearPackedGpu = require("../resize_bilinear_packed_gpu");
|
|
function resizeBilinear(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { images } = inputs;
|
|
const { alignCorners, halfPixelCenters, size } = attrs;
|
|
const [newHeight, newWidth] = size;
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new (0, _resizeBilinearPackedGpu.ResizeBilinearPackedProgram)(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters) : new (0, _resizeBilinearGpu.ResizeBilinearProgram)(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters);
|
|
return backend.runWebGLProgram(program, [
|
|
images
|
|
], "float32");
|
|
}
|
|
const resizeBilinearConfig = {
|
|
kernelName: (0, _tfjsCore.ResizeBilinear),
|
|
backendName: "webgl",
|
|
kernelFunc: resizeBilinear
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../resize_bilinear_gpu":"bR7AJ","../resize_bilinear_packed_gpu":"gl6xN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bR7AJ":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ResizeBilinearProgram", ()=>ResizeBilinearProgram);
|
|
class ResizeBilinearProgram {
|
|
constructor(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters){
|
|
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
|
|
];
|
|
let sourceFracIndexRC;
|
|
if (halfPixelCenters) sourceFracIndexRC = `(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC` + ` - vec2(0.5)`;
|
|
else sourceFracIndexRC = `vec2(yRC) * effectiveInputOverOutputRatioRC`;
|
|
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 = ${sourceFracIndexRC};
|
|
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gl6xN":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ResizeBilinearPackedProgram", ()=>ResizeBilinearPackedProgram);
|
|
class ResizeBilinearPackedProgram {
|
|
constructor(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters){
|
|
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
|
|
];
|
|
let sourceFracIndexRC;
|
|
if (halfPixelCenters) sourceFracIndexRC = `(vec3(yRC) + vec3(0.5)) * ` + `effectiveInputOverOutputRatioRC - vec3(0.5)`;
|
|
else sourceFracIndexRC = `vec3(yRC) * effectiveInputOverOutputRatioRC`;
|
|
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 = ${sourceFracIndexRC};
|
|
|
|
// Compute the four integer indices.
|
|
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gEi6O":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeBilinearGrad", ()=>resizeBilinearGrad);
|
|
parcelHelpers.export(exports, "resizeBilinearGradConfig", ()=>resizeBilinearGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _resizeBilinearBackpropGpu = require("../resize_bilinear_backprop_gpu");
|
|
function resizeBilinearGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { images, dy } = inputs;
|
|
const { alignCorners } = attrs;
|
|
const program = new (0, _resizeBilinearBackpropGpu.ResizeBilinearBackpropProgram)(dy.shape, images.shape, alignCorners);
|
|
return backend.runWebGLProgram(program, [
|
|
dy
|
|
], dy.dtype);
|
|
}
|
|
const resizeBilinearGradConfig = {
|
|
kernelName: (0, _tfjsCore.ResizeBilinearGrad),
|
|
backendName: "webgl",
|
|
kernelFunc: resizeBilinearGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../resize_bilinear_backprop_gpu":"cwxV9","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cwxV9":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ResizeBilinearBackpropProgram", ()=>ResizeBilinearBackpropProgram);
|
|
class ResizeBilinearBackpropProgram {
|
|
constructor(dyShape, inputShape, alignCorners){
|
|
this.variableNames = [
|
|
"dy"
|
|
];
|
|
this.outputShape = [];
|
|
this.outputShape = inputShape;
|
|
const [, xHeight, xWidth] = inputShape;
|
|
const [, yHeight, yWidth] = dyShape;
|
|
// 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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eTSe5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeNearestNeighbor", ()=>resizeNearestNeighbor);
|
|
parcelHelpers.export(exports, "resizeNearestNeighborConfig", ()=>resizeNearestNeighborConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _resizeNearestNeighborGpu = require("../resize_nearest_neighbor_gpu");
|
|
var _resizeNearestNeighborPackedGpu = require("../resize_nearest_neighbor_packed_gpu");
|
|
function resizeNearestNeighbor(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { images } = inputs;
|
|
const { alignCorners, halfPixelCenters, size } = attrs;
|
|
const [newHeight, newWidth] = size;
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new (0, _resizeNearestNeighborPackedGpu.ResizeNearestNeighborPackedProgram)(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters) : new (0, _resizeNearestNeighborGpu.ResizeNearestNeighborProgram)(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters);
|
|
return backend.runWebGLProgram(program, [
|
|
images
|
|
], images.dtype);
|
|
}
|
|
const resizeNearestNeighborConfig = {
|
|
kernelName: (0, _tfjsCore.ResizeNearestNeighbor),
|
|
backendName: "webgl",
|
|
kernelFunc: resizeNearestNeighbor
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../resize_nearest_neighbor_gpu":"ggWuj","../resize_nearest_neighbor_packed_gpu":"92adt","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ggWuj":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ResizeNearestNeighborProgram", ()=>ResizeNearestNeighborProgram);
|
|
class ResizeNearestNeighborProgram {
|
|
constructor(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters){
|
|
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";
|
|
let sourceFracIndexRC;
|
|
if (halfPixelCenters) sourceFracIndexRC = `max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC` + `, vec2(0.0))`;
|
|
else sourceFracIndexRC = `vec2(yRC) * effectiveInputOverOutputRatioRC`;
|
|
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 = ${sourceFracIndexRC};
|
|
|
|
// 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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"92adt":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ResizeNearestNeighborPackedProgram", ()=>ResizeNearestNeighborPackedProgram);
|
|
class ResizeNearestNeighborPackedProgram {
|
|
constructor(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters){
|
|
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
|
|
];
|
|
// When align corners is false, we rounds the value with floor.
|
|
const roundBase = alignCorners ? "0.5" : "0.0";
|
|
let sourceFracIndexRC;
|
|
if (halfPixelCenters) sourceFracIndexRC = `max((vec3(yRC) + vec3(0.5)) * ` + `effectiveInputOverOutputRatioRC, vec3(0.0))`;
|
|
else sourceFracIndexRC = `vec3(yRC) * effectiveInputOverOutputRatioRC`;
|
|
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 = ${sourceFracIndexRC};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec3 sourceNearestRC = ivec3(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${depth - 1};
|
|
bool hasNextRow = coords.z < ${newWidth - 1};
|
|
|
|
vec4 newValue = vec4(
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fZoE2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeNearestNeighborGrad", ()=>resizeNearestNeighborGrad);
|
|
parcelHelpers.export(exports, "resizeNearestNeighborGradConfig", ()=>resizeNearestNeighborGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _resizeNearestNeighborBackpropGpu = require("../resize_nearest_neighbor_backprop_gpu");
|
|
function resizeNearestNeighborGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { images, dy } = inputs;
|
|
const { alignCorners } = attrs;
|
|
const program = new (0, _resizeNearestNeighborBackpropGpu.ResizeNearestNeigborBackpropProgram)(dy.shape, images.shape, alignCorners);
|
|
return backend.runWebGLProgram(program, [
|
|
dy
|
|
], dy.dtype);
|
|
}
|
|
const resizeNearestNeighborGradConfig = {
|
|
kernelName: (0, _tfjsCore.ResizeNearestNeighborGrad),
|
|
backendName: "webgl",
|
|
kernelFunc: resizeNearestNeighborGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../resize_nearest_neighbor_backprop_gpu":"9j4W1","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9j4W1":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ResizeNearestNeigborBackpropProgram", ()=>ResizeNearestNeigborBackpropProgram);
|
|
class ResizeNearestNeigborBackpropProgram {
|
|
constructor(dyShape, inputShape, alignCorners){
|
|
this.variableNames = [
|
|
"dy"
|
|
];
|
|
this.outputShape = [];
|
|
this.outputShape = inputShape;
|
|
const [, xHeight, xWidth] = inputShape;
|
|
const [, yHeight, yWidth] = dyShape;
|
|
// 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);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"81ghw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reverse", ()=>reverse);
|
|
parcelHelpers.export(exports, "reverseConfig", ()=>reverseConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reverseGpu = require("../reverse_gpu");
|
|
var _reversePackedGpu = require("../reverse_packed_gpu");
|
|
var _identity = require("./Identity");
|
|
function reverse(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { dims } = attrs;
|
|
const xRank = x.shape.length;
|
|
const $dims = (0, _tfjsCore.util).parseAxisParam(dims, x.shape);
|
|
if (xRank === 0) return (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
const program = (0, _tfjsCore.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new (0, _reversePackedGpu.ReversePackedProgram)(x.shape, $dims) : new (0, _reverseGpu.ReverseProgram)(x.shape, $dims);
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
const reverseConfig = {
|
|
kernelName: (0, _tfjsCore.Reverse),
|
|
backendName: "webgl",
|
|
kernelFunc: reverse
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../reverse_gpu":"iDwSz","../reverse_packed_gpu":"jpTar","./Identity":"hY9aT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iDwSz":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ReverseProgram", ()=>ReverseProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class 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 = (0, _shaderCompiler.getCoordsDataType)(rank);
|
|
this.userCode = `
|
|
void main() {
|
|
${type} coords = getOutputCoords();
|
|
setOutput(getX(${inCoords}));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jpTar":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ReversePackedProgram", ()=>ReversePackedProgram);
|
|
var _packingUtil = require("./packing_util");
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class 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 = (0, _packingUtil.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 = (0, _shaderCompiler.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]}`;
|
|
}
|
|
}
|
|
}
|
|
|
|
},{"./packing_util":"5ylpz","./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7nWSD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rotateWithOffsetConfig", ()=>rotateWithOffsetConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _rotateGpu = require("../rotate_gpu");
|
|
const rotateWithOffsetConfig = {
|
|
kernelName: (0, _tfjsCore.RotateWithOffset),
|
|
backendName: "webgl",
|
|
kernelFunc: ({ inputs, attrs, backend })=>{
|
|
const { image } = inputs;
|
|
const { radians, fillValue, center } = attrs;
|
|
const webglBackend = backend;
|
|
const program = new (0, _rotateGpu.RotateProgram)(image.shape, fillValue);
|
|
const [centerX, centerY] = (0, _tfjsCore.backend_util).getImageCenter(center, image.shape[1], image.shape[2]);
|
|
const customValues = [
|
|
[
|
|
centerX,
|
|
centerY,
|
|
Math.sin(radians),
|
|
Math.cos(radians)
|
|
]
|
|
];
|
|
const output = webglBackend.runWebGLProgram(program, [
|
|
image
|
|
], image.dtype, customValues);
|
|
return output;
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../rotate_gpu":"1XVMP","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1XVMP":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "RotateProgram", ()=>RotateProgram);
|
|
class RotateProgram {
|
|
constructor(imageShape, fillValue){
|
|
this.variableNames = [
|
|
"Image"
|
|
];
|
|
this.outputShape = [];
|
|
this.customUniforms = [
|
|
{
|
|
name: "params",
|
|
type: "vec4"
|
|
}
|
|
];
|
|
const imageHeight = imageShape[1];
|
|
const imageWidth = imageShape[2];
|
|
this.outputShape = imageShape;
|
|
let fillSnippet = "";
|
|
if (typeof fillValue === "number") fillSnippet = `float outputValue = ${fillValue.toFixed(2)};`;
|
|
else fillSnippet = `
|
|
vec3 fill = vec3(${fillValue.join(",")});
|
|
float outputValue = fill[coords[3]];`;
|
|
this.userCode = `
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
float coordXFloat = (float(x) - params[0]) * params[3] -
|
|
(float(y) - params[1]) * params[2];
|
|
float coordYFloat = (float(x) - params[0]) * params[2] +
|
|
(float(y) - params[1]) * params[3];
|
|
int coordX = int(round(coordXFloat + params[0]));
|
|
int coordY = int(round(coordYFloat + params[1]));
|
|
${fillSnippet}
|
|
if(coordX >= 0 && coordX < ${imageWidth} && coordY >= 0 && coordY < ${imageHeight}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gGWXk":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "round", ()=>round);
|
|
parcelHelpers.export(exports, "roundConfig", ()=>roundConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
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 round = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: ROUND
|
|
});
|
|
const roundConfig = {
|
|
kernelName: (0, _tfjsCore.Round),
|
|
backendName: "webgl",
|
|
kernelFunc: round
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2xH8K":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rsqrt", ()=>rsqrt);
|
|
parcelHelpers.export(exports, "rsqrtConfig", ()=>rsqrtConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const RSQRT = `return inversesqrt(x);`;
|
|
const rsqrt = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: RSQRT,
|
|
cpuKernelImpl: (0, _shared.rsqrtImplCPU)
|
|
});
|
|
const rsqrtConfig = {
|
|
kernelName: (0, _tfjsCore.Rsqrt),
|
|
backendName: "webgl",
|
|
kernelFunc: rsqrt
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cYHjA":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "scatterNd", ()=>scatterNd);
|
|
parcelHelpers.export(exports, "scatterNdConfig", ()=>scatterNdConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _scatterGpu = require("../scatter_gpu");
|
|
var _scatterPackedGpu = require("../scatter_packed_gpu");
|
|
var _reshape = require("./Reshape");
|
|
function scatterNd(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { indices, updates } = inputs;
|
|
const { shape } = attrs;
|
|
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = (0, _tfjsCore.backend_util).calculateShapes(updates, indices, shape);
|
|
const flattenShape = [
|
|
outputSize / sliceSize,
|
|
sliceSize
|
|
];
|
|
if (outputSize === 0) return backend.makeTensorInfo(shape, indices.dtype);
|
|
const flattenIndices = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: indices
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
numUpdates,
|
|
sliceRank
|
|
]
|
|
}
|
|
});
|
|
const flattenX = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: updates
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
numUpdates,
|
|
sliceSize
|
|
]
|
|
}
|
|
});
|
|
const defaultValue = backend.makeTensorInfo([], "float32", new Float32Array([
|
|
0
|
|
])); // scalar(0)
|
|
let program;
|
|
if ((0, _tfjsCore.env)().getBool("WEBGL_PACK")) program = new (0, _scatterPackedGpu.ScatterPackedProgram)(numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length, strides, flattenShape);
|
|
else program = new (0, _scatterGpu.ScatterProgram)(numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length, strides, flattenShape);
|
|
const res = backend.runWebGLProgram(program, [
|
|
flattenX,
|
|
flattenIndices,
|
|
defaultValue
|
|
], flattenX.dtype);
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: res
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(flattenIndices);
|
|
backend.disposeIntermediateTensorInfo(flattenX);
|
|
backend.disposeIntermediateTensorInfo(res);
|
|
backend.disposeIntermediateTensorInfo(defaultValue);
|
|
return reshaped;
|
|
}
|
|
const scatterNdConfig = {
|
|
kernelName: (0, _tfjsCore.ScatterNd),
|
|
backendName: "webgl",
|
|
kernelFunc: scatterNd
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../scatter_gpu":"kN25X","../scatter_packed_gpu":"gWrr3","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kN25X":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ScatterProgram", ()=>ScatterProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class ScatterProgram {
|
|
constructor(updateSize, sliceDim, indicesRank, updatesRank, strides, shape, summingDupeIndex = true, defaultIsTensor = false){
|
|
this.variableNames = [
|
|
"updates",
|
|
"indices",
|
|
"defaultValue"
|
|
];
|
|
this.outputShape = shape;
|
|
const stridesType = (0, _shaderCompiler.getCoordsDataType)(strides.length);
|
|
const dtype = (0, _shaderCompiler.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})`;
|
|
let defaultValuesString = "";
|
|
if (defaultIsTensor) defaultValuesString = "coords[0], coords[1]";
|
|
const defaultValueSnippet = `getDefaultValue(${defaultValuesString})`;
|
|
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(${defaultValueSnippet}, sum, float(found)));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gWrr3":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ScatterPackedProgram", ()=>ScatterPackedProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class ScatterPackedProgram {
|
|
constructor(updateSize, sliceDim, indicesRank, updatesRank, strides, shape, summingDupeIndex = true, defaultIsTensor = false){
|
|
this.variableNames = [
|
|
"updates",
|
|
"indices",
|
|
"defaultValue"
|
|
];
|
|
this.packedInputs = true;
|
|
this.packedOutput = true;
|
|
this.outputShape = shape;
|
|
const stridesType = (0, _shaderCompiler.getCoordsDataType)(strides.length);
|
|
const dtype = (0, _shaderCompiler.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})`;
|
|
let defaultValuesString = "";
|
|
if (defaultIsTensor) defaultValuesString = "coords[0], coords[1]";
|
|
const defaultValueSnippet = `getDefaultValue(${defaultValuesString})`;
|
|
const strideString = sliceDim > 1 ? "strides[j]" : "strides";
|
|
const strideString2 = sliceDim > 1 ? "strides[j + 1]" : "strides";
|
|
this.userCode = `
|
|
${stridesType} strides = ${stridesType}(${strides});
|
|
|
|
void main() {
|
|
${dtype} coords = getOutputCoords();
|
|
vec4 sum = vec4(0.);
|
|
vec4 found = vec4(0.);
|
|
for (int i = 0; i < ${updateSize}; i+=2) {
|
|
ivec2 flattenedIndex = ivec2(0);
|
|
for (int j = 0; j < ${sliceDim}; j+=2) {
|
|
ivec4 index = round(${indicesSnippet});
|
|
flattenedIndex += index.xz * ${strideString};
|
|
if (j + 1 < ${sliceDim}) {
|
|
flattenedIndex += index.yw * ${strideString2};
|
|
}
|
|
}
|
|
if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
|
|
flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
|
|
vec4 updVals = ${updatesSnippet};
|
|
if (flattenedIndex[0] == coords[0]) {
|
|
sum.xy += updVals.xy;
|
|
found.xy = vec2(1.);
|
|
} else if (flattenedIndex[0] == coords[0] + 1) {
|
|
sum.zw += updVals.xy;
|
|
found.zw = vec2(1.);
|
|
}
|
|
if (flattenedIndex[1] == coords[0]) {
|
|
sum.xy += updVals.zw;
|
|
found.xy = vec2(1.);
|
|
} else if (flattenedIndex[1] == coords[0] + 1) {
|
|
sum.zw += updVals.zw;
|
|
found.zw = vec2(1.);
|
|
}
|
|
}
|
|
}
|
|
setOutput(mix(${defaultValueSnippet}, sum, found));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kyGeI":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "searchSorted", ()=>searchSorted);
|
|
parcelHelpers.export(exports, "searchSortedConfig", ()=>searchSortedConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _searchSortedGpu = require("../search_sorted_gpu");
|
|
function searchSorted(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { sortedSequence, values } = inputs;
|
|
const { side } = attrs;
|
|
const program = new (0, _searchSortedGpu.SearchSortedProgram)(sortedSequence.shape[0], sortedSequence.shape[1], values.shape[1], side);
|
|
const customValues = [
|
|
[
|
|
sortedSequence.shape[1]
|
|
]
|
|
];
|
|
return backend.runWebGLProgram(program, [
|
|
sortedSequence,
|
|
values
|
|
], "int32", customValues);
|
|
}
|
|
const searchSortedConfig = {
|
|
kernelName: (0, _tfjsCore.SearchSorted),
|
|
backendName: "webgl",
|
|
kernelFunc: searchSorted
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../search_sorted_gpu":"1IKeg","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1IKeg":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "SearchSortedProgram", ()=>SearchSortedProgram);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
class SearchSortedProgram {
|
|
constructor(batchSize, numInputs, numValues, side){
|
|
this.variableNames = [
|
|
"sortedSequence",
|
|
"values"
|
|
];
|
|
this.customUniforms = [
|
|
{
|
|
name: "numInputs",
|
|
type: "int"
|
|
}
|
|
];
|
|
this.outputShape = [
|
|
batchSize,
|
|
numValues
|
|
];
|
|
const webGL2LoopHead = "while (left < right) {";
|
|
// WebGL1 doesn't accept non constant loop conditions, so upper bound loop
|
|
// iterations.
|
|
const webGL1LoopHead = `for (int i = 0; i < ${Math.ceil(Math.log2(numInputs + 1))}; ++i) { if (left >= right) break;`;
|
|
const loopHead = (0, _tfjsCore.env)().getNumber("WEBGL_VERSION") === 2 ? webGL2LoopHead : webGL1LoopHead;
|
|
// left corresponds to lower bound and right to upper bound.
|
|
const boundComparator = side === "left" ? "<" : "<=";
|
|
this.userCode = `
|
|
int findBound(int batch, float value) {
|
|
int left = 0;
|
|
int right = numInputs;
|
|
int mid;
|
|
${loopHead}
|
|
mid = (left + right) / 2;
|
|
if (getSortedSequence(batch, mid) ${boundComparator} value) {
|
|
left = mid + 1;
|
|
} else {
|
|
right = mid;
|
|
}
|
|
}
|
|
return right;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int valueIndex = coords[1];
|
|
|
|
float value = getValues(batch, valueIndex);
|
|
|
|
setOutput(float(findBound(batch, value)));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b6rGf":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "select", ()=>select);
|
|
parcelHelpers.export(exports, "selectConfig", ()=>selectConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _selectGpu = require("../select_gpu");
|
|
function select(args) {
|
|
const { inputs, backend } = args;
|
|
const { condition, t, e } = inputs;
|
|
const program = new (0, _selectGpu.SelectProgram)(condition.shape.length, t.shape, t.shape.length);
|
|
return backend.runWebGLProgram(program, [
|
|
condition,
|
|
t,
|
|
e
|
|
], (0, _tfjsCore.upcastType)(t.dtype, e.dtype));
|
|
}
|
|
const selectConfig = {
|
|
kernelName: (0, _tfjsCore.Select),
|
|
backendName: "webgl",
|
|
kernelFunc: select
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../select_gpu":"apyaJ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"apyaJ":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "SelectProgram", ()=>SelectProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class 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 = (0, _shaderCompiler.getCoordsDataType)(rank);
|
|
this.userCode = `
|
|
void main() {
|
|
${dtype} resRC = getOutputCoords();
|
|
float cVal = getC(${cCoords});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${abCoords}));
|
|
} else {
|
|
setOutput(getB(${abCoords}));
|
|
}
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1HlBg":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "selu", ()=>selu);
|
|
parcelHelpers.export(exports, "seluConfig", ()=>seluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const SELU = `
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${(0, _tfjsCore.backend_util).SELU_SCALEALPHA};
|
|
float scale = ${(0, _tfjsCore.backend_util).SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`;
|
|
const selu = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: SELU
|
|
});
|
|
const seluConfig = {
|
|
kernelName: (0, _tfjsCore.Selu),
|
|
backendName: "webgl",
|
|
kernelFunc: selu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c3gWE":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sigmoid", ()=>sigmoid);
|
|
parcelHelpers.export(exports, "sigmoidConfig", ()=>sigmoidConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const SIGMOID = (0, _kernelFuncsUtils.CHECK_NAN_SNIPPET_UNARY) + `
|
|
return 1.0 / (1.0 + exp(-1.0 * x));
|
|
`;
|
|
const SIGMOID_PACKED = `
|
|
vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
|
|
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 sigmoid = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: SIGMOID,
|
|
packedOpSnippet: SIGMOID_PACKED,
|
|
cpuKernelImpl: (0, _shared.sigmoidImplCPU)
|
|
});
|
|
const sigmoidConfig = {
|
|
kernelName: (0, _tfjsCore.Sigmoid),
|
|
backendName: "webgl",
|
|
kernelFunc: sigmoid
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"83hlB":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sign", ()=>sign);
|
|
parcelHelpers.export(exports, "signConfig", ()=>signConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
// Sign does not propagate NANs.
|
|
const SIGN = `
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`;
|
|
const sign = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: SIGN
|
|
});
|
|
const signConfig = {
|
|
kernelName: (0, _tfjsCore.Sign),
|
|
backendName: "webgl",
|
|
kernelFunc: sign
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6Fn44":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sin", ()=>sin);
|
|
parcelHelpers.export(exports, "sinConfig", ()=>sinConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryopPackedGpu = require("../binaryop_packed_gpu");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const SIN = (0, _kernelFuncsUtils.CHECK_NAN_SNIPPET_UNARY) + `
|
|
return sin(x);
|
|
`;
|
|
const SIN_PACKED = `
|
|
vec4 result = sin(x);
|
|
bvec4 isNaN = isnan(x);
|
|
${(0, _binaryopPackedGpu.CHECK_NAN_SNIPPET_PACKED)}
|
|
return result;
|
|
`;
|
|
const sin = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: SIN,
|
|
packedOpSnippet: SIN_PACKED
|
|
});
|
|
const sinConfig = {
|
|
kernelName: (0, _tfjsCore.Sin),
|
|
backendName: "webgl",
|
|
kernelFunc: sin
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../binaryop_packed_gpu":"hkzp7","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9tvOm":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sinh", ()=>sinh);
|
|
parcelHelpers.export(exports, "sinhConfig", ()=>sinhConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const SINH = `
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`;
|
|
const sinh = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: SINH
|
|
});
|
|
const sinhConfig = {
|
|
kernelName: (0, _tfjsCore.Sinh),
|
|
backendName: "webgl",
|
|
kernelFunc: sinh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1YmQs":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "softplus", ()=>softplus);
|
|
parcelHelpers.export(exports, "softplusConfig", ()=>softplusConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
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 softplus = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: SOFTPLUS
|
|
});
|
|
const softplusConfig = {
|
|
kernelName: (0, _tfjsCore.Softplus),
|
|
backendName: "webgl",
|
|
kernelFunc: softplus
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"58w9T":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "spaceToBatchND", ()=>spaceToBatchND);
|
|
parcelHelpers.export(exports, "spaceToBatchNDConfig", ()=>spaceToBatchNDConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _padV2 = require("./PadV2");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
const spaceToBatchND = (args)=>{
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { blockShape, paddings } = attrs;
|
|
(0, _tfjsCore.util).assert(x.shape.length <= 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 toDispose = [];
|
|
const paddedX = (0, _padV2.padV2)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
paddings: completePaddings,
|
|
constantValue: 0
|
|
}
|
|
});
|
|
const reshapedPaddedShape = (0, _tfjsCore.backend_util).getReshaped(paddedX.shape, blockShape, prod, false);
|
|
const permutedReshapedPaddedPermutation = (0, _tfjsCore.backend_util).getPermuted(reshapedPaddedShape.length, blockShape.length, false);
|
|
const flattenShape = (0, _tfjsCore.backend_util).getReshapedPermuted(paddedX.shape, blockShape, prod, false);
|
|
const reshapedPaddedX = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: paddedX
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: reshapedPaddedShape
|
|
}
|
|
});
|
|
const paddedXT = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: reshapedPaddedX
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedReshapedPaddedPermutation
|
|
}
|
|
});
|
|
const result = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: paddedXT
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: flattenShape
|
|
}
|
|
});
|
|
toDispose.push(paddedX);
|
|
toDispose.push(reshapedPaddedX);
|
|
toDispose.push(paddedXT);
|
|
toDispose.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return result;
|
|
};
|
|
const spaceToBatchNDConfig = {
|
|
kernelName: (0, _tfjsCore.SpaceToBatchND),
|
|
backendName: "webgl",
|
|
kernelFunc: spaceToBatchND
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./PadV2":"bOlXa","./Reshape":"fgZen","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iVlEr":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseFillEmptyRows", ()=>sparseFillEmptyRows);
|
|
parcelHelpers.export(exports, "sparseFillEmptyRowsConfig", ()=>sparseFillEmptyRowsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function sparseFillEmptyRows(args) {
|
|
const { inputs, backend } = args;
|
|
const { indices, values, denseShape, defaultValue } = inputs;
|
|
if (denseShape.shape.length !== 1) throw new Error(`Dense shape must be a vector, saw:
|
|
${denseShape.shape}`);
|
|
if (indices.shape.length !== 2) throw new Error(`Indices must be a matrix, saw:
|
|
${indices.shape}`);
|
|
if (values.shape.length !== 1) throw new Error(`Values must be a vector, saw:
|
|
${values.shape}`);
|
|
if (defaultValue.shape.length !== 0) throw new Error(`Default value must be a scalar, saw:
|
|
${defaultValue.shape}`);
|
|
const $indices = backend.readSync(indices.dataId);
|
|
const $values = backend.readSync(values.dataId);
|
|
const $denseShape = backend.readSync(denseShape.dataId);
|
|
const $defaultValue = backend.readSync(defaultValue.dataId)[0];
|
|
const [outputIndices, outputIndicesShape, outputValues, emptyRowIndicator, reverseIndexMap] = (0, _shared.sparseFillEmptyRowsImplCPU)($indices, indices.shape, indices.dtype, $values, values.dtype, $denseShape, $defaultValue);
|
|
return [
|
|
backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),
|
|
backend.makeTensorInfo([
|
|
outputIndicesShape[0]
|
|
], values.dtype, outputValues),
|
|
backend.makeTensorInfo([
|
|
emptyRowIndicator.length
|
|
], "bool", new Uint8Array(emptyRowIndicator.map((value)=>Number(value)))),
|
|
backend.makeTensorInfo([
|
|
reverseIndexMap.length
|
|
], indices.dtype, new Int32Array(reverseIndexMap))
|
|
];
|
|
}
|
|
const sparseFillEmptyRowsConfig = {
|
|
kernelName: (0, _tfjsCore.SparseFillEmptyRows),
|
|
backendName: "webgl",
|
|
kernelFunc: sparseFillEmptyRows
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"arBQ7":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseReshape", ()=>sparseReshape);
|
|
parcelHelpers.export(exports, "sparseReshapeConfig", ()=>sparseReshapeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function sparseReshape(args) {
|
|
const { inputs, backend } = args;
|
|
const { inputIndices, inputShape, newShape } = inputs;
|
|
if (inputIndices.shape.length !== 2) throw new Error(`Input indices should be a matrix but received shape ${inputIndices.shape}`);
|
|
if (inputShape.shape.length !== 1) throw new Error(`Input shape should be a vector but received shape ${inputShape.shape}`);
|
|
if (newShape.shape.length !== 1) throw new Error(`Target shape should be a vector but received shape ${newShape.shape}`);
|
|
const $inputShape = Array.from(backend.readSync(inputShape.dataId));
|
|
const $inputIndices = backend.readSync(inputIndices.dataId);
|
|
const targetShape = Array.from(backend.readSync(newShape.dataId));
|
|
const [newIndices, indicesShape, outputShape] = (0, _shared.sparseReshapeImplCPU)($inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape, targetShape);
|
|
return [
|
|
backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),
|
|
backend.makeTensorInfo([
|
|
outputShape.length
|
|
], newShape.dtype, new Int32Array(outputShape))
|
|
];
|
|
}
|
|
const sparseReshapeConfig = {
|
|
kernelName: (0, _tfjsCore.SparseReshape),
|
|
backendName: "webgl",
|
|
kernelFunc: sparseReshape
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gQmRe":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseSegmentMean", ()=>sparseSegmentMean);
|
|
parcelHelpers.export(exports, "sparseSegmentMeanConfig", ()=>sparseSegmentMeanConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function sparseSegmentMean(args) {
|
|
const { inputs, backend } = args;
|
|
const { data, indices, segmentIds } = inputs;
|
|
if (data.shape.length < 1) throw new Error(`Data should be at least 1 dimensional but received scalar`);
|
|
if (indices.shape.length !== 1) throw new Error(`Indices should be a vector but received shape
|
|
${indices.shape}`);
|
|
if (segmentIds.shape.length !== 1) throw new Error(`Segment ids should be a vector but received shape
|
|
${segmentIds.shape}`);
|
|
const $data = backend.readSync(data.dataId);
|
|
const $indices = backend.readSync(indices.dataId);
|
|
const $segmentIds = backend.readSync(segmentIds.dataId);
|
|
const [outputData, outputDataShape] = (0, _shared.sparseSegmentReductionImplCPU)($data, data.shape, data.dtype, $indices, $segmentIds, true);
|
|
return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
|
|
}
|
|
const sparseSegmentMeanConfig = {
|
|
kernelName: (0, _tfjsCore.SparseSegmentMean),
|
|
backendName: "webgl",
|
|
kernelFunc: sparseSegmentMean
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2zeh8":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseSegmentSum", ()=>sparseSegmentSum);
|
|
parcelHelpers.export(exports, "sparseSegmentSumConfig", ()=>sparseSegmentSumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function sparseSegmentSum(args) {
|
|
const { inputs, backend } = args;
|
|
const { data, indices, segmentIds } = inputs;
|
|
if (data.shape.length < 1) throw new Error(`Data should be at least 1 dimensional but received scalar`);
|
|
if (indices.shape.length !== 1) throw new Error(`Indices should be a vector but received shape
|
|
${indices.shape}`);
|
|
if (segmentIds.shape.length !== 1) throw new Error(`Segment ids should be a vector but received shape
|
|
${segmentIds.shape}`);
|
|
const $data = backend.readSync(data.dataId);
|
|
const $indices = backend.readSync(indices.dataId);
|
|
const $segmentIds = backend.readSync(segmentIds.dataId);
|
|
const [outputData, outputDataShape] = (0, _shared.sparseSegmentReductionImplCPU)($data, data.shape, data.dtype, $indices, $segmentIds);
|
|
return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
|
|
}
|
|
const sparseSegmentSumConfig = {
|
|
kernelName: (0, _tfjsCore.SparseSegmentSum),
|
|
backendName: "webgl",
|
|
kernelFunc: sparseSegmentSum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2SjVb":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseToDense", ()=>sparseToDense);
|
|
parcelHelpers.export(exports, "sparseToDenseConfig", ()=>sparseToDenseConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _scatterGpu = require("../scatter_gpu");
|
|
var _reshape = require("./Reshape");
|
|
function sparseToDense(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { sparseIndices, sparseValues, defaultValue } = inputs;
|
|
const { outputShape } = attrs;
|
|
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = (0, _tfjsCore.backend_util).calculateShapes(sparseValues, sparseIndices, outputShape);
|
|
const sumDupeIndices = false;
|
|
if (sparseValues.dtype === "string") {
|
|
const indicesBuf = backend.bufferSync(sparseIndices);
|
|
const updatesBuf = backend.bufferSync(sparseValues);
|
|
const $defaultValue = (0, _tfjsCore.util).decodeString(backend.readSync(defaultValue.dataId)[0]);
|
|
const outBuf = (0, _shared.scatterImplCPU)(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
|
|
return backend.makeTensorInfo(outputShape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const program = new (0, _scatterGpu.ScatterProgram)(numUpdates, sliceRank, sparseIndices.shape.length, sparseValues.shape.length, strides, [
|
|
outputSize,
|
|
1
|
|
], sumDupeIndices);
|
|
const res = backend.runWebGLProgram(program, [
|
|
sparseValues,
|
|
sparseIndices,
|
|
defaultValue
|
|
], sparseValues.dtype);
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: res
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outputShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(res);
|
|
return reshaped;
|
|
}
|
|
const sparseToDenseConfig = {
|
|
kernelName: (0, _tfjsCore.SparseToDense),
|
|
backendName: "webgl",
|
|
kernelFunc: sparseToDense
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../scatter_gpu":"kN25X","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6cXfl":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "splitV", ()=>splitV);
|
|
parcelHelpers.export(exports, "splitVConfig", ()=>splitVConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _slice = require("./Slice");
|
|
function splitV(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { numOrSizeSplits, axis } = attrs;
|
|
const $axis = (0, _tfjsCore.util).parseAxisParam(axis, x.shape)[0];
|
|
const splitSizes = (0, _tfjsCore.backend_util).prepareSplitSize(x, numOrSizeSplits, $axis);
|
|
const xRank = x.shape.length;
|
|
const begin = new Array(xRank).fill(0);
|
|
const size = x.shape.slice();
|
|
return splitSizes.map((s)=>{
|
|
const sliceSize = [
|
|
...size
|
|
];
|
|
sliceSize[$axis] = s;
|
|
const sliceT = (0, _slice.slice)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin,
|
|
size: sliceSize
|
|
}
|
|
});
|
|
begin[$axis] += s;
|
|
return sliceT;
|
|
});
|
|
}
|
|
const splitVConfig = {
|
|
kernelName: (0, _tfjsCore.SplitV),
|
|
backendName: "webgl",
|
|
kernelFunc: splitV
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Slice":"6jQ29","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4bT4M":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sqrt", ()=>sqrt);
|
|
parcelHelpers.export(exports, "sqrtConfig", ()=>sqrtConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
var _shared = require("../kernel_utils/shared");
|
|
const SQRT = `return sqrt(x);`;
|
|
const sqrt = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: SQRT,
|
|
packedOpSnippet: SQRT,
|
|
cpuKernelImpl: (0, _shared.sqrtImplCPU)
|
|
});
|
|
const sqrtConfig = {
|
|
kernelName: (0, _tfjsCore.Sqrt),
|
|
backendName: "webgl",
|
|
kernelFunc: sqrt
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jCuUm":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "square", ()=>square);
|
|
parcelHelpers.export(exports, "squareConfig", ()=>squareConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const SQUARE = `return x * x;`;
|
|
const square = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: SQUARE
|
|
});
|
|
const squareConfig = {
|
|
kernelName: (0, _tfjsCore.Square),
|
|
backendName: "webgl",
|
|
kernelFunc: square
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fSbIq":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "squaredDifference", ()=>squaredDifference);
|
|
parcelHelpers.export(exports, "squaredDifferenceConfig", ()=>squaredDifferenceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const SQUARED_DIFFERENCE = "return (a - b) * (a - b);";
|
|
const squaredDifference = (0, _kernelFuncsUtils.binaryKernelFunc)({
|
|
opSnippet: SQUARED_DIFFERENCE,
|
|
packedOpSnippet: SQUARED_DIFFERENCE
|
|
});
|
|
const squaredDifferenceConfig = {
|
|
kernelName: (0, _tfjsCore.SquaredDifference),
|
|
backendName: "webgl",
|
|
kernelFunc: squaredDifference
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8HWNl":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "staticRegexReplace", ()=>staticRegexReplace);
|
|
parcelHelpers.export(exports, "staticRegexReplaceConfig", ()=>staticRegexReplaceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function staticRegexReplace(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
if (x.dtype !== "string") throw new Error("Input must be of datatype string");
|
|
const $x = backend.readSync(x.dataId);
|
|
const stringInput = (0, _tfjsCore.backend_util).fromUint8ToStringArray($x);
|
|
const output = (0, _shared.staticRegexReplaceImplCPU)(stringInput, "string", attrs);
|
|
return backend.makeTensorInfo(x.shape, "string", output);
|
|
}
|
|
const staticRegexReplaceConfig = {
|
|
kernelName: (0, _tfjsCore.StaticRegexReplace),
|
|
backendName: "webgl",
|
|
kernelFunc: staticRegexReplace
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"d3n9V":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "step", ()=>step);
|
|
parcelHelpers.export(exports, "stepConfig", ()=>stepConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryopGpu = require("../unaryop_gpu");
|
|
function step({ inputs, attrs, backend }) {
|
|
const { x } = inputs;
|
|
const opSnippet = (0, _unaryopGpu.CHECK_NAN_SNIPPET) + `
|
|
return x > 0.0 ? 1.0 : float(${attrs.alpha});
|
|
`;
|
|
const program = new (0, _unaryopGpu.UnaryOpProgram)(x.shape, opSnippet);
|
|
return backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
const stepConfig = {
|
|
kernelName: (0, _tfjsCore.Step),
|
|
backendName: "webgl",
|
|
kernelFunc: step
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../unaryop_gpu":"gIMrR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"47wD9":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stridedSlice", ()=>stridedSlice);
|
|
parcelHelpers.export(exports, "stridedSliceConfig", ()=>stridedSliceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _stridedSliceGpu = require("../strided_slice_gpu");
|
|
var _reshape = require("./Reshape");
|
|
var _slice = require("./Slice");
|
|
function stridedSlice(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask } = attrs;
|
|
const { finalShapeSparse, finalShape, isIdentity, sliceDim0, isSimpleSlice, begin: $begin, end: $end, strides: $strides } = (0, _tfjsCore.slice_util).sliceInfo(x.shape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask);
|
|
let result;
|
|
if (isIdentity) // Optimization #1, slice is a no-op plus reshape
|
|
result = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: finalShape
|
|
}
|
|
});
|
|
else if (sliceDim0 || isSimpleSlice) {
|
|
// Optimization #2, slice is memory contiguous (only occurs in dim 0)
|
|
(0, _tfjsCore.util).assert(x.shape.length >= 1, ()=>`Input must have rank at least 1, got: ${x.shape.length}`);
|
|
const size = (0, _tfjsCore.slice_util).computeOutShape($begin, $end, $strides);
|
|
// To tolerate begin[0] > end[0] (a 0-output slice), we min(begin, end).
|
|
const sliced = (0, _slice.slice)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin: $begin,
|
|
size
|
|
}
|
|
});
|
|
result = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: sliced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: finalShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(sliced);
|
|
} else {
|
|
const shouldExecuteOnCPU = backend.shouldExecuteOnCPU([
|
|
x
|
|
]);
|
|
if (shouldExecuteOnCPU) {
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const values = backend.readSync(x.dataId);
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
const xBuf = (0, _tfjsCore.buffer)(x.shape, x.dtype, values);
|
|
const resultValues = (0, _shared.stridedSliceImplCPU)(finalShapeSparse, xBuf, $strides, $begin);
|
|
result = backend.makeTensorInfo(finalShape, x.dtype, resultValues.values);
|
|
} else {
|
|
const program = new (0, _stridedSliceGpu.StridedSliceProgram)($begin, $strides, finalShapeSparse);
|
|
result = backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
}
|
|
}
|
|
const resultReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: finalShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
return resultReshaped;
|
|
}
|
|
const stridedSliceConfig = {
|
|
kernelName: (0, _tfjsCore.StridedSlice),
|
|
backendName: "webgl",
|
|
kernelFunc: stridedSlice
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../strided_slice_gpu":"2eIE7","./Reshape":"fgZen","./Slice":"6jQ29","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2eIE7":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "StridedSliceProgram", ()=>StridedSliceProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class StridedSliceProgram {
|
|
constructor(begin, strides, size){
|
|
this.variableNames = [
|
|
"x"
|
|
];
|
|
this.outputShape = size;
|
|
const rank = size.length;
|
|
const inputDtype = (0, _shaderCompiler.getCoordsDataType)(size.length);
|
|
const dtype = (0, _shaderCompiler.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}));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aUZOK":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringNGrams", ()=>stringNGrams);
|
|
parcelHelpers.export(exports, "stringNGramsConfig", ()=>stringNGramsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function stringNGrams(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences } = attrs;
|
|
const { data, dataSplits } = inputs;
|
|
const $data = backend.readSync(data.dataId);
|
|
const $dataSplits = backend.readSync(dataSplits.dataId);
|
|
const [nGrams, nGramsSplits] = (0, _shared.stringNGramsImplCPU)($data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences);
|
|
return [
|
|
backend.makeTensorInfo([
|
|
nGrams.length
|
|
], "string", nGrams),
|
|
backend.makeTensorInfo(dataSplits.shape, "int32", nGramsSplits)
|
|
];
|
|
}
|
|
const stringNGramsConfig = {
|
|
kernelName: (0, _tfjsCore.StringNGrams),
|
|
backendName: "webgl",
|
|
kernelFunc: stringNGrams
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ezwh5":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringSplit", ()=>stringSplit);
|
|
parcelHelpers.export(exports, "stringSplitConfig", ()=>stringSplitConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function stringSplit(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { skipEmpty } = attrs;
|
|
const { input, delimiter } = inputs;
|
|
if (input.dtype !== "string") throw new Error("Input must be of datatype string");
|
|
if (input.shape.length !== 1) throw new Error(`Input must be a vector, got shape: ${input.shape}`);
|
|
if (delimiter.shape.length !== 0) throw new Error(`Delimiter must be a scalar, got shape: ${delimiter.shape}`);
|
|
const $input = backend.readSync(input.dataId);
|
|
const $delimiter = backend.readSync(delimiter.dataId)[0];
|
|
const [indices, values, shape] = (0, _shared.stringSplitImplCPU)($input, $delimiter, skipEmpty);
|
|
const outputSize = values.length;
|
|
return [
|
|
backend.makeTensorInfo([
|
|
outputSize,
|
|
2
|
|
], "int32", indices),
|
|
backend.makeTensorInfo([
|
|
outputSize
|
|
], "string", values),
|
|
backend.makeTensorInfo([
|
|
2
|
|
], "int32", new Int32Array(shape))
|
|
];
|
|
}
|
|
const stringSplitConfig = {
|
|
kernelName: (0, _tfjsCore.StringSplit),
|
|
backendName: "webgl",
|
|
kernelFunc: stringSplit
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b6pUo":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringToHashBucketFast", ()=>stringToHashBucketFast);
|
|
parcelHelpers.export(exports, "stringToHashBucketFastConfig", ()=>stringToHashBucketFastConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
function stringToHashBucketFast(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { numBuckets } = attrs;
|
|
const { input } = inputs;
|
|
if (input.dtype !== "string") throw new Error("Input must be of datatype string");
|
|
if (numBuckets <= 0) throw new Error(`Number of buckets must be at least 1`);
|
|
const $input = backend.readSync(input.dataId);
|
|
const output = (0, _shared.stringToHashBucketFastImplCPU)($input, numBuckets);
|
|
return backend.makeTensorInfo(input.shape, "int32", output);
|
|
}
|
|
const stringToHashBucketFastConfig = {
|
|
kernelName: (0, _tfjsCore.StringToHashBucketFast),
|
|
backendName: "webgl",
|
|
kernelFunc: stringToHashBucketFast
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2vzWF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tan", ()=>tan);
|
|
parcelHelpers.export(exports, "tanConfig", ()=>tanConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const TAN = `return tan(x);`;
|
|
const tan = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: TAN
|
|
});
|
|
const tanConfig = {
|
|
kernelName: (0, _tfjsCore.Tan),
|
|
backendName: "webgl",
|
|
kernelFunc: tan
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7BFBf":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tanh", ()=>tanh);
|
|
parcelHelpers.export(exports, "tanhConfig", ()=>tanhConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _kernelFuncsUtils = require("../kernel_utils/kernel_funcs_utils");
|
|
const TANH = `
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`;
|
|
const tanh = (0, _kernelFuncsUtils.unaryKernelFunc)({
|
|
opSnippet: TANH
|
|
});
|
|
const tanhConfig = {
|
|
kernelName: (0, _tfjsCore.Tanh),
|
|
backendName: "webgl",
|
|
kernelFunc: tanh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/kernel_funcs_utils":"grPtN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2uPVJ":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tensorScatterUpdate", ()=>tensorScatterUpdate);
|
|
parcelHelpers.export(exports, "tensorScatterUpdateConfig", ()=>tensorScatterUpdateConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _scatterGpu = require("../scatter_gpu");
|
|
var _reshape = require("./Reshape");
|
|
function tensorScatterUpdate(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { tensor, indices, updates } = inputs;
|
|
const {} = attrs;
|
|
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = (0, _tfjsCore.backend_util).calculateShapes(updates, indices, tensor.shape);
|
|
const flattenShape = [
|
|
outputSize / sliceSize,
|
|
sliceSize
|
|
];
|
|
if (outputSize === 0) return backend.makeTensorInfo(tensor.shape, indices.dtype);
|
|
const flattenIndices = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: indices
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
numUpdates,
|
|
sliceRank
|
|
]
|
|
}
|
|
});
|
|
const flattenX = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: updates
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
numUpdates,
|
|
sliceSize
|
|
]
|
|
}
|
|
});
|
|
const flattenTensor = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: tensor
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: flattenShape
|
|
}
|
|
});
|
|
const program = new (0, _scatterGpu.ScatterProgram)(numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length, strides, flattenShape, false, true);
|
|
const res = backend.runWebGLProgram(program, [
|
|
flattenX,
|
|
flattenIndices,
|
|
flattenTensor
|
|
], flattenTensor.dtype);
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: res
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: tensor.shape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(flattenIndices);
|
|
backend.disposeIntermediateTensorInfo(flattenX);
|
|
backend.disposeIntermediateTensorInfo(flattenTensor);
|
|
backend.disposeIntermediateTensorInfo(res);
|
|
return reshaped;
|
|
}
|
|
const tensorScatterUpdateConfig = {
|
|
kernelName: (0, _tfjsCore.TensorScatterUpdate),
|
|
backendName: "webgl",
|
|
kernelFunc: tensorScatterUpdate
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../scatter_gpu":"kN25X","./Reshape":"fgZen","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dbDLN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tile", ()=>tile);
|
|
parcelHelpers.export(exports, "tileConfig", ()=>tileConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _tileGpu = require("../tile_gpu");
|
|
function tile(params) {
|
|
const { inputs, backend, attrs } = params;
|
|
const { x } = inputs;
|
|
const { reps } = attrs;
|
|
// tile gpu program cannot handle rank > 5 case.
|
|
if (x.dtype === "string" || x.shape.length > 5) {
|
|
// Even thought string tensor is always on CPU, just to be consistent on how
|
|
// to access tensor data.
|
|
const data = backend.readSync(x.dataId);
|
|
const value = x.dtype === "string" ? data.map((d)=>(0, _tfjsCore.util).decodeString(d)) : data;
|
|
const buf = (0, _tfjsCore.buffer)(x.shape, x.dtype, value);
|
|
const outBuf = (0, _shared.tileImplCPU)(buf, reps);
|
|
return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const program = new (0, _tileGpu.TileProgram)(x.shape, reps);
|
|
const output = backend.runWebGLProgram(program, [
|
|
x
|
|
], x.dtype);
|
|
return output;
|
|
}
|
|
const tileConfig = {
|
|
kernelName: (0, _tfjsCore.Tile),
|
|
backendName: "webgl",
|
|
kernelFunc: tile
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../tile_gpu":"kUfPd","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kUfPd":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2017 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "TileProgram", ()=>TileProgram);
|
|
var _shaderCompiler = require("./shader_compiler");
|
|
class 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 = (0, _shaderCompiler.getCoordsDataType)(this.rank);
|
|
const sourceCoords = getSourceCoords(aShape);
|
|
this.userCode = `
|
|
void main() {
|
|
${dtype} resRC = getOutputCoords();
|
|
setOutput(getA(${sourceCoords}));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
function 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();
|
|
}
|
|
|
|
},{"./shader_compiler":"5uusa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gvorh":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
// Based on Algorithm 2 of Bitonic Top K, ref:
|
|
// https://anilshanbhag.in/static/papers/gputopk_sigmod18.pdf
|
|
parcelHelpers.export(exports, "topK", ()=>topK);
|
|
parcelHelpers.export(exports, "topKConfig", ()=>topKConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _topKGpu = require("../top_k_gpu");
|
|
var _fill = require("./Fill");
|
|
var _gatherV2 = require("./GatherV2");
|
|
var _reshape = require("./Reshape");
|
|
var _slice = require("./Slice");
|
|
function disposeIntermediateTensorInfoOrNull(backend, tensorInfo) {
|
|
if (tensorInfo !== null) backend.disposeIntermediateTensorInfo(tensorInfo);
|
|
}
|
|
function roundUpToPow2(num) {
|
|
let pow2 = 1;
|
|
while(pow2 < num)pow2 *= 2;
|
|
return pow2;
|
|
}
|
|
function topK(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { k, sorted } = attrs;
|
|
// Empirically determined constant used to determine last dim threshold for
|
|
// handing off execution to the CPU.
|
|
const TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD = (0, _tfjsCore.env)().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD");
|
|
// Empirically determined constant used to determine k threshold for handing
|
|
// off execution to the CPU.
|
|
const TOPK_K_CPU_HANDOFF_THRESHOLD = (0, _tfjsCore.env)().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD");
|
|
const xShape = x.shape;
|
|
const lastDim = xShape[xShape.length - 1];
|
|
if (backend.shouldExecuteOnCPU([
|
|
x
|
|
]) || lastDim < TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD || k > TOPK_K_CPU_HANDOFF_THRESHOLD) {
|
|
const xVals = backend.readSync(x.dataId);
|
|
const [allTopKVals, allTopKIndices] = (0, _shared.topKImplCPU)(xVals, xShape, x.dtype, k, sorted);
|
|
return [
|
|
backend.makeTensorInfo(allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),
|
|
backend.makeTensorInfo(allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)
|
|
];
|
|
}
|
|
if (k === 0) {
|
|
xShape[xShape.length - 1] = 0;
|
|
return [
|
|
backend.makeTensorInfo(xShape, x.dtype, []),
|
|
backend.makeTensorInfo(xShape, "int32", [])
|
|
];
|
|
}
|
|
if (lastDim === 1 /* firstPass */ ) return [
|
|
x,
|
|
(0, _fill.fill)({
|
|
attrs: {
|
|
shape: xShape,
|
|
dtype: "int32",
|
|
value: 0
|
|
},
|
|
backend
|
|
})
|
|
];
|
|
// Eagerly unpack x input since it is passed in to all the shaders which
|
|
// require unpacked inputs.
|
|
const xtexData = backend.texData.get(x.dataId);
|
|
const xIsPacked = xtexData !== null && xtexData.isPacked;
|
|
const xUnPacked = xIsPacked ? backend.unpackTensor(x) : x;
|
|
// Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(xShape);
|
|
const batch = xSize / lastDim;
|
|
const x2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: xUnPacked
|
|
},
|
|
attrs: {
|
|
shape: [
|
|
batch,
|
|
lastDim
|
|
]
|
|
},
|
|
backend
|
|
});
|
|
if (xIsPacked) disposeIntermediateTensorInfoOrNull(backend, xUnPacked);
|
|
const kPow2 = roundUpToPow2(k);
|
|
const lastDimPow2 = roundUpToPow2(lastDim);
|
|
// Only the indices containing the top K are kept at every step to reduce
|
|
// number of outputs in the GPU algorithms, so once the final set of indices
|
|
// is computed then gather is used to grab the corresponding values
|
|
// from the original input.
|
|
let indices = null;
|
|
// GPU algorithm always takes in an indices input but this input is not used
|
|
// on the first run of a GPU algorithm, therefore if indices is null we simply
|
|
// pass in x2D instead of it but the value will not actually be used
|
|
const getInputs = ()=>indices === null ? [
|
|
x2D,
|
|
x2D
|
|
] : [
|
|
x2D,
|
|
indices
|
|
];
|
|
const runSwap = (dir, inc, shape)=>{
|
|
const inputs = getInputs();
|
|
const program = new (0, _topKGpu.SwapProgram)(shape);
|
|
const fistPass = indices === null ? 1 : 0;
|
|
const customValues = [
|
|
[
|
|
lastDim
|
|
],
|
|
[
|
|
fistPass
|
|
],
|
|
[
|
|
Number.NEGATIVE_INFINITY
|
|
],
|
|
[
|
|
dir
|
|
],
|
|
[
|
|
inc
|
|
]
|
|
];
|
|
const prevIndices = indices;
|
|
indices = backend.runWebGLProgram(program, inputs, "int32", customValues);
|
|
disposeIntermediateTensorInfoOrNull(backend, prevIndices);
|
|
};
|
|
// Step 1: local sort
|
|
for(let len = 1; len < kPow2; len *= 2){
|
|
const dir = len * 2;
|
|
for(let inc = len; inc >= 1; inc /= 2)runSwap(dir, inc, [
|
|
batch,
|
|
lastDimPow2
|
|
]);
|
|
}
|
|
// Step 2: merge
|
|
for(let indicesSize = lastDimPow2; indicesSize > kPow2; indicesSize /= 2){
|
|
const inputs = getInputs();
|
|
const mergeProgram = new (0, _topKGpu.MergeProgram)([
|
|
batch,
|
|
indicesSize / 2
|
|
]);
|
|
const firstPass = indices === null ? 1 : 0;
|
|
const customValues = [
|
|
[
|
|
lastDim
|
|
],
|
|
[
|
|
firstPass
|
|
],
|
|
[
|
|
kPow2
|
|
]
|
|
];
|
|
const prevIndices = indices;
|
|
indices = backend.runWebGLProgram(mergeProgram, inputs, "int32", customValues);
|
|
disposeIntermediateTensorInfoOrNull(backend, prevIndices);
|
|
// Step 3: rebuild
|
|
const len = kPow2 / 2;
|
|
const dir = len * 2;
|
|
for(let inc = len; inc >= 1; inc /= 2)runSwap(dir, inc, indices.shape);
|
|
}
|
|
// Keep only the requested top K results instead of kPow2
|
|
let prevIndices = indices;
|
|
indices = (0, _slice.slice)({
|
|
inputs: {
|
|
x: indices
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin: 0,
|
|
size: [
|
|
batch,
|
|
k
|
|
]
|
|
}
|
|
});
|
|
disposeIntermediateTensorInfoOrNull(backend, prevIndices);
|
|
// Gather values on last dimension
|
|
let values = (0, _gatherV2.gatherV2)({
|
|
inputs: {
|
|
x: x2D,
|
|
indices
|
|
},
|
|
backend,
|
|
attrs: {
|
|
axis: 1,
|
|
batchDims: 1
|
|
}
|
|
});
|
|
disposeIntermediateTensorInfoOrNull(backend, x2D);
|
|
// Reshape back to the original input shape, except that the last
|
|
// dimension is k.
|
|
const newShape = xShape.slice(0, -1);
|
|
newShape.push(k);
|
|
prevIndices = indices;
|
|
indices = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: indices
|
|
},
|
|
attrs: {
|
|
shape: newShape
|
|
},
|
|
backend
|
|
});
|
|
disposeIntermediateTensorInfoOrNull(backend, prevIndices);
|
|
const prevValues = values;
|
|
values = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: values
|
|
},
|
|
attrs: {
|
|
shape: newShape
|
|
},
|
|
backend
|
|
});
|
|
disposeIntermediateTensorInfoOrNull(backend, prevValues);
|
|
return [
|
|
values,
|
|
indices
|
|
];
|
|
}
|
|
const topKConfig = {
|
|
kernelName: (0, _tfjsCore.TopK),
|
|
backendName: "webgl",
|
|
kernelFunc: topK
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../top_k_gpu":"fpm4p","./Fill":"6Rawr","./GatherV2":"cBFXe","./Reshape":"fgZen","./Slice":"6jQ29","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fpm4p":[function(require,module,exports) {
|
|
// Based on Algorithm 2 of Bitonic Top K, ref:
|
|
// https://anilshanbhag.in/static/papers/gputopk_sigmod18.pdf
|
|
// The original algorithm is based on computing the top K only, however
|
|
// since for TFJS we require the indices of the top K values as well then the
|
|
// algorithm found here is a bit modified. Rather than producing the values
|
|
// at each step, the indices containing the top K are generated instead.
|
|
// The output values are not generated to reduce the number of outputs in the
|
|
// GPU, the values can easily be retrieved from the indices using a gather
|
|
// op.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "SwapProgram", ()=>SwapProgram);
|
|
parcelHelpers.export(exports, "MergeProgram", ()=>MergeProgram);
|
|
class SwapProgram {
|
|
/**
|
|
* @param shape desired output shape (can be larger than input shape, output
|
|
* will be padded with -Infinity)
|
|
*/ constructor(shape){
|
|
this.variableNames = [
|
|
"x",
|
|
"indices"
|
|
];
|
|
// |n| Size of the original input of TopK.
|
|
// |firstPass|indicates if this is the first time swap is being used which
|
|
// means no indices input containing the top K is present yet.
|
|
// |inc| Swaps pairs of indices (0, inc), (1, inc + 1), (2, inc + 2) ...
|
|
this.customUniforms = [
|
|
{
|
|
name: "n",
|
|
type: "int"
|
|
},
|
|
{
|
|
name: "firstPass",
|
|
type: "int"
|
|
},
|
|
{
|
|
name: "negativeInf",
|
|
type: "float"
|
|
},
|
|
{
|
|
name: "dir",
|
|
type: "int"
|
|
},
|
|
{
|
|
name: "inc",
|
|
type: "int"
|
|
}
|
|
];
|
|
this.outputShape = shape;
|
|
this.userCode = `
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int elemIdx = coords[1];
|
|
|
|
// We compare elements pair-wise within a group of size 2 * inc.
|
|
// The comparing rule for each group alternates between ascending
|
|
// and descending. Within each group, we compare each pair at
|
|
// positions i and i+inc. To decide whether an element at position i
|
|
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
|
|
// inc, it is in the first half of the group, we denote it as x0,
|
|
// otherwise we denote it as x1.
|
|
// For example, as shown in the Bitonic top K paper referenced above,
|
|
// Figure5(a) shows that element[1] is in the
|
|
// second half of the group when group size is 2, but it is in the
|
|
// first half of the group when group size is 4.
|
|
|
|
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
|
|
int i = isFirstInPair ? elemIdx : elemIdx - inc;
|
|
|
|
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
|
|
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
|
|
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
|
|
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
|
|
|
|
// Denotes which direction indices are in (ascending or descending).
|
|
bool reverse = imod(elemIdx, 2 * dir) >= dir;
|
|
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
|
|
if (reverse == isGreater) { // Elements in opposite order of direction
|
|
int iTemp = i0;
|
|
i0 = i1;
|
|
i1 = iTemp;
|
|
}
|
|
if (isFirstInPair) {
|
|
setOutput(float(i0));
|
|
} else {
|
|
setOutput(float(i1));
|
|
}
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
class MergeProgram {
|
|
/**
|
|
* @param shape desired output shape (must be half of the input size)
|
|
*/ constructor(shape){
|
|
this.variableNames = [
|
|
"x",
|
|
"indices"
|
|
];
|
|
// |n| Size of the original input of TopK
|
|
// |firstPass| indicates if this is the first time swap is being used which
|
|
// means no indices input containing the top K is present yet.
|
|
// |k| Top k elements desired
|
|
this.customUniforms = [
|
|
{
|
|
name: "n",
|
|
type: "int"
|
|
},
|
|
{
|
|
name: "firstPass",
|
|
type: "int"
|
|
},
|
|
{
|
|
name: "k",
|
|
type: "int"
|
|
}
|
|
];
|
|
this.outputShape = shape;
|
|
this.userCode = `
|
|
void main() {
|
|
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int elemIdx = coords[1];
|
|
|
|
// The output size is half of the previous size.
|
|
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
|
|
// we only need to output the indices at positions |, the indices at
|
|
// positions _ can be thrown away, see Figure5(b) After Phase 2
|
|
// (Merge phase) in the Bitonic Top K paper referenced above.
|
|
// For example, the paper shows we only need to output the orange bars.
|
|
// The output sequence should look like this | | | | | | | |.
|
|
// Because the sequence is halved, to map the output index back
|
|
// to the previous sequence to find the corresponding value,
|
|
// we need to double the index. When we double the index,
|
|
// we basically interpolate a position, so 2i looks like
|
|
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
|
|
// of each 2k positions by - elemIdx % k. E.g. for output at
|
|
// index 4,5,6,7, we want to get the corresponding element at
|
|
// original index 8,9,10,11, for output at index 8,9,10,11,
|
|
// we want to get the corresponding element at original index
|
|
// 16,17,18,19, so on and so forth.
|
|
|
|
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
|
|
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
|
|
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
|
|
|
|
float x0 = getX(batch, i0);
|
|
float x1 = i1 < n ? getX(batch, i1) : x0;
|
|
|
|
setOutput(x0 >= x1 ? float(i0) : float(i1));
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4cCvF":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "transform", ()=>transform);
|
|
parcelHelpers.export(exports, "transformConfig", ()=>transformConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _transformGpu = require("../transform_gpu");
|
|
function transform(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { image, transforms } = inputs;
|
|
const { interpolation, fillMode, fillValue, outputShape } = attrs;
|
|
const [batch, imageHeight, imageWidth, numChannels] = image.shape;
|
|
const [outHeight, outWidth] = outputShape != null ? outputShape : [
|
|
imageHeight,
|
|
imageWidth
|
|
];
|
|
const outShape = [
|
|
batch,
|
|
outHeight,
|
|
outWidth,
|
|
numChannels
|
|
];
|
|
const program = new (0, _transformGpu.TransformProgram)(imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape);
|
|
return backend.runWebGLProgram(program, [
|
|
image,
|
|
transforms
|
|
], "float32");
|
|
}
|
|
const transformConfig = {
|
|
kernelName: (0, _tfjsCore.Transform),
|
|
backendName: "webgl",
|
|
kernelFunc: transform
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../transform_gpu":"1WaA8","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1WaA8":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "TransformProgram", ()=>TransformProgram);
|
|
class TransformProgram {
|
|
constructor(imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape){
|
|
this.variableNames = [
|
|
"Image",
|
|
"Transforms"
|
|
];
|
|
this.outputShape = outShape;
|
|
const interpolationModeId = interpolation === "nearest" ? 1 : 2;
|
|
let fillModeId;
|
|
switch(fillMode){
|
|
case "constant":
|
|
fillModeId = 1;
|
|
break;
|
|
case "reflect":
|
|
fillModeId = 2;
|
|
break;
|
|
case "wrap":
|
|
fillModeId = 3;
|
|
break;
|
|
case "nearest":
|
|
fillModeId = 4;
|
|
break;
|
|
default:
|
|
fillModeId = 1;
|
|
break;
|
|
}
|
|
this.userCode = `
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${fillModeId} == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
inCoord -= sz2 * float(int(float(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${fillModeId} == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord -= len * float(int(float(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${fillModeId} == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
} else {
|
|
return outCoord;
|
|
}
|
|
}
|
|
|
|
float readWithFillValue(int batch, int coordY, int coordX,
|
|
int channel) {
|
|
float outputValue;
|
|
if (0 <= coordY && coordY < ${imageHeight} && 0 <= coordX && coordX < ${imageWidth}) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = float(${fillValue});
|
|
}
|
|
return outputValue;
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
float outputValue;
|
|
int batch = coords[0];
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
int channel = coords[3];
|
|
float xf = float(x);
|
|
float yf = float(y);
|
|
float a1 = getTransforms(batch, 0);
|
|
float a2 = getTransforms(batch, 1);
|
|
float a3 = getTransforms(batch, 2);
|
|
float b1 = getTransforms(batch, 3);
|
|
float b2 = getTransforms(batch, 4);
|
|
float b3 = getTransforms(batch, 5);
|
|
float c1 = getTransforms(batch, 6);
|
|
float c2 = getTransforms(batch, 7);
|
|
float projection = c1 * xf + c2 * yf + 1.0;
|
|
if (projection == 0.0) {
|
|
outputValue = float(${fillValue});
|
|
} else {
|
|
float inX = (a1 * xf + a2 * yf + a3) / projection;
|
|
float inY = (b1 * xf + b2 * yf + b3) / projection;
|
|
float mapX = mapCoord(inX, float(${imageWidth}));
|
|
float mapY = mapCoord(inY, float(${imageHeight}));
|
|
|
|
if (${interpolationModeId} == 1) {
|
|
int coordY = int(round(mapY));
|
|
int coordX = int(round(mapX));
|
|
outputValue = readWithFillValue(batch, coordY, coordX,
|
|
channel);
|
|
} else {
|
|
float yFloor = floor(mapY);
|
|
float xFloor = floor(mapX);
|
|
float yCeil = yFloor + 1.0;
|
|
float xCeil = xFloor + 1.0;
|
|
float valueYFloor = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
|
|
float valueYCeil = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
|
|
outputValue = (yCeil - mapY) * valueYFloor +
|
|
(mapY - yFloor) * valueYCeil;
|
|
}
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"e7lqL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unique", ()=>unique);
|
|
parcelHelpers.export(exports, "uniqueConfig", ()=>uniqueConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _shared = require("../kernel_utils/shared");
|
|
var _webglUtil = require("../webgl_util");
|
|
function unique(args) {
|
|
const { inputs, attrs, backend } = args;
|
|
const { axis } = attrs;
|
|
const { x } = inputs;
|
|
(0, _webglUtil.assertNotComplex)(x, "unique");
|
|
// For now, always forward calculation to the CPU backend.
|
|
console.warn("WARNING: ", "UI might be locked temporarily as data is being downloaded");
|
|
const values = backend.readSync(x.dataId);
|
|
const { outputValues, outputShape, indices } = (0, _shared.uniqueImplCPU)(values, axis, x.shape, x.dtype);
|
|
return [
|
|
backend.makeTensorInfo(outputShape, x.dtype, outputValues),
|
|
backend.makeTensorInfo([
|
|
indices.length
|
|
], "int32", indices)
|
|
];
|
|
}
|
|
const uniqueConfig = {
|
|
kernelName: (0, _tfjsCore.Unique),
|
|
backendName: "webgl",
|
|
kernelFunc: unique
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernel_utils/shared":"e4M7v","../webgl_util":"fjf7t","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5jnF3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unpack", ()=>unpack);
|
|
parcelHelpers.export(exports, "unpackConfig", ()=>unpackConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reshape = require("./Reshape");
|
|
var _slice = require("./Slice");
|
|
function unpack(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { value } = inputs;
|
|
let { axis } = attrs;
|
|
if (axis < 0) axis += value.shape.length;
|
|
const x = value;
|
|
const xRank = x.shape.length;
|
|
const num = value.shape[axis];
|
|
const outShape = new Array(xRank - 1);
|
|
let outIndex = 0;
|
|
for(let i = 0; i < xRank; i++)if (i !== axis) outShape[outIndex++] = x.shape[i];
|
|
const toDispose = [];
|
|
const begin = new Array(xRank).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;
|
|
const sliced = (0, _slice.slice)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin,
|
|
size
|
|
}
|
|
});
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: sliced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
res[i] = reshaped;
|
|
toDispose.push(sliced);
|
|
}
|
|
toDispose.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return res;
|
|
}
|
|
const unpackConfig = {
|
|
kernelName: (0, _tfjsCore.Unpack),
|
|
backendName: "webgl",
|
|
kernelFunc: unpack
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Reshape":"fgZen","./Slice":"6jQ29","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"vnA1C":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unsortedSegmentSum", ()=>unsortedSegmentSum);
|
|
parcelHelpers.export(exports, "unsortedSegmentSumConfig", ()=>unsortedSegmentSumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _segmentGpu = require("../segment_gpu");
|
|
var _range = require("./Range");
|
|
var _reshape = require("./Reshape");
|
|
var _tile = require("./Tile");
|
|
var _transpose = require("./Transpose");
|
|
function unsortedSegmentSum(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, segmentIds } = inputs;
|
|
const { numSegments } = attrs;
|
|
const xRank = x.shape.length;
|
|
const toDispose = [];
|
|
let axis = 0;
|
|
const permutation = (0, _tfjsCore.backend_util).getAxesPermutation([
|
|
axis
|
|
], xRank);
|
|
let permutedX = x;
|
|
if (permutation != null) {
|
|
permutedX = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutation
|
|
}
|
|
});
|
|
toDispose.push(permutedX);
|
|
axis = (0, _tfjsCore.backend_util).getInnerMostAxes(1, xRank)[0];
|
|
}
|
|
const outShape = (0, _tfjsCore.backend_util).segment_util.computeOutShape(permutedX.shape, axis, numSegments);
|
|
const inSize = (0, _tfjsCore.util).sizeFromShape([
|
|
permutedX.shape[axis]
|
|
]);
|
|
const a2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: permutedX
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
-1,
|
|
inSize
|
|
]
|
|
}
|
|
});
|
|
toDispose.push(a2D);
|
|
const outputDType = (0, _tfjsCore.sumOutType)(x.dtype);
|
|
const segOpCompute = (x, segOpType, segmentIds, dtype, numSegments)=>{
|
|
const batchSize = x.shape[0];
|
|
const inSize = x.shape[1];
|
|
const windowSize = (0, _tfjsCore.backend_util).segment_util.segOpComputeOptimalWindowSize(inSize, numSegments);
|
|
const segOpInfo = {
|
|
windowSize,
|
|
inSize,
|
|
batchSize,
|
|
numSegments
|
|
};
|
|
const program = new (0, _segmentGpu.SegmentOpProgram)(segOpInfo, segOpType);
|
|
const output = backend.compileAndRun(program, [
|
|
x,
|
|
segmentIds
|
|
], dtype);
|
|
toDispose.push(output);
|
|
// No need to run another GPGPU program.
|
|
if (output.shape[1] === numSegments) return output;
|
|
const rangeInfo = (0, _range.range)({
|
|
backend,
|
|
attrs: {
|
|
start: 0,
|
|
stop: numSegments,
|
|
step: 1,
|
|
dtype: "float32"
|
|
}
|
|
});
|
|
const tileInfo = (0, _tile.tile)({
|
|
inputs: {
|
|
x: rangeInfo
|
|
},
|
|
backend,
|
|
attrs: {
|
|
reps: [
|
|
inSize / windowSize
|
|
]
|
|
}
|
|
});
|
|
toDispose.push(rangeInfo);
|
|
toDispose.push(tileInfo);
|
|
const result = segOpCompute(output, segOpType, tileInfo, dtype, numSegments);
|
|
return result;
|
|
};
|
|
const segOpResult = segOpCompute(a2D, "unsortedSegmentSum", segmentIds, outputDType, numSegments);
|
|
const reshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: segOpResult
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
let result = reshaped;
|
|
if (permutation != null) {
|
|
toDispose.push(reshaped);
|
|
const perm = (0, _tfjsCore.backend_util).getUndoAxesPermutation(permutation);
|
|
result = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm
|
|
}
|
|
});
|
|
}
|
|
toDispose.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return result;
|
|
}
|
|
const unsortedSegmentSumConfig = {
|
|
kernelName: (0, _tfjsCore.UnsortedSegmentSum),
|
|
backendName: "webgl",
|
|
kernelFunc: unsortedSegmentSum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../segment_gpu":"57Kv1","./Range":"4ulNZ","./Reshape":"fgZen","./Tile":"dbDLN","./Transpose":"cKJAC","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"57Kv1":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "SegmentOpProgram", ()=>SegmentOpProgram);
|
|
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});
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5k877":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "SupportedModels", ()=>Se);
|
|
parcelHelpers.export(exports, "blurBodyPart", ()=>$e);
|
|
parcelHelpers.export(exports, "bodyPixMaskValueToRainbowColor", ()=>U);
|
|
parcelHelpers.export(exports, "createSegmenter", ()=>ke);
|
|
parcelHelpers.export(exports, "drawBokehEffect", ()=>Ye);
|
|
parcelHelpers.export(exports, "drawMask", ()=>Ne);
|
|
parcelHelpers.export(exports, "drawPixelatedMask", ()=>Qe);
|
|
parcelHelpers.export(exports, "toBinaryMask", ()=>Ue);
|
|
parcelHelpers.export(exports, "toColoredMask", ()=>qe);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _tfjsConverter = require("@tensorflow/tfjs-converter");
|
|
var _selfieSegmentation = require("@mediapipe/selfie_segmentation");
|
|
var R = function(t, e) {
|
|
return R = Object.setPrototypeOf || ({
|
|
__proto__: []
|
|
}) instanceof Array && function(t, e) {
|
|
t.__proto__ = e;
|
|
} || function(t, e) {
|
|
for(var n in e)e.hasOwnProperty(n) && (t[n] = e[n]);
|
|
}, R(t, e);
|
|
};
|
|
function F(t, e) {
|
|
function n() {
|
|
this.constructor = t;
|
|
}
|
|
R(t, e), t.prototype = null === e ? Object.create(e) : (n.prototype = e.prototype, new n);
|
|
}
|
|
var C = function() {
|
|
return C = Object.assign || function(t) {
|
|
for(var e, n = 1, r = arguments.length; n < r; n++)for(var i in e = arguments[n])Object.prototype.hasOwnProperty.call(e, i) && (t[i] = e[i]);
|
|
return t;
|
|
}, C.apply(this, arguments);
|
|
};
|
|
function D(t, e, n, r) {
|
|
return new (n || (n = Promise))(function(i, o) {
|
|
function a(t) {
|
|
try {
|
|
u(r.next(t));
|
|
} catch (t) {
|
|
o(t);
|
|
}
|
|
}
|
|
function s(t) {
|
|
try {
|
|
u(r.throw(t));
|
|
} catch (t) {
|
|
o(t);
|
|
}
|
|
}
|
|
function u(t) {
|
|
var e;
|
|
t.done ? i(t.value) : (e = t.value, e instanceof n ? e : new n(function(t) {
|
|
t(e);
|
|
})).then(a, s);
|
|
}
|
|
u((r = r.apply(t, e || [])).next());
|
|
});
|
|
}
|
|
function B(t, e) {
|
|
var n, r, i, o, a = {
|
|
label: 0,
|
|
sent: function() {
|
|
if (1 & i[0]) throw i[1];
|
|
return i[1];
|
|
},
|
|
trys: [],
|
|
ops: []
|
|
};
|
|
return o = {
|
|
next: s(0),
|
|
throw: s(1),
|
|
return: s(2)
|
|
}, "function" == typeof Symbol && (o[Symbol.iterator] = function() {
|
|
return this;
|
|
}), o;
|
|
function s(o) {
|
|
return function(s) {
|
|
return function(o) {
|
|
if (n) throw new TypeError("Generator is already executing.");
|
|
for(; a;)try {
|
|
if (n = 1, r && (i = 2 & o[0] ? r.return : o[0] ? r.throw || ((i = r.return) && i.call(r), 0) : r.next) && !(i = i.call(r, o[1])).done) return i;
|
|
switch(r = 0, i && (o = [
|
|
2 & o[0],
|
|
i.value
|
|
]), o[0]){
|
|
case 0:
|
|
case 1:
|
|
i = o;
|
|
break;
|
|
case 4:
|
|
return a.label++, {
|
|
value: o[1],
|
|
done: !1
|
|
};
|
|
case 5:
|
|
a.label++, r = o[1], o = [
|
|
0
|
|
];
|
|
continue;
|
|
case 7:
|
|
o = a.ops.pop(), a.trys.pop();
|
|
continue;
|
|
default:
|
|
if (!(i = a.trys, (i = i.length > 0 && i[i.length - 1]) || 6 !== o[0] && 2 !== o[0])) {
|
|
a = 0;
|
|
continue;
|
|
}
|
|
if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
|
|
a.label = o[1];
|
|
break;
|
|
}
|
|
if (6 === o[0] && a.label < i[1]) {
|
|
a.label = i[1], i = o;
|
|
break;
|
|
}
|
|
if (i && a.label < i[2]) {
|
|
a.label = i[2], a.ops.push(o);
|
|
break;
|
|
}
|
|
i[2] && a.ops.pop(), a.trys.pop();
|
|
continue;
|
|
}
|
|
o = e.call(t, a);
|
|
} catch (t) {
|
|
o = [
|
|
6,
|
|
t
|
|
], r = 0;
|
|
} finally{
|
|
n = i = 0;
|
|
}
|
|
if (5 & o[0]) throw o[1];
|
|
return {
|
|
value: o[0] ? o[1] : void 0,
|
|
done: !0
|
|
};
|
|
}([
|
|
o,
|
|
s
|
|
]);
|
|
};
|
|
}
|
|
}
|
|
function L(t) {
|
|
return t instanceof SVGAnimatedLength ? t.baseVal.value : t;
|
|
}
|
|
function z(t) {
|
|
return D(this, void 0, void 0, function() {
|
|
var r, i;
|
|
return B(this, function(o) {
|
|
switch(o.label){
|
|
case 0:
|
|
return r = document.createElement("canvas"), t instanceof (0, _tfjsCore.Tensor) ? [
|
|
4,
|
|
(0, _tfjsCore.browser).toPixels(t, r)
|
|
] : [
|
|
3,
|
|
2
|
|
];
|
|
case 1:
|
|
return o.sent(), [
|
|
3,
|
|
3
|
|
];
|
|
case 2:
|
|
r.width = L(t.width), r.height = L(t.height), i = r.getContext("2d"), t instanceof ImageData ? i.putImageData(t, 0, 0) : i.drawImage(t, 0, 0), o.label = 3;
|
|
case 3:
|
|
return [
|
|
2,
|
|
r
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function W(t) {
|
|
return D(this, void 0, void 0, function() {
|
|
var r, i, o, a, s, u;
|
|
return B(this, function(f) {
|
|
switch(f.label){
|
|
case 0:
|
|
return t instanceof (0, _tfjsCore.Tensor) ? (r = t.shape.slice(0, 2), i = r[0], o = r[1], a = ImageData.bind, [
|
|
4,
|
|
(0, _tfjsCore.browser).toPixels(t)
|
|
]) : [
|
|
3,
|
|
2
|
|
];
|
|
case 1:
|
|
return [
|
|
2,
|
|
new (a.apply(ImageData, [
|
|
void 0,
|
|
f.sent(),
|
|
o,
|
|
i
|
|
]))
|
|
];
|
|
case 2:
|
|
return s = document.createElement("canvas"), u = s.getContext("2d"), s.width = L(t.width), s.height = L(t.height), u.drawImage(t, 0, 0), [
|
|
2,
|
|
u.getImageData(0, 0, s.width, s.height)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function j(t) {
|
|
return D(this, void 0, void 0, function() {
|
|
var e, r;
|
|
return B(this, function(i) {
|
|
switch(i.label){
|
|
case 0:
|
|
return t instanceof SVGImageElement || t instanceof OffscreenCanvas ? [
|
|
4,
|
|
z(t)
|
|
] : [
|
|
3,
|
|
2
|
|
];
|
|
case 1:
|
|
return r = i.sent(), [
|
|
3,
|
|
3
|
|
];
|
|
case 2:
|
|
r = t, i.label = 3;
|
|
case 3:
|
|
return e = r, [
|
|
2,
|
|
(0, _tfjsCore.browser).fromPixels(e, 4)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function V(t) {
|
|
if (t < 0 || t >= 256) throw new Error("Mask value must be in range [0, 255] but got " + t);
|
|
if (!Number.isInteger(t)) throw new Error("Mask value must be an integer but got " + t);
|
|
}
|
|
var K = [
|
|
[
|
|
110,
|
|
64,
|
|
170
|
|
],
|
|
[
|
|
143,
|
|
61,
|
|
178
|
|
],
|
|
[
|
|
178,
|
|
60,
|
|
178
|
|
],
|
|
[
|
|
210,
|
|
62,
|
|
167
|
|
],
|
|
[
|
|
238,
|
|
67,
|
|
149
|
|
],
|
|
[
|
|
255,
|
|
78,
|
|
125
|
|
],
|
|
[
|
|
255,
|
|
94,
|
|
99
|
|
],
|
|
[
|
|
255,
|
|
115,
|
|
75
|
|
],
|
|
[
|
|
255,
|
|
140,
|
|
56
|
|
],
|
|
[
|
|
239,
|
|
167,
|
|
47
|
|
],
|
|
[
|
|
217,
|
|
194,
|
|
49
|
|
],
|
|
[
|
|
194,
|
|
219,
|
|
64
|
|
],
|
|
[
|
|
175,
|
|
240,
|
|
91
|
|
],
|
|
[
|
|
135,
|
|
245,
|
|
87
|
|
],
|
|
[
|
|
96,
|
|
247,
|
|
96
|
|
],
|
|
[
|
|
64,
|
|
243,
|
|
115
|
|
],
|
|
[
|
|
40,
|
|
234,
|
|
141
|
|
],
|
|
[
|
|
28,
|
|
219,
|
|
169
|
|
],
|
|
[
|
|
26,
|
|
199,
|
|
194
|
|
],
|
|
[
|
|
33,
|
|
176,
|
|
213
|
|
],
|
|
[
|
|
47,
|
|
150,
|
|
224
|
|
],
|
|
[
|
|
65,
|
|
125,
|
|
224
|
|
],
|
|
[
|
|
84,
|
|
101,
|
|
214
|
|
],
|
|
[
|
|
99,
|
|
81,
|
|
195
|
|
]
|
|
];
|
|
function U(t) {
|
|
if (V(t), t < K.length) {
|
|
var e = K[t];
|
|
return {
|
|
r: e[0],
|
|
g: e[1],
|
|
b: e[2],
|
|
a: 255
|
|
};
|
|
}
|
|
throw new Error("Mask value must be in range [0, " + K.length + ")");
|
|
}
|
|
function q(t) {
|
|
var e = t.shape[2], n = (0, _tfjsCore.argMax)(t, 2), r = (0, _tfjsCore.reshape)(n, [
|
|
-1
|
|
]);
|
|
return (0, _tfjsCore.oneHot)(r, e);
|
|
}
|
|
function N(t, e) {
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
return (0, _tfjsCore.cast)((0, _tfjsCore.greater)(t, (0, _tfjsCore.scalar)(e)), "int32");
|
|
});
|
|
}
|
|
function Q(t, e) {
|
|
var n = e.shape, o = n[0], s = n[1], m = n[2];
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
var n = q(e), r = (0, _tfjsCore.expandDims)((0, _tfjsCore.range)(0, m, 1, "int32"), 1), g = (0, _tfjsCore.cast)((0, _tfjsCore.matMul)(n, r), "int32"), v = (0, _tfjsCore.reshape)(g, [
|
|
o,
|
|
s
|
|
]), w = (0, _tfjsCore.add)(v, (0, _tfjsCore.scalar)(1, "int32"));
|
|
return (0, _tfjsCore.sub)(function(t, e) {
|
|
return (0, _tfjsCore.mul)(t, e);
|
|
}(w, t), (0, _tfjsCore.scalar)(1, "int32"));
|
|
});
|
|
}
|
|
var X = function() {
|
|
function t(t, e) {
|
|
this.model = t, this.outputStride = e;
|
|
var n = this.model.inputs[0].shape;
|
|
(0, _tfjsCore.util).assert(-1 === n[1] && -1 === n[2], function() {
|
|
return "Input shape [" + n[1] + ", " + n[2] + "] must both be equal to or -1";
|
|
});
|
|
}
|
|
return t.prototype.predict = function(t) {
|
|
var e = this;
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
var n = e.preprocessInput((0, _tfjsCore.cast)(t, "float32")), r = (0, _tfjsCore.expandDims)(n, 0), o = e.model.predict(r).map(function(t) {
|
|
return (0, _tfjsCore.squeeze)(t, [
|
|
0
|
|
]);
|
|
}), a = e.nameOutputResults(o);
|
|
return {
|
|
heatmapScores: (0, _tfjsCore.sigmoid)(a.heatmap),
|
|
offsets: a.offsets,
|
|
displacementFwd: a.displacementFwd,
|
|
displacementBwd: a.displacementBwd,
|
|
segmentation: a.segmentation,
|
|
partHeatmaps: a.partHeatmaps,
|
|
longOffsets: a.longOffsets,
|
|
partOffsets: a.partOffsets
|
|
};
|
|
});
|
|
}, t.prototype.dispose = function() {
|
|
this.model.dispose();
|
|
}, t;
|
|
}(), Y = function(t) {
|
|
function e() {
|
|
return null !== t && t.apply(this, arguments) || this;
|
|
}
|
|
return F(e, t), e.prototype.preprocessInput = function(t) {
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
return (0, _tfjsCore.sub)((0, _tfjsCore.div)(t, 127.5), 1);
|
|
});
|
|
}, e.prototype.nameOutputResults = function(t) {
|
|
return {
|
|
offsets: t[0],
|
|
segmentation: t[1],
|
|
partHeatmaps: t[2],
|
|
longOffsets: t[3],
|
|
heatmap: t[4],
|
|
displacementFwd: t[5],
|
|
displacementBwd: t[6],
|
|
partOffsets: t[7]
|
|
};
|
|
}, e;
|
|
}(X), G = [
|
|
"nose",
|
|
"leftEye",
|
|
"rightEye",
|
|
"leftEar",
|
|
"rightEar",
|
|
"leftShoulder",
|
|
"rightShoulder",
|
|
"leftElbow",
|
|
"rightElbow",
|
|
"leftWrist",
|
|
"rightWrist",
|
|
"leftHip",
|
|
"rightHip",
|
|
"leftKnee",
|
|
"rightKnee",
|
|
"leftAnkle",
|
|
"rightAnkle"
|
|
], $ = G.length, J = G.reduce(function(t, e, n) {
|
|
return t[e] = n, t;
|
|
}, {});
|
|
[
|
|
[
|
|
"leftHip",
|
|
"leftShoulder"
|
|
],
|
|
[
|
|
"leftElbow",
|
|
"leftShoulder"
|
|
],
|
|
[
|
|
"leftElbow",
|
|
"leftWrist"
|
|
],
|
|
[
|
|
"leftHip",
|
|
"leftKnee"
|
|
],
|
|
[
|
|
"leftKnee",
|
|
"leftAnkle"
|
|
],
|
|
[
|
|
"rightHip",
|
|
"rightShoulder"
|
|
],
|
|
[
|
|
"rightElbow",
|
|
"rightShoulder"
|
|
],
|
|
[
|
|
"rightElbow",
|
|
"rightWrist"
|
|
],
|
|
[
|
|
"rightHip",
|
|
"rightKnee"
|
|
],
|
|
[
|
|
"rightKnee",
|
|
"rightAnkle"
|
|
],
|
|
[
|
|
"leftShoulder",
|
|
"rightShoulder"
|
|
],
|
|
[
|
|
"leftHip",
|
|
"rightHip"
|
|
]
|
|
].map(function(t) {
|
|
var e = t[0], n = t[1];
|
|
return [
|
|
J[e],
|
|
J[n]
|
|
];
|
|
});
|
|
function Z(t, e, n) {
|
|
var r = t[0], i = t[1], o = e[0], a = e[1], s = n.top, u = n.bottom;
|
|
return [
|
|
a / (n.left + n.right + i),
|
|
o / (s + u + r)
|
|
];
|
|
}
|
|
function tt(t, e, n, r) {
|
|
return {
|
|
y: r.get(t, e, n),
|
|
x: r.get(t, e, n + $)
|
|
};
|
|
}
|
|
function et(t, e, n) {
|
|
var r = tt(t.heatmapY, t.heatmapX, t.id, n), i = r.y, o = r.x;
|
|
return {
|
|
x: t.heatmapX * e + o,
|
|
y: t.heatmapY * e + i
|
|
};
|
|
}
|
|
function nt(t, e, n) {
|
|
return t < e ? e : t > n ? n : t;
|
|
}
|
|
function rt(t, e) {
|
|
return {
|
|
x: t.x + e.x,
|
|
y: t.y + e.y
|
|
};
|
|
}
|
|
function it(t, e, n) {
|
|
void 0 === n && (n = .3);
|
|
for(var r = 0, i = 0, o = 0; o < t.length; o++)e.keypoints[o].score > n && (i += 1, r += Math.pow(t[o].x - e.keypoints[o].position.x, 2) + Math.pow(t[o].y - e.keypoints[o].position.y, 2));
|
|
return 0 === i ? r = 1 / 0 : r /= i, r;
|
|
}
|
|
function ot(t, e, n, r, i, o, a) {
|
|
for(var s = a[0], u = a[1], f = n(t), l = f.y * r + f.x, c = i[$ * (2 * l) + e], d = i[$ * (2 * l + 1) + e], h = t.y + c, p = t.x + d, m = 0; m < o; m++){
|
|
h = Math.min(h, s - 1);
|
|
var g = n({
|
|
x: p = Math.min(p, u - 1),
|
|
y: h
|
|
}), v = g.y * r + g.x;
|
|
h += c = i[$ * (2 * v) + e], p += d = i[$ * (2 * v + 1) + e];
|
|
}
|
|
return {
|
|
x: p,
|
|
y: h
|
|
};
|
|
}
|
|
function at(t, e, n, r, i, o, a, s, u, f) {
|
|
for(var l = i[0], c = i[1], d = o[0], h = o[1], p = s[0], m = s[1], g = [], v = function(t) {
|
|
return function(t, e, n, r) {
|
|
var i = e[0], o = e[1], a = n[0], s = n[1], u = Math.round(((i + t.y + 1) * s - 1) / r);
|
|
return {
|
|
x: Math.round(((o + t.x + 1) * a - 1) / r),
|
|
y: u
|
|
};
|
|
}(t, [
|
|
l,
|
|
c
|
|
], [
|
|
d,
|
|
h
|
|
], u);
|
|
}, w = 0; w < r; w++){
|
|
var y = ot(t, w, v, a, e, f, [
|
|
p,
|
|
m
|
|
]);
|
|
g.push(y);
|
|
}
|
|
for(var b = -1, S = 1 / 0, x = 0; x < n.length; x++){
|
|
var M = it(g, n[x]);
|
|
M < S && (b = x, S = M);
|
|
}
|
|
return b;
|
|
}
|
|
function st(t, e) {
|
|
var n = t[0], r = t[1];
|
|
return [
|
|
Math.round((r - 1) / e + 1),
|
|
Math.round((n - 1) / e + 1)
|
|
];
|
|
}
|
|
function ut(t, e, n, r, i, o, a, s, u, f, l) {
|
|
for(var d = a[0], h = a[1], p = t.shape, m = p[0], g = p[1], v = e.shape.slice(0, 2), w = v[0], y = v[1], x = (0, _tfjsCore.reshape)(e, [
|
|
w,
|
|
y,
|
|
2,
|
|
$
|
|
]), M = new Float32Array(l * $ * 3).fill(0), k = 0; k < n.length; k++)for(var E = k * $ * 3, T = n[k], P = 0; P < $; P++){
|
|
var I = T.keypoints[P], O = E + 3 * P;
|
|
M[O] = I.score, M[O + 1] = I.position.y, M[O + 2] = I.position.x;
|
|
}
|
|
var _ = Z([
|
|
r,
|
|
i
|
|
], [
|
|
d,
|
|
h
|
|
], s), H = _[0], A = _[1], R = (0, _tfjsCore.tensor)(M, [
|
|
l,
|
|
$,
|
|
3
|
|
]), F = s.top, C = s.left, D = {
|
|
variableNames: [
|
|
"segmentation",
|
|
"longOffsets",
|
|
"poses"
|
|
],
|
|
outputShape: [
|
|
m,
|
|
g
|
|
],
|
|
userCode: "\n int convertToPositionInOutput(int pos, int pad, float scale, int stride) {\n return round(((float(pos + pad) + 1.0) * scale - 1.0) / float(stride));\n }\n\n float convertToPositionInOutputFloat(\n int pos, int pad, float scale, int stride) {\n return ((float(pos + pad) + 1.0) * scale - 1.0) / float(stride);\n }\n\n float dist(float x1, float y1, float x2, float y2) {\n return pow(x1 - x2, 2.0) + pow(y1 - y2, 2.0);\n }\n\n float sampleLongOffsets(float h, float w, int d, int k) {\n float fh = fract(h);\n float fw = fract(w);\n int clH = int(ceil(h));\n int clW = int(ceil(w));\n int flH = int(floor(h));\n int flW = int(floor(w));\n float o11 = getLongOffsets(flH, flW, d, k);\n float o12 = getLongOffsets(flH, clW, d, k);\n float o21 = getLongOffsets(clH, flW, d, k);\n float o22 = getLongOffsets(clH, clW, d, k);\n float o1 = mix(o11, o12, fw);\n float o2 = mix(o21, o22, fw);\n return mix(o1, o2, fh);\n }\n\n int findNearestPose(int h, int w) {\n float prob = getSegmentation(h, w);\n if (prob < 1.0) {\n return -1;\n }\n\n // Done(Tyler): convert from output space h/w to strided space.\n float stridedH = convertToPositionInOutputFloat(\n h, " + F + ", " + A + ", " + o + ");\n float stridedW = convertToPositionInOutputFloat(\n w, " + C + ", " + H + ", " + o + ");\n\n float minDist = 1000000.0;\n int iMin = -1;\n for (int i = 0; i < " + l + "; i++) {\n float curDistSum = 0.0;\n int numKpt = 0;\n for (int k = 0; k < " + $ + "; k++) {\n float dy = sampleLongOffsets(stridedH, stridedW, 0, k);\n float dx = sampleLongOffsets(stridedH, stridedW, 1, k);\n\n float y = float(h) + dy;\n float x = float(w) + dx;\n\n for (int s = 0; s < " + u + "; s++) {\n int yRounded = round(min(y, float(" + (r - 1) + ")));\n int xRounded = round(min(x, float(" + (i - 1) + ")));\n\n float yStrided = convertToPositionInOutputFloat(\n yRounded, " + F + ", " + A + ", " + o + ");\n float xStrided = convertToPositionInOutputFloat(\n xRounded, " + C + ", " + H + ", " + o + ");\n\n float dy = sampleLongOffsets(yStrided, xStrided, 0, k);\n float dx = sampleLongOffsets(yStrided, xStrided, 1, k);\n\n y = y + dy;\n x = x + dx;\n }\n\n float poseScore = getPoses(i, k, 0);\n float poseY = getPoses(i, k, 1);\n float poseX = getPoses(i, k, 2);\n if (poseScore > " + f + ") {\n numKpt = numKpt + 1;\n curDistSum = curDistSum + dist(x, y, poseX, poseY);\n }\n }\n if (numKpt > 0 && curDistSum / float(numKpt) < minDist) {\n minDist = curDistSum / float(numKpt);\n iMin = i;\n }\n }\n return iMin;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int nearestPose = findNearestPose(coords[0], coords[1]);\n setOutput(float(nearestPose));\n }\n "
|
|
};
|
|
return (0, _tfjsCore.backend)().compileAndRun(D, [
|
|
t,
|
|
x,
|
|
R
|
|
]);
|
|
}
|
|
function ft() {
|
|
return "webgl" === (0, _tfjsCore.getBackend)();
|
|
}
|
|
function lt(t, e, n, o, s, u, f, l, c, d, h, p) {
|
|
var m = f[0], g = f[1];
|
|
return void 0 === c && (c = .2), void 0 === d && (d = 8), void 0 === h && (h = .3), void 0 === p && (p = 10), D(this, void 0, void 0, function() {
|
|
var f, v, w, y, b;
|
|
return B(this, function(S) {
|
|
switch(S.label){
|
|
case 0:
|
|
return f = n.filter(function(t) {
|
|
return t.score >= c;
|
|
}), ft() ? (w = (0, _tfjsCore.tidy)(function() {
|
|
var n = ut(t, e, f, o, s, u, [
|
|
m,
|
|
g
|
|
], l, d, h, p), c = (0, _tfjsCore.engine)().makeTensorFromDataId(n.dataId, n.shape, n.dtype);
|
|
return f.map(function(t, e) {
|
|
return function(t, e) {
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
return (0, _tfjsCore.cast)((0, _tfjsCore.equal)(t, (0, _tfjsCore.scalar)(e)), "int32");
|
|
});
|
|
}(c, e);
|
|
});
|
|
}), [
|
|
4,
|
|
Promise.all(w.map(function(t) {
|
|
return t.data();
|
|
}))
|
|
]) : [
|
|
3,
|
|
2
|
|
];
|
|
case 1:
|
|
return v = S.sent(), w.forEach(function(t) {
|
|
return t.dispose();
|
|
}), [
|
|
3,
|
|
5
|
|
];
|
|
case 2:
|
|
return [
|
|
4,
|
|
t.data()
|
|
];
|
|
case 3:
|
|
return y = S.sent(), [
|
|
4,
|
|
e.data()
|
|
];
|
|
case 4:
|
|
b = S.sent(), v = function(t, e, n, r, i, o, a, s, u, f) {
|
|
var l = a[0], c = a[1];
|
|
void 0 === f && (f = 5);
|
|
for(var d = n.map(function(t) {
|
|
return new Uint8Array(r * i).fill(0);
|
|
}), h = s.top, p = s.left, m = Z([
|
|
r,
|
|
i
|
|
], [
|
|
l,
|
|
c
|
|
], s), g = m[0], v = m[1], w = st([
|
|
l,
|
|
c
|
|
], o)[0], y = 0; y < r; y += 1)for(var b = 0; b < i; b += 1){
|
|
var S = y * i + b;
|
|
if (1 === t[S]) {
|
|
var x = at({
|
|
x: b,
|
|
y: y
|
|
}, e, n, f, [
|
|
h,
|
|
p
|
|
], [
|
|
g,
|
|
v
|
|
], w, [
|
|
r,
|
|
i
|
|
], o, u);
|
|
x >= 0 && (d[x][S] = 1);
|
|
}
|
|
}
|
|
return d;
|
|
}(y, b, f, o, s, u, [
|
|
m,
|
|
g
|
|
], l, d), S.label = 5;
|
|
case 5:
|
|
return [
|
|
2,
|
|
v.map(function(t, e) {
|
|
return {
|
|
data: t,
|
|
pose: f[e],
|
|
width: s,
|
|
height: o
|
|
};
|
|
})
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function ct(t, e, n, o, s, u, f, l, c, m, g, v, w) {
|
|
var y = l[0], b = l[1];
|
|
return void 0 === m && (m = .2), void 0 === g && (g = 8), void 0 === v && (v = .3), void 0 === w && (w = 10), D(this, void 0, void 0, function() {
|
|
var l, S, x, E, T, P;
|
|
return B(this, function(I) {
|
|
switch(I.label){
|
|
case 0:
|
|
return l = o.filter(function(t) {
|
|
return t.score >= m;
|
|
}), ft() ? (x = (0, _tfjsCore.tidy)(function() {
|
|
var o = ut(t, e, l, s, u, f, [
|
|
y,
|
|
b
|
|
], c, g, v, w), m = (0, _tfjsCore.engine)().makeTensorFromDataId(o.dataId, o.shape, o.dtype);
|
|
return l.map(function(t, e) {
|
|
return function(t, e, n) {
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
return (0, _tfjsCore.sub)((0, _tfjsCore.mul)((0, _tfjsCore.cast)((0, _tfjsCore.equal)(t, (0, _tfjsCore.scalar)(n)), "int32"), (0, _tfjsCore.add)(e, 1)), 1);
|
|
});
|
|
}(m, n, e);
|
|
});
|
|
}), [
|
|
4,
|
|
Promise.all(x.map(function(t) {
|
|
return t.data();
|
|
}))
|
|
]) : [
|
|
3,
|
|
2
|
|
];
|
|
case 1:
|
|
return S = I.sent(), x.forEach(function(t) {
|
|
return t.dispose();
|
|
}), [
|
|
3,
|
|
6
|
|
];
|
|
case 2:
|
|
return [
|
|
4,
|
|
t.data()
|
|
];
|
|
case 3:
|
|
return E = I.sent(), [
|
|
4,
|
|
e.data()
|
|
];
|
|
case 4:
|
|
return T = I.sent(), [
|
|
4,
|
|
n.data()
|
|
];
|
|
case 5:
|
|
P = I.sent(), S = function(t, e, n, r, i, o, a, s, u, f, l) {
|
|
var c = s[0], d = s[1];
|
|
void 0 === l && (l = 5);
|
|
for(var h = r.map(function(t) {
|
|
return new Int32Array(i * o).fill(-1);
|
|
}), p = u.top, m = u.left, g = Z([
|
|
i,
|
|
o
|
|
], [
|
|
c,
|
|
d
|
|
], u), v = g[0], w = g[1], y = st([
|
|
c,
|
|
d
|
|
], a)[0], b = 0; b < i; b += 1)for(var S = 0; S < o; S += 1){
|
|
var x = b * o + S;
|
|
if (1 === t[x]) {
|
|
var M = at({
|
|
x: S,
|
|
y: b
|
|
}, e, r, l, [
|
|
p,
|
|
m
|
|
], [
|
|
v,
|
|
w
|
|
], y, [
|
|
i,
|
|
o
|
|
], a, f);
|
|
M >= 0 && (h[M][x] = n[x]);
|
|
}
|
|
}
|
|
return h;
|
|
}(E, T, P, l, s, u, f, [
|
|
y,
|
|
b
|
|
], c, g), I.label = 6;
|
|
case 6:
|
|
return [
|
|
2,
|
|
S.map(function(t, e) {
|
|
return {
|
|
pose: l[e],
|
|
data: t,
|
|
height: s,
|
|
width: u
|
|
};
|
|
})
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function dt(t) {
|
|
return Math.floor(t / 2);
|
|
}
|
|
var ht = function() {
|
|
function t(t, e) {
|
|
this.priorityQueue = new Array(t), this.numberOfElements = -1, this.getElementValue = e;
|
|
}
|
|
return t.prototype.enqueue = function(t) {
|
|
this.priorityQueue[++this.numberOfElements] = t, this.swim(this.numberOfElements);
|
|
}, t.prototype.dequeue = function() {
|
|
var t = this.priorityQueue[0];
|
|
return this.exchange(0, this.numberOfElements--), this.sink(0), this.priorityQueue[this.numberOfElements + 1] = null, t;
|
|
}, t.prototype.empty = function() {
|
|
return -1 === this.numberOfElements;
|
|
}, t.prototype.size = function() {
|
|
return this.numberOfElements + 1;
|
|
}, t.prototype.all = function() {
|
|
return this.priorityQueue.slice(0, this.numberOfElements + 1);
|
|
}, t.prototype.max = function() {
|
|
return this.priorityQueue[0];
|
|
}, t.prototype.swim = function(t) {
|
|
for(; t > 0 && this.less(dt(t), t);)this.exchange(t, dt(t)), t = dt(t);
|
|
}, t.prototype.sink = function(t) {
|
|
for(; 2 * t <= this.numberOfElements;){
|
|
var e = 2 * t;
|
|
if (e < this.numberOfElements && this.less(e, e + 1) && e++, !this.less(t, e)) break;
|
|
this.exchange(t, e), t = e;
|
|
}
|
|
}, t.prototype.getValueAt = function(t) {
|
|
return this.getElementValue(this.priorityQueue[t]);
|
|
}, t.prototype.less = function(t, e) {
|
|
return this.getValueAt(t) < this.getValueAt(e);
|
|
}, t.prototype.exchange = function(t, e) {
|
|
var n = this.priorityQueue[t];
|
|
this.priorityQueue[t] = this.priorityQueue[e], this.priorityQueue[e] = n;
|
|
}, t;
|
|
}();
|
|
function pt(t, e, n, r, i, o) {
|
|
for(var a = o.shape, s = a[0], u = a[1], f = !0, l = Math.max(n - i, 0), c = Math.min(n + i + 1, s), d = l; d < c; ++d){
|
|
for(var h = Math.max(r - i, 0), p = Math.min(r + i + 1, u), m = h; m < p; ++m)if (o.get(d, m, t) > e) {
|
|
f = !1;
|
|
break;
|
|
}
|
|
if (!f) break;
|
|
}
|
|
return f;
|
|
}
|
|
var mt = [
|
|
[
|
|
"nose",
|
|
"leftEye"
|
|
],
|
|
[
|
|
"leftEye",
|
|
"leftEar"
|
|
],
|
|
[
|
|
"nose",
|
|
"rightEye"
|
|
],
|
|
[
|
|
"rightEye",
|
|
"rightEar"
|
|
],
|
|
[
|
|
"nose",
|
|
"leftShoulder"
|
|
],
|
|
[
|
|
"leftShoulder",
|
|
"leftElbow"
|
|
],
|
|
[
|
|
"leftElbow",
|
|
"leftWrist"
|
|
],
|
|
[
|
|
"leftShoulder",
|
|
"leftHip"
|
|
],
|
|
[
|
|
"leftHip",
|
|
"leftKnee"
|
|
],
|
|
[
|
|
"leftKnee",
|
|
"leftAnkle"
|
|
],
|
|
[
|
|
"nose",
|
|
"rightShoulder"
|
|
],
|
|
[
|
|
"rightShoulder",
|
|
"rightElbow"
|
|
],
|
|
[
|
|
"rightElbow",
|
|
"rightWrist"
|
|
],
|
|
[
|
|
"rightShoulder",
|
|
"rightHip"
|
|
],
|
|
[
|
|
"rightHip",
|
|
"rightKnee"
|
|
],
|
|
[
|
|
"rightKnee",
|
|
"rightAnkle"
|
|
]
|
|
].map(function(t) {
|
|
var e = t[0], n = t[1];
|
|
return [
|
|
J[e],
|
|
J[n]
|
|
];
|
|
}), gt = mt.map(function(t) {
|
|
return t[1];
|
|
}), vt = mt.map(function(t) {
|
|
return t[0];
|
|
});
|
|
function wt(t, e, n, r) {
|
|
return {
|
|
y: nt(Math.round(t.y / e), 0, n - 1),
|
|
x: nt(Math.round(t.x / e), 0, r - 1)
|
|
};
|
|
}
|
|
function yt(t, e, n, r, i, o, a, s) {
|
|
void 0 === s && (s = 2);
|
|
for(var u = r.shape, f = u[0], l = u[1], c = function(t, e, n) {
|
|
var r = n.shape[2] / 2;
|
|
return {
|
|
y: n.get(e.y, e.x, t),
|
|
x: n.get(e.y, e.x, r + t)
|
|
};
|
|
}(t, wt(e.position, o, f, l), a), d = rt(e.position, c), h = 0; h < s; h++){
|
|
var p = wt(d, o, f, l), m = tt(p.y, p.x, n, i);
|
|
d = rt({
|
|
x: p.x * o,
|
|
y: p.y * o
|
|
}, {
|
|
x: m.x,
|
|
y: m.y
|
|
});
|
|
}
|
|
var g = wt(d, o, f, l), v = r.get(g.y, g.x, n);
|
|
return {
|
|
position: d,
|
|
part: G[n],
|
|
score: v
|
|
};
|
|
}
|
|
function bt(t, e, n, r, i, o) {
|
|
var a = e.shape[2], s = gt.length, u = new Array(a), f = t.part, l = t.score, c = et(f, r, n);
|
|
u[f.id] = {
|
|
score: l,
|
|
part: G[f.id],
|
|
position: c
|
|
};
|
|
for(var d = s - 1; d >= 0; --d){
|
|
var h = gt[d], p = vt[d];
|
|
u[h] && !u[p] && (u[p] = yt(d, u[h], p, e, n, r, o));
|
|
}
|
|
for(d = 0; d < s; ++d){
|
|
h = vt[d], p = gt[d];
|
|
u[h] && !u[p] && (u[p] = yt(d, u[h], p, e, n, r, i));
|
|
}
|
|
return u;
|
|
}
|
|
function St(t, e, n, r) {
|
|
var i = n.x, o = n.y;
|
|
return t.some(function(t) {
|
|
var n, a, s, u, f, l, c = t.keypoints[r].position;
|
|
return n = o, a = i, s = c.y, u = c.x, (f = s - n) * f + (l = u - a) * l <= e;
|
|
});
|
|
}
|
|
function xt(t, e, n) {
|
|
var r = n.reduce(function(n, r, i) {
|
|
var o = r.position, a = r.score;
|
|
return St(t, e, o, i) || (n += a), n;
|
|
}, 0);
|
|
return r / n.length;
|
|
}
|
|
function Mt(t, e, n, r, i, o, a, s) {
|
|
void 0 === a && (a = .5), void 0 === s && (s = 20);
|
|
for(var u = [], f = function(t, e, n) {
|
|
for(var r = n.shape, i = r[0], o = r[1], a = r[2], s = new ht(i * o * a, function(t) {
|
|
return t.score;
|
|
}), u = 0; u < i; ++u)for(var f = 0; f < o; ++f)for(var l = 0; l < a; ++l){
|
|
var c = n.get(u, f, l);
|
|
c < t || pt(l, c, u, f, e, n) && s.enqueue({
|
|
score: c,
|
|
part: {
|
|
heatmapY: u,
|
|
heatmapX: f,
|
|
id: l
|
|
}
|
|
});
|
|
}
|
|
return s;
|
|
}(a, 1, t), l = s * s; u.length < o && !f.empty();){
|
|
var c = f.dequeue();
|
|
if (!St(u, l, et(c.part, i, e), c.part.id)) {
|
|
var d = bt(c, t, e, i, n, r), h = xt(u, l, d);
|
|
u.push({
|
|
keypoints: d,
|
|
score: h
|
|
});
|
|
}
|
|
}
|
|
return u;
|
|
}
|
|
var kt, Et = [
|
|
-123.15,
|
|
-115.9,
|
|
-103.06
|
|
], Tt = function(t) {
|
|
function e() {
|
|
return null !== t && t.apply(this, arguments) || this;
|
|
}
|
|
return F(e, t), e.prototype.preprocessInput = function(t) {
|
|
return (0, _tfjsCore.add)(t, Et);
|
|
}, e.prototype.nameOutputResults = function(t) {
|
|
var e = t[0], n = t[1], r = t[2], i = t[3], o = t[4], a = t[5];
|
|
return {
|
|
offsets: o,
|
|
segmentation: t[6],
|
|
partHeatmaps: a,
|
|
longOffsets: i,
|
|
heatmap: r,
|
|
displacementFwd: n,
|
|
displacementBwd: e,
|
|
partOffsets: t[7]
|
|
};
|
|
}, e;
|
|
}(X), Pt = "https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/resnet50/", It = "https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/mobilenet/";
|
|
function Ot(t) {
|
|
if ("undefined" != typeof HTMLCanvasElement && t instanceof HTMLCanvasElement || "undefined" != typeof OffscreenCanvas && t instanceof OffscreenCanvas || "undefined" != typeof HTMLImageElement && t instanceof HTMLImageElement) return function(t) {
|
|
if ("offsetHeight" in t && 0 !== t.offsetHeight && "offsetWidth" in t && 0 !== t.offsetWidth) return [
|
|
t.offsetHeight,
|
|
t.offsetWidth
|
|
];
|
|
if (null != t.height && null != t.width) return [
|
|
t.height,
|
|
t.width
|
|
];
|
|
throw new Error("HTMLImageElement must have height and width attributes set.");
|
|
}(t);
|
|
if ("undefined" != typeof ImageData && t instanceof ImageData) return [
|
|
t.height,
|
|
t.width
|
|
];
|
|
if ("undefined" != typeof HTMLVideoElement && t instanceof HTMLVideoElement) return function(t) {
|
|
return t.hasAttribute("height") && t.hasAttribute("width") ? [
|
|
t.height,
|
|
t.width
|
|
] : [
|
|
t.videoHeight,
|
|
t.videoWidth
|
|
];
|
|
}(t);
|
|
if (t instanceof (0, _tfjsCore.Tensor)) return [
|
|
t.shape[0],
|
|
t.shape[1]
|
|
];
|
|
throw new Error("error: Unknown input type: " + t + ".");
|
|
}
|
|
function _t(t, e) {
|
|
return function(t, e) {
|
|
return (t - 1) % e == 0;
|
|
}(t, e) ? t : Math.floor(t / e) * e + 1;
|
|
}
|
|
var Ht = {
|
|
low: "low",
|
|
medium: "medium",
|
|
high: "high",
|
|
full: "full"
|
|
}, At = ((kt = {})[Ht.low] = .25, kt[Ht.medium] = .5, kt[Ht.high] = .75, kt[Ht.full] = 1, kt);
|
|
function Rt(t, e, n) {
|
|
var r = n[0], i = n[1], o = function(t) {
|
|
if ("string" == typeof t) {
|
|
var e = At[t];
|
|
return (0, _tfjsCore.util).assert("number" == typeof e, function() {
|
|
return "string value of inputResolution must be one of " + Object.values(Ht).join(",") + " but was " + t + ".";
|
|
}), e;
|
|
}
|
|
return (0, _tfjsCore.util).assert("number" == typeof t && t <= 2 && t >= .1, function() {
|
|
return "inputResolution must be a string or number between 0.1 and 2, but was " + t;
|
|
}), t;
|
|
}(t);
|
|
return [
|
|
_t(r * o, e),
|
|
_t(i * o, e)
|
|
];
|
|
}
|
|
function Ft(t, e, n, i, o) {
|
|
var a = e[0], s = e[1], f = n[0], l = n[1], c = i[0], d = c[0], h = c[1], p = i[1], m = p[0], w = p[1];
|
|
return void 0 === o && (o = !1), (0, _tfjsCore.tidy)(function() {
|
|
var e = (0, _tfjsCore.image).resizeBilinear(t, [
|
|
f,
|
|
l
|
|
], !0);
|
|
return o && (e = (0, _tfjsCore.sigmoid)(e)), function(t, e, n) {
|
|
var i = e[0], o = e[1], a = n[0], s = a[0], f = a[1], l = n[1], c = l[0], d = l[1];
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
var e = (0, _tfjsCore.expandDims)(t);
|
|
return (0, _tfjsCore.squeeze)((0, _tfjsCore.image).cropAndResize(e, [
|
|
[
|
|
s / (i + s + f - 1),
|
|
c / (o + c + d - 1),
|
|
(s + i - 1) / (i + s + f - 1),
|
|
(c + o - 1) / (o + c + d - 1)
|
|
]
|
|
], [
|
|
0
|
|
], [
|
|
i,
|
|
o
|
|
]), [
|
|
0
|
|
]);
|
|
});
|
|
}(e, [
|
|
a,
|
|
s
|
|
], [
|
|
[
|
|
d,
|
|
h
|
|
],
|
|
[
|
|
m,
|
|
w
|
|
]
|
|
]);
|
|
});
|
|
}
|
|
function Ct(t, i) {
|
|
var o = i[0], a = i[1], s = Ot(t), u = s[0], f = s[1], l = a / o, c = [
|
|
0,
|
|
0,
|
|
0,
|
|
0
|
|
], d = c[0], h = c[1], p = c[2], m = c[3];
|
|
f / u < l ? (d = 0, h = 0, p = Math.round(.5 * (l * u - f)), m = Math.round(.5 * (l * u - f))) : (d = Math.round(.5 * (1 / l * f - u)), h = Math.round(.5 * (1 / l * f - u)), p = 0, m = 0);
|
|
var g = (0, _tfjsCore.tidy)(function() {
|
|
var r = function(t) {
|
|
return t instanceof (0, _tfjsCore.Tensor) ? t : (0, _tfjsCore.browser).fromPixels(t);
|
|
}(t);
|
|
return r = (0, _tfjsCore.pad3d)(r, [
|
|
[
|
|
d,
|
|
h
|
|
],
|
|
[
|
|
p,
|
|
m
|
|
],
|
|
[
|
|
0,
|
|
0
|
|
]
|
|
]), (0, _tfjsCore.image).resizeBilinear(r, [
|
|
o,
|
|
a
|
|
]);
|
|
});
|
|
return {
|
|
resized: g,
|
|
padding: {
|
|
top: d,
|
|
left: p,
|
|
right: m,
|
|
bottom: h
|
|
}
|
|
};
|
|
}
|
|
function Dt(t) {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(e) {
|
|
return [
|
|
2,
|
|
Promise.all(t.map(function(t) {
|
|
return t.buffer();
|
|
}))
|
|
];
|
|
});
|
|
});
|
|
}
|
|
function Bt(t, e, n, r, i) {
|
|
var o = e[0], a = e[1], s = n[0], u = n[1], f = function(t, e, n, r, i) {
|
|
return void 0 === r && (r = 0), void 0 === i && (i = 0), 1 === n && 1 === e && 0 === r && 0 === i ? t : t.map(function(t) {
|
|
return function(t, e, n, r, i) {
|
|
return void 0 === r && (r = 0), void 0 === i && (i = 0), {
|
|
score: t.score,
|
|
keypoints: t.keypoints.map(function(t) {
|
|
var o = t.score, a = t.part, s = t.position;
|
|
return {
|
|
score: o,
|
|
part: a,
|
|
position: {
|
|
x: s.x * n + i,
|
|
y: s.y * e + r
|
|
}
|
|
};
|
|
})
|
|
};
|
|
}(t, e, n, r, i);
|
|
});
|
|
}(t, (o + r.top + r.bottom) / s, (a + r.left + r.right) / u, -r.top, -r.left);
|
|
return i ? function(t, e) {
|
|
return e <= 0 ? t : t.map(function(t) {
|
|
return function(t, e) {
|
|
return {
|
|
score: t.score,
|
|
keypoints: t.keypoints.map(function(t) {
|
|
var n = t.score, r = t.part, i = t.position;
|
|
return {
|
|
score: n,
|
|
part: r,
|
|
position: {
|
|
x: e - 1 - i.x,
|
|
y: i.y
|
|
}
|
|
};
|
|
})
|
|
};
|
|
}(t, e);
|
|
});
|
|
}(f, a) : f;
|
|
}
|
|
var Lt = {
|
|
architecture: "MobileNetV1",
|
|
outputStride: 16,
|
|
quantBytes: 4,
|
|
multiplier: .75
|
|
}, zt = [
|
|
"MobileNetV1",
|
|
"ResNet50"
|
|
], Wt = {
|
|
MobileNetV1: [
|
|
8,
|
|
16,
|
|
32
|
|
],
|
|
ResNet50: [
|
|
32,
|
|
16
|
|
]
|
|
}, jt = {
|
|
MobileNetV1: [
|
|
.5,
|
|
.75,
|
|
1
|
|
],
|
|
ResNet50: [
|
|
1
|
|
]
|
|
}, Vt = [
|
|
1,
|
|
2,
|
|
4
|
|
];
|
|
var Kt = {
|
|
flipHorizontal: !1,
|
|
internalResolution: "medium",
|
|
segmentationThreshold: .7,
|
|
maxDetections: 10,
|
|
scoreThreshold: .4,
|
|
nmsRadius: 20
|
|
}, Ut = {
|
|
flipHorizontal: !1,
|
|
internalResolution: "medium",
|
|
segmentationThreshold: .7,
|
|
maxDetections: 10,
|
|
scoreThreshold: .4,
|
|
nmsRadius: 20,
|
|
minKeypointScore: .3,
|
|
refineSteps: 10
|
|
};
|
|
function qt(t) {
|
|
var e = t.segmentationThreshold, n = t.maxDetections, r = t.scoreThreshold, i = t.nmsRadius;
|
|
if (e < 0 || e > 1) throw new Error("segmentationThreshold " + e + ". Should be in range [0.0, 1.0]");
|
|
if (n <= 0) throw new Error("Invalid maxDetections " + n + ". Should be > 0");
|
|
if (r < 0 || r > 1) throw new Error("Invalid scoreThreshold " + r + ". Should be in range [0.0, 1.0]");
|
|
if (i <= 0) throw new Error("Invalid nmsRadius " + i + ".");
|
|
}
|
|
function Nt(t) {
|
|
var e = t.segmentationThreshold, n = t.maxDetections, r = t.scoreThreshold, i = t.nmsRadius, o = t.minKeypointScore, a = t.refineSteps;
|
|
if (e < 0 || e > 1) throw new Error("segmentationThreshold " + e + ". Should be in range [0.0, 1.0]");
|
|
if (n <= 0) throw new Error("Invalid maxDetections " + n + ". Should be > 0");
|
|
if (r < 0 || r > 1) throw new Error("Invalid scoreThreshold " + r + ". Should be in range [0.0, 1.0]");
|
|
if (i <= 0) throw new Error("Invalid nmsRadius " + i + ".");
|
|
if (o < 0 || o > 1) throw new Error("Invalid minKeypointScore " + o + ".Should be in range [0.0, 1.0]");
|
|
if (a <= 0 || a > 20) throw new Error("Invalid refineSteps " + a + ".Should be in range [1, 20]");
|
|
}
|
|
var Qt = function() {
|
|
function t(t) {
|
|
this.baseModel = t;
|
|
}
|
|
return t.prototype.predictForPersonSegmentation = function(t) {
|
|
var e = this.baseModel.predict(t);
|
|
return {
|
|
segmentLogits: e.segmentation,
|
|
heatmapScores: e.heatmapScores,
|
|
offsets: e.offsets,
|
|
displacementFwd: e.displacementFwd,
|
|
displacementBwd: e.displacementBwd
|
|
};
|
|
}, t.prototype.predictForPersonSegmentationAndPart = function(t) {
|
|
var e = this.baseModel.predict(t);
|
|
return {
|
|
segmentLogits: e.segmentation,
|
|
partHeatmapLogits: e.partHeatmaps,
|
|
heatmapScores: e.heatmapScores,
|
|
offsets: e.offsets,
|
|
displacementFwd: e.displacementFwd,
|
|
displacementBwd: e.displacementBwd
|
|
};
|
|
}, t.prototype.predictForMultiPersonInstanceSegmentationAndPart = function(t) {
|
|
var e = this.baseModel.predict(t);
|
|
return {
|
|
segmentLogits: e.segmentation,
|
|
longOffsets: e.longOffsets,
|
|
heatmapScores: e.heatmapScores,
|
|
offsets: e.offsets,
|
|
displacementFwd: e.displacementFwd,
|
|
displacementBwd: e.displacementBwd,
|
|
partHeatmaps: e.partHeatmaps
|
|
};
|
|
}, t.prototype.segmentPersonActivation = function(t, e, n) {
|
|
var i = this;
|
|
void 0 === n && (n = .5);
|
|
var o = Ot(t), a = o[0], s = o[1], u = Rt(e, this.baseModel.outputStride, [
|
|
a,
|
|
s
|
|
]), f = Ct(t, u), l = f.resized, c = f.padding, d = (0, _tfjsCore.tidy)(function() {
|
|
var t = i.predictForPersonSegmentation(l), e = t.segmentLogits, r = t.heatmapScores, o = t.offsets, u = t.displacementFwd, f = t.displacementBwd, d = l.shape, h = d[0], p = d[1], m = Ft(e, [
|
|
a,
|
|
s
|
|
], [
|
|
h,
|
|
p
|
|
], [
|
|
[
|
|
c.top,
|
|
c.bottom
|
|
],
|
|
[
|
|
c.left,
|
|
c.right
|
|
]
|
|
], true);
|
|
return {
|
|
segmentation: N((0, _tfjsCore.squeeze)(m), n),
|
|
heatmapScores: r,
|
|
offsets: o,
|
|
displacementFwd: u,
|
|
displacementBwd: f
|
|
};
|
|
}), h = d.segmentation, p = d.heatmapScores, m = d.offsets, v = d.displacementFwd, w = d.displacementBwd;
|
|
return l.dispose(), {
|
|
segmentation: h,
|
|
heatmapScores: p,
|
|
offsets: m,
|
|
displacementFwd: v,
|
|
displacementBwd: w,
|
|
padding: c,
|
|
internalResolutionHeightAndWidth: u
|
|
};
|
|
}, t.prototype.segmentPerson = function(t, e) {
|
|
return void 0 === e && (e = Kt), D(this, void 0, void 0, function() {
|
|
var n, r, i, o, a, s, u, f, l, c, d, h, p, m, g, v, w, y;
|
|
return B(this, function(b) {
|
|
switch(b.label){
|
|
case 0:
|
|
return qt(e = C(C({}, Kt), e)), n = this.segmentPersonActivation(t, e.internalResolution, e.segmentationThreshold), r = n.segmentation, i = n.heatmapScores, o = n.offsets, a = n.displacementFwd, s = n.displacementBwd, u = n.padding, f = n.internalResolutionHeightAndWidth, l = r.shape, c = l[0], d = l[1], [
|
|
4,
|
|
r.data()
|
|
];
|
|
case 1:
|
|
return h = b.sent(), r.dispose(), [
|
|
4,
|
|
Dt([
|
|
i,
|
|
o,
|
|
a,
|
|
s
|
|
])
|
|
];
|
|
case 2:
|
|
return p = b.sent(), m = p[0], g = p[1], v = p[2], w = p[3], y = Bt(y = Mt(m, g, v, w, this.baseModel.outputStride, e.maxDetections, e.scoreThreshold, e.nmsRadius), [
|
|
c,
|
|
d
|
|
], f, u, false), i.dispose(), o.dispose(), a.dispose(), s.dispose(), [
|
|
2,
|
|
{
|
|
height: c,
|
|
width: d,
|
|
data: h,
|
|
allPoses: y
|
|
}
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}, t.prototype.segmentMultiPerson = function(t, e) {
|
|
return void 0 === e && (e = Ut), D(this, void 0, void 0, function() {
|
|
var n, i, o, a, s, u, f, l, c, d, h, p, m, v, w, y, b, S, x, M, k, E = this;
|
|
return B(this, function(T) {
|
|
switch(T.label){
|
|
case 0:
|
|
return Nt(e = C(C({}, Ut), e)), n = Ot(t), i = n[0], o = n[1], a = Rt(e.internalResolution, this.baseModel.outputStride, [
|
|
i,
|
|
o
|
|
]), s = Ct(t, a), u = s.resized, f = s.padding, l = (0, _tfjsCore.tidy)(function() {
|
|
var t, n = E.predictForMultiPersonInstanceSegmentationAndPart(u), r = n.segmentLogits, s = n.longOffsets, l = n.heatmapScores, c = n.offsets, d = n.displacementFwd, h = n.displacementBwd, p = Ft(r, [
|
|
i,
|
|
o
|
|
], a, [
|
|
[
|
|
f.top,
|
|
f.bottom
|
|
],
|
|
[
|
|
f.left,
|
|
f.right
|
|
]
|
|
], true);
|
|
return t = s, {
|
|
segmentation: N((0, _tfjsCore.squeeze)(p), e.segmentationThreshold),
|
|
longOffsets: t,
|
|
heatmapScoresRaw: l,
|
|
offsetsRaw: c,
|
|
displacementFwdRaw: d,
|
|
displacementBwdRaw: h
|
|
};
|
|
}), c = l.segmentation, d = l.longOffsets, h = l.heatmapScoresRaw, p = l.offsetsRaw, m = l.displacementFwdRaw, v = l.displacementBwdRaw, [
|
|
4,
|
|
Dt([
|
|
h,
|
|
p,
|
|
m,
|
|
v
|
|
])
|
|
];
|
|
case 1:
|
|
return w = T.sent(), y = w[0], b = w[1], S = w[2], x = w[3], M = Bt(M = Mt(y, b, S, x, this.baseModel.outputStride, e.maxDetections, e.scoreThreshold, e.nmsRadius), [
|
|
i,
|
|
o
|
|
], a, f, false), [
|
|
4,
|
|
lt(c, d, M, i, o, this.baseModel.outputStride, a, f, e.scoreThreshold, e.refineSteps, e.minKeypointScore, e.maxDetections)
|
|
];
|
|
case 2:
|
|
return k = T.sent(), u.dispose(), c.dispose(), d.dispose(), h.dispose(), p.dispose(), m.dispose(), v.dispose(), [
|
|
2,
|
|
k
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}, t.prototype.segmentPersonPartsActivation = function(t, e, n) {
|
|
var i = this;
|
|
void 0 === n && (n = .5);
|
|
var o = Ot(t), a = o[0], s = o[1], u = Rt(e, this.baseModel.outputStride, [
|
|
a,
|
|
s
|
|
]), f = Ct(t, u), l = f.resized, c = f.padding, d = (0, _tfjsCore.tidy)(function() {
|
|
var t = i.predictForPersonSegmentationAndPart(l), e = t.segmentLogits, r = t.partHeatmapLogits, o = t.heatmapScores, u = t.offsets, f = t.displacementFwd, d = t.displacementBwd, h = l.shape, p = h[0], m = h[1], v = Ft(e, [
|
|
a,
|
|
s
|
|
], [
|
|
p,
|
|
m
|
|
], [
|
|
[
|
|
c.top,
|
|
c.bottom
|
|
],
|
|
[
|
|
c.left,
|
|
c.right
|
|
]
|
|
], true), w = Ft(r, [
|
|
a,
|
|
s
|
|
], [
|
|
p,
|
|
m
|
|
], [
|
|
[
|
|
c.top,
|
|
c.bottom
|
|
],
|
|
[
|
|
c.left,
|
|
c.right
|
|
]
|
|
], true);
|
|
return {
|
|
partSegmentation: Q(N((0, _tfjsCore.squeeze)(v), n), w),
|
|
heatmapScores: o,
|
|
offsets: u,
|
|
displacementFwd: f,
|
|
displacementBwd: d
|
|
};
|
|
}), h = d.partSegmentation, p = d.heatmapScores, m = d.offsets, v = d.displacementFwd, w = d.displacementBwd;
|
|
return l.dispose(), {
|
|
partSegmentation: h,
|
|
heatmapScores: p,
|
|
offsets: m,
|
|
displacementFwd: v,
|
|
displacementBwd: w,
|
|
padding: c,
|
|
internalResolutionHeightAndWidth: u
|
|
};
|
|
}, t.prototype.segmentPersonParts = function(t, e) {
|
|
return void 0 === e && (e = Kt), D(this, void 0, void 0, function() {
|
|
var n, r, i, o, a, s, u, f, l, c, d, h, p, m, g, v, w, y;
|
|
return B(this, function(b) {
|
|
switch(b.label){
|
|
case 0:
|
|
return qt(e = C(C({}, Kt), e)), n = this.segmentPersonPartsActivation(t, e.internalResolution, e.segmentationThreshold), r = n.partSegmentation, i = n.heatmapScores, o = n.offsets, a = n.displacementFwd, s = n.displacementBwd, u = n.padding, f = n.internalResolutionHeightAndWidth, l = r.shape, c = l[0], d = l[1], [
|
|
4,
|
|
r.data()
|
|
];
|
|
case 1:
|
|
return h = b.sent(), r.dispose(), [
|
|
4,
|
|
Dt([
|
|
i,
|
|
o,
|
|
a,
|
|
s
|
|
])
|
|
];
|
|
case 2:
|
|
return p = b.sent(), m = p[0], g = p[1], v = p[2], w = p[3], y = Bt(y = Mt(m, g, v, w, this.baseModel.outputStride, e.maxDetections, e.scoreThreshold, e.nmsRadius), [
|
|
c,
|
|
d
|
|
], f, u, false), i.dispose(), o.dispose(), a.dispose(), s.dispose(), [
|
|
2,
|
|
{
|
|
height: c,
|
|
width: d,
|
|
data: h,
|
|
allPoses: y
|
|
}
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}, t.prototype.segmentMultiPersonParts = function(t, e) {
|
|
return void 0 === e && (e = Ut), D(this, void 0, void 0, function() {
|
|
var n, o, a, s, d, h, p, m, v, w, y, b, S, x, M, k, E, T, P, I, O, _, H = this;
|
|
return B(this, function(A) {
|
|
switch(A.label){
|
|
case 0:
|
|
return Nt(e = C(C({}, Ut), e)), n = Ot(t), o = n[0], a = n[1], s = Rt(e.internalResolution, this.baseModel.outputStride, [
|
|
o,
|
|
a
|
|
]), d = Ct(t, s), h = d.resized, p = d.padding, m = (0, _tfjsCore.tidy)(function() {
|
|
var t = H.predictForMultiPersonInstanceSegmentationAndPart(h), n = t.segmentLogits, d = t.longOffsets, m = t.heatmapScores, v = t.offsets, w = t.displacementFwd, y = t.displacementBwd, b = t.partHeatmaps, S = Ft(n, [
|
|
o,
|
|
a
|
|
], s, [
|
|
[
|
|
p.top,
|
|
p.bottom
|
|
],
|
|
[
|
|
p.left,
|
|
p.right
|
|
]
|
|
], true), x = Ft(b, [
|
|
o,
|
|
a
|
|
], s, [
|
|
[
|
|
p.top,
|
|
p.bottom
|
|
],
|
|
[
|
|
p.left,
|
|
p.right
|
|
]
|
|
], true), M = d, k = N((0, _tfjsCore.squeeze)(S), e.segmentationThreshold), E = function(t) {
|
|
var e = t.shape, n = e[0], o = e[1], a = e[2];
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
var e = q(t), r = (0, _tfjsCore.expandDims)((0, _tfjsCore.range)(0, a, 1, "int32"), 1), s = (0, _tfjsCore.cast)((0, _tfjsCore.matMul)(e, r), "int32");
|
|
return (0, _tfjsCore.reshape)(s, [
|
|
n,
|
|
o
|
|
]);
|
|
});
|
|
}(x);
|
|
return {
|
|
segmentation: k,
|
|
longOffsets: M,
|
|
heatmapScoresRaw: m,
|
|
offsetsRaw: v,
|
|
displacementFwdRaw: w,
|
|
displacementBwdRaw: y,
|
|
partSegmentation: E
|
|
};
|
|
}), v = m.segmentation, w = m.longOffsets, y = m.heatmapScoresRaw, b = m.offsetsRaw, S = m.displacementFwdRaw, x = m.displacementBwdRaw, M = m.partSegmentation, [
|
|
4,
|
|
Dt([
|
|
y,
|
|
b,
|
|
S,
|
|
x
|
|
])
|
|
];
|
|
case 1:
|
|
return k = A.sent(), E = k[0], T = k[1], P = k[2], I = k[3], O = Bt(O = Mt(E, T, P, I, this.baseModel.outputStride, e.maxDetections, e.scoreThreshold, e.nmsRadius), [
|
|
o,
|
|
a
|
|
], s, p, false), [
|
|
4,
|
|
ct(v, w, M, O, o, a, this.baseModel.outputStride, s, p, e.scoreThreshold, e.refineSteps, e.minKeypointScore, e.maxDetections)
|
|
];
|
|
case 2:
|
|
return _ = A.sent(), h.dispose(), v.dispose(), w.dispose(), y.dispose(), b.dispose(), S.dispose(), x.dispose(), M.dispose(), [
|
|
2,
|
|
_
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}, t.prototype.dispose = function() {
|
|
this.baseModel.dispose();
|
|
}, t;
|
|
}();
|
|
function Xt(e) {
|
|
return D(this, void 0, void 0, function() {
|
|
var n, r, i, o, a, s;
|
|
return B(this, function(u) {
|
|
switch(u.label){
|
|
case 0:
|
|
if (n = e.outputStride, r = e.quantBytes, i = e.multiplier, null == _tfjsCore) throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n model.");
|
|
return o = function(t, e, n) {
|
|
var r = {
|
|
1: "100",
|
|
.75: "075",
|
|
.5: "050"
|
|
}, i = "model-stride" + t + ".json";
|
|
return 4 === n ? It + "float/" + r[e] + "/" + i : It + "quant" + n + "/" + r[e] + "/" + i;
|
|
}(n, i, r), [
|
|
4,
|
|
(0, _tfjsConverter.loadGraphModel)(e.modelUrl || o)
|
|
];
|
|
case 1:
|
|
return a = u.sent(), s = new Y(a, n), [
|
|
2,
|
|
new Qt(s)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Yt(e) {
|
|
return D(this, void 0, void 0, function() {
|
|
var n, r, i, o, a;
|
|
return B(this, function(s) {
|
|
switch(s.label){
|
|
case 0:
|
|
if (n = e.outputStride, r = e.quantBytes, null == _tfjsCore) throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n model.");
|
|
return i = function(t, e) {
|
|
var n = "model-stride" + t + ".json";
|
|
return 4 === e ? Pt + "float/" + n : Pt + "quant" + e + "/" + n;
|
|
}(n, r), [
|
|
4,
|
|
(0, _tfjsConverter.loadGraphModel)(e.modelUrl || i)
|
|
];
|
|
case 1:
|
|
return o = s.sent(), a = new Tt(o, n), [
|
|
2,
|
|
new Qt(a)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Gt(t) {
|
|
return void 0 === t && (t = Lt), D(this, void 0, void 0, function() {
|
|
return B(this, function(e) {
|
|
return "ResNet50" === (t = function(t) {
|
|
if (null == (t = t || Lt).architecture && (t.architecture = "MobileNetV1"), zt.indexOf(t.architecture) < 0) throw new Error("Invalid architecture " + t.architecture + ". Should be one of " + zt);
|
|
if (null == t.outputStride && (t.outputStride = 16), Wt[t.architecture].indexOf(t.outputStride) < 0) throw new Error("Invalid outputStride " + t.outputStride + ". Should be one of " + Wt[t.architecture] + " for architecture " + t.architecture + ".");
|
|
if (null == t.multiplier && (t.multiplier = 1), jt[t.architecture].indexOf(t.multiplier) < 0) throw new Error("Invalid multiplier " + t.multiplier + ". Should be one of " + jt[t.architecture] + " for architecture " + t.architecture + ".");
|
|
if (null == t.quantBytes && (t.quantBytes = 4), Vt.indexOf(t.quantBytes) < 0) throw new Error("Invalid quantBytes " + t.quantBytes + ". Should be one of " + Vt + " for architecture " + t.architecture + ".");
|
|
return t;
|
|
}(t)).architecture ? [
|
|
2,
|
|
Yt(t)
|
|
] : "MobileNetV1" === t.architecture ? [
|
|
2,
|
|
Xt(t)
|
|
] : [
|
|
2,
|
|
null
|
|
];
|
|
});
|
|
});
|
|
}
|
|
var $t = [
|
|
"left_face",
|
|
"right_face",
|
|
"left_upper_arm_front",
|
|
"left_upper_arm_back",
|
|
"right_upper_arm_front",
|
|
"right_upper_arm_back",
|
|
"left_lower_arm_front",
|
|
"left_lower_arm_back",
|
|
"right_lower_arm_front",
|
|
"right_lower_arm_back",
|
|
"left_hand",
|
|
"right_hand",
|
|
"torso_front",
|
|
"torso_back",
|
|
"left_upper_leg_front",
|
|
"left_upper_leg_back",
|
|
"right_upper_leg_front",
|
|
"right_upper_leg_back",
|
|
"left_lower_leg_front",
|
|
"left_lower_leg_back",
|
|
"right_lower_leg_front",
|
|
"right_lower_leg_back",
|
|
"left_feet",
|
|
"right_feet"
|
|
], Jt = function() {
|
|
function t(t) {
|
|
this.mask = t;
|
|
}
|
|
return t.prototype.toCanvasImageSource = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
z(this.mask)
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.toImageData = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
this.mask
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.toTensor = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
j(this.mask)
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.getUnderlyingType = function() {
|
|
return "imagedata";
|
|
}, t;
|
|
}();
|
|
function Zt(t) {
|
|
if (V(t), 255 !== t) throw new Error("Foreground id must be 255 but got " + t);
|
|
return "person";
|
|
}
|
|
function te(t) {
|
|
if (V(t), t >= $t.length) throw new Error("Invalid body part value " + t);
|
|
return $t[t];
|
|
}
|
|
var ee = function() {
|
|
function t(t) {
|
|
this.bodyPixModel = t;
|
|
}
|
|
return t.prototype.segmentPeople = function(t, e) {
|
|
return D(this, void 0, void 0, function() {
|
|
var n, r, i, o;
|
|
return B(this, function(a) {
|
|
switch(a.label){
|
|
case 0:
|
|
return t instanceof ImageBitmap && ((n = document.createElement("canvas")).getContext("2d").drawImage(t, 0, 0), t = n), e.segmentBodyParts ? e.multiSegmentation ? [
|
|
4,
|
|
this.bodyPixModel.segmentMultiPersonParts(t, e)
|
|
] : [
|
|
3,
|
|
2
|
|
] : [
|
|
3,
|
|
5
|
|
];
|
|
case 1:
|
|
return i = a.sent(), [
|
|
3,
|
|
4
|
|
];
|
|
case 2:
|
|
return [
|
|
4,
|
|
this.bodyPixModel.segmentPersonParts(t, e)
|
|
];
|
|
case 3:
|
|
i = [
|
|
a.sent()
|
|
], a.label = 4;
|
|
case 4:
|
|
return r = i.map(function(t) {
|
|
var e = t.data, n = t.width, r = t.height, i = new Uint8ClampedArray(n * r * 4).fill(0);
|
|
return e.forEach(function(t, e) {
|
|
-1 === t ? (i[4 * e] = $t.length, i[4 * e + 3] = 0) : (i[4 * e] = t, i[4 * e + 3] = 255);
|
|
}), {
|
|
maskValueToLabel: te,
|
|
mask: new Jt(new ImageData(i, n, r))
|
|
};
|
|
}), [
|
|
3,
|
|
10
|
|
];
|
|
case 5:
|
|
return e.multiSegmentation ? [
|
|
4,
|
|
this.bodyPixModel.segmentMultiPerson(t, e)
|
|
] : [
|
|
3,
|
|
7
|
|
];
|
|
case 6:
|
|
return o = a.sent(), [
|
|
3,
|
|
9
|
|
];
|
|
case 7:
|
|
return [
|
|
4,
|
|
this.bodyPixModel.segmentPerson(t, e)
|
|
];
|
|
case 8:
|
|
o = [
|
|
a.sent()
|
|
], a.label = 9;
|
|
case 9:
|
|
r = o.map(function(t) {
|
|
var e = t.data, n = t.width, r = t.height, i = new Uint8ClampedArray(n * r * 4).fill(0);
|
|
return e.forEach(function(t, e) {
|
|
0 === t ? (i[4 * e] = 0, i[4 * e + 3] = 0) : (i[4 * e] = 255, i[4 * e + 3] = 255);
|
|
}), {
|
|
maskValueToLabel: Zt,
|
|
mask: new Jt(new ImageData(i, n, r))
|
|
};
|
|
}), a.label = 10;
|
|
case 10:
|
|
return [
|
|
2,
|
|
r
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}, t.prototype.dispose = function() {
|
|
this.bodyPixModel.dispose();
|
|
}, t.prototype.reset = function() {}, t;
|
|
}();
|
|
function ne(t) {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(e) {
|
|
return [
|
|
2,
|
|
Gt(t).then(function(t) {
|
|
return new ee(t);
|
|
})
|
|
];
|
|
});
|
|
});
|
|
}
|
|
var re = {
|
|
runtime: "mediapipe",
|
|
modelType: "general"
|
|
};
|
|
var ie = function() {
|
|
function t(t) {
|
|
this.mask = t;
|
|
}
|
|
return t.prototype.toCanvasImageSource = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
this.mask
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.toImageData = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
W(this.mask)
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.toTensor = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
j(this.mask)
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.getUnderlyingType = function() {
|
|
return "canvasimagesource";
|
|
}, t;
|
|
}();
|
|
function oe(t) {
|
|
return V(t), "person";
|
|
}
|
|
var ae = function() {
|
|
function t(t) {
|
|
var e, n = this;
|
|
this.selfieMode = !1;
|
|
var r;
|
|
if (this.selfieSegmentationSolution = new (0, _selfieSegmentation.SelfieSegmentation)({
|
|
locateFile: null !== (e = t.locateFile) && void 0 !== e ? e : function(e, n) {
|
|
return t.solutionPath ? t.solutionPath.replace(/\/+$/, "") + "/" + e : n + "/" + e;
|
|
}
|
|
}), "landscape" === t.modelType) r = 1;
|
|
else r = 0;
|
|
this.selfieSegmentationSolution.setOptions({
|
|
modelSelection: r,
|
|
selfieMode: this.selfieMode
|
|
}), this.selfieSegmentationSolution.onResults(function(t) {
|
|
n.segmentation = [
|
|
{
|
|
maskValueToLabel: oe,
|
|
mask: new ie(t.segmentationMask)
|
|
}
|
|
];
|
|
});
|
|
}
|
|
return t.prototype.segmentPeople = function(t, r) {
|
|
return D(this, void 0, void 0, function() {
|
|
var i, o;
|
|
return B(this, function(a) {
|
|
switch(a.label){
|
|
case 0:
|
|
return r && r.flipHorizontal && r.flipHorizontal !== this.selfieMode && (this.selfieMode = r.flipHorizontal, this.selfieSegmentationSolution.setOptions({
|
|
selfieMode: this.selfieMode
|
|
})), t instanceof (0, _tfjsCore.Tensor) ? (o = ImageData.bind, [
|
|
4,
|
|
(0, _tfjsCore.browser).toPixels(t)
|
|
]) : [
|
|
3,
|
|
2
|
|
];
|
|
case 1:
|
|
return i = new (o.apply(ImageData, [
|
|
void 0,
|
|
a.sent(),
|
|
t.shape[1],
|
|
t.shape[0]
|
|
])), [
|
|
3,
|
|
3
|
|
];
|
|
case 2:
|
|
i = t, a.label = 3;
|
|
case 3:
|
|
return t = i, [
|
|
4,
|
|
this.selfieSegmentationSolution.send({
|
|
image: t
|
|
})
|
|
];
|
|
case 4:
|
|
return a.sent(), [
|
|
2,
|
|
this.segmentation
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}, t.prototype.dispose = function() {
|
|
this.selfieSegmentationSolution.close();
|
|
}, t.prototype.reset = function() {
|
|
this.selfieSegmentationSolution.reset(), this.segmentation = null, this.selfieMode = !1;
|
|
}, t.prototype.initialize = function() {
|
|
return this.selfieSegmentationSolution.initialize();
|
|
}, t;
|
|
}();
|
|
function se(t) {
|
|
return D(this, void 0, void 0, function() {
|
|
var e, n;
|
|
return B(this, function(r) {
|
|
switch(r.label){
|
|
case 0:
|
|
return e = function(t) {
|
|
if (null == t) return C({}, re);
|
|
var e = C({}, t);
|
|
return e.runtime = "mediapipe", null == e.modelType && (e.modelType = re.modelType), e;
|
|
}(t), [
|
|
4,
|
|
(n = new ae(e)).initialize()
|
|
];
|
|
case 1:
|
|
return r.sent(), [
|
|
2,
|
|
n
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function ue(t, e, n, r) {
|
|
var i = t.width, o = t.height, a = r ? -1 : 1, s = Math.cos(t.rotation), u = Math.sin(t.rotation), f = t.xCenter, l = t.yCenter, c = 1 / e, d = 1 / n, h = new Array(16);
|
|
return h[0] = i * s * a * c, h[1] = -o * u * c, h[2] = 0, h[3] = (-0.5 * i * s * a + .5 * o * u + f) * c, h[4] = i * u * a * d, h[5] = o * s * d, h[6] = 0, h[7] = (-0.5 * o * s - .5 * i * u * a + l) * d, h[8] = 0, h[9] = 0, h[10] = i * c, h[11] = 0, h[12] = 0, h[13] = 0, h[14] = 0, h[15] = 1, function(t) {
|
|
if (16 !== t.length) throw new Error("Array length must be 16 but got " + t.length);
|
|
return [
|
|
[
|
|
t[0],
|
|
t[1],
|
|
t[2],
|
|
t[3]
|
|
],
|
|
[
|
|
t[4],
|
|
t[5],
|
|
t[6],
|
|
t[7]
|
|
],
|
|
[
|
|
t[8],
|
|
t[9],
|
|
t[10],
|
|
t[11]
|
|
],
|
|
[
|
|
t[12],
|
|
t[13],
|
|
t[14],
|
|
t[15]
|
|
]
|
|
];
|
|
}(h);
|
|
}
|
|
function fe(t) {
|
|
return t instanceof (0, _tfjsCore.Tensor) ? {
|
|
height: t.shape[0],
|
|
width: t.shape[1]
|
|
} : {
|
|
height: t.height,
|
|
width: t.width
|
|
};
|
|
}
|
|
function le(t, e) {
|
|
(0, _tfjsCore.util).assert(0 !== t.width, function() {
|
|
return e + " width cannot be 0.";
|
|
}), (0, _tfjsCore.util).assert(0 !== t.height, function() {
|
|
return e + " height cannot be 0.";
|
|
});
|
|
}
|
|
function ce(t, e) {
|
|
var n = function(t, e, n, r) {
|
|
var i = e - t, o = r - n;
|
|
if (0 === i) throw new Error("Original min and max are both " + t + ", range cannot be 0.");
|
|
var a = o / i;
|
|
return {
|
|
scale: a,
|
|
offset: n - t * a
|
|
};
|
|
}(0, 255, e[0], e[1]);
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
return (0, _tfjsCore.add)((0, _tfjsCore.mul)(t, n.scale), n.offset);
|
|
});
|
|
}
|
|
function de(t, o, a) {
|
|
var s = o.outputTensorSize, f = o.keepAspectRatio, l = o.borderMode, c = o.outputTensorFloatRange, d = fe(t), h = function(t, e) {
|
|
return e ? {
|
|
xCenter: e.xCenter * t.width,
|
|
yCenter: e.yCenter * t.height,
|
|
width: e.width * t.width,
|
|
height: e.height * t.height,
|
|
rotation: e.rotation
|
|
} : {
|
|
xCenter: .5 * t.width,
|
|
yCenter: .5 * t.height,
|
|
width: t.width,
|
|
height: t.height,
|
|
rotation: 0
|
|
};
|
|
}(d, a), p = function(t, e, n) {
|
|
if (void 0 === n && (n = !1), !n) return {
|
|
top: 0,
|
|
left: 0,
|
|
right: 0,
|
|
bottom: 0
|
|
};
|
|
var r = e.height, i = e.width;
|
|
le(e, "targetSize"), le(t, "roi");
|
|
var o, a, s = r / i, u = t.height / t.width, f = 0, l = 0;
|
|
return s > u ? (o = t.width, a = t.width * s, l = (1 - u / s) / 2) : (o = t.height / s, a = t.height, f = (1 - s / u) / 2), t.width = o, t.height = a, {
|
|
top: l,
|
|
left: f,
|
|
right: f,
|
|
bottom: l
|
|
};
|
|
}(h, s, f), m = ue(h, d.width, d.height, !1), g = (0, _tfjsCore.tidy)(function() {
|
|
var r, o = (r = t) instanceof (0, _tfjsCore.Tensor) ? r : (0, _tfjsCore.browser).fromPixels(r), a = (0, _tfjsCore.tensor2d)(function(t, e, n) {
|
|
return le(n, "inputResolution"), [
|
|
1 / n.width * t[0][0] * e.width,
|
|
1 / n.height * t[0][1] * e.width,
|
|
t[0][3] * e.width,
|
|
1 / n.width * t[1][0] * e.height,
|
|
1 / n.height * t[1][1] * e.height,
|
|
t[1][3] * e.height,
|
|
0,
|
|
0
|
|
];
|
|
}(m, d, s), [
|
|
1,
|
|
8
|
|
]), f = "zero" === l ? "constant" : "nearest", h = (0, _tfjsCore.image).transform((0, _tfjsCore.expandDims)((0, _tfjsCore.cast)(o, "float32")), a, "bilinear", f, 0, [
|
|
s.height,
|
|
s.width
|
|
]);
|
|
return null != c ? ce(h, c) : h;
|
|
});
|
|
return {
|
|
imageTensor: g,
|
|
padding: p,
|
|
transformationMatrix: m
|
|
};
|
|
}
|
|
function he(t, e, n) {
|
|
return (0, _tfjsCore.tidy)(function() {
|
|
var r = (0, _tfjsCore.squeeze)(t, [
|
|
0
|
|
]), i = r.shape[2];
|
|
if (1 === i) {
|
|
var o = r;
|
|
switch(e.activation){
|
|
case "none":
|
|
break;
|
|
case "sigmoid":
|
|
o = (0, _tfjsCore.sigmoid)(o);
|
|
break;
|
|
case "softmax":
|
|
throw new Error("Softmax activation requires two channels.");
|
|
default:
|
|
throw new Error("Activation not supported (" + e.activation + ")");
|
|
}
|
|
var a = n ? (0, _tfjsCore.image).resizeBilinear(o, [
|
|
n.height,
|
|
n.width
|
|
]) : o;
|
|
return (0, _tfjsCore.squeeze)(a, [
|
|
2
|
|
]);
|
|
}
|
|
throw new Error("Unsupported number of tensor channels " + i);
|
|
});
|
|
}
|
|
var pe = {
|
|
runtime: "tfjs",
|
|
modelType: "general",
|
|
modelUrl: "https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/general/1"
|
|
}, me = {
|
|
flipHorizontal: !1
|
|
}, ge = {
|
|
outputTensorSize: {
|
|
width: 256,
|
|
height: 256
|
|
},
|
|
keepAspectRatio: !1,
|
|
borderMode: "zero",
|
|
outputTensorFloatRange: [
|
|
0,
|
|
1
|
|
]
|
|
}, ve = {
|
|
outputTensorSize: {
|
|
width: 256,
|
|
height: 144
|
|
},
|
|
keepAspectRatio: !1,
|
|
borderMode: "zero",
|
|
outputTensorFloatRange: [
|
|
0,
|
|
1
|
|
]
|
|
}, we = {
|
|
activation: "none"
|
|
};
|
|
var ye = function() {
|
|
function t(t) {
|
|
this.mask = t;
|
|
}
|
|
return t.prototype.toCanvasImageSource = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
z(this.mask)
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.toImageData = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
W(this.mask)
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.toTensor = function() {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(t) {
|
|
return [
|
|
2,
|
|
this.mask
|
|
];
|
|
});
|
|
});
|
|
}, t.prototype.getUnderlyingType = function() {
|
|
return "tensor";
|
|
}, t;
|
|
}();
|
|
function be(t) {
|
|
return V(t), "person";
|
|
}
|
|
var Se, xe = function() {
|
|
function t(t, e) {
|
|
this.modelType = t, this.model = e;
|
|
}
|
|
return t.prototype.segmentPeople = function(t, e) {
|
|
return D(this, void 0, void 0, function() {
|
|
var n, i = this;
|
|
return B(this, function(o) {
|
|
return e = function(t) {
|
|
if (null == t) return C({}, me);
|
|
var e = C({}, t);
|
|
return null == e.flipHorizontal && (e.flipHorizontal = me.flipHorizontal), e;
|
|
}(e), null == t ? (this.reset(), [
|
|
2,
|
|
[]
|
|
]) : (n = (0, _tfjsCore.tidy)(function() {
|
|
var e = de(t, "general" === i.modelType ? ge : ve).imageTensor, n = (0, _tfjsCore.slice)(i.model.predict(e), [
|
|
0,
|
|
0,
|
|
0,
|
|
1
|
|
], -1), r = fe(t), o = he(n, we, r), a = (0, _tfjsCore.expandDims)(o, 2), s = (0, _tfjsCore.pad)(a, [
|
|
[
|
|
0,
|
|
0
|
|
],
|
|
[
|
|
0,
|
|
0
|
|
],
|
|
[
|
|
0,
|
|
1
|
|
]
|
|
]);
|
|
return (0, _tfjsCore.mirrorPad)(s, [
|
|
[
|
|
0,
|
|
0
|
|
],
|
|
[
|
|
0,
|
|
0
|
|
],
|
|
[
|
|
0,
|
|
2
|
|
]
|
|
], "symmetric");
|
|
}), [
|
|
2,
|
|
[
|
|
{
|
|
maskValueToLabel: be,
|
|
mask: new ye(n)
|
|
}
|
|
]
|
|
]);
|
|
});
|
|
});
|
|
}, t.prototype.dispose = function() {
|
|
this.model.dispose();
|
|
}, t.prototype.reset = function() {}, t;
|
|
}();
|
|
function Me(t) {
|
|
return D(this, void 0, void 0, function() {
|
|
var e, n, r;
|
|
return B(this, function(i) {
|
|
switch(i.label){
|
|
case 0:
|
|
return e = function(t) {
|
|
if (null == t) return C({}, pe);
|
|
var e = C({}, t);
|
|
if (e.runtime = "tfjs", null == e.modelType && (e.modelType = pe.modelType), "general" !== e.modelType && "landscape" !== e.modelType) throw new Error("Model type must be one of general or landscape, but got " + e.modelType);
|
|
null == e.modelUrl && ("general" === e.modelType ? e.modelUrl = "https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/general/1" : e.modelUrl = "https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/landscape/1");
|
|
return e;
|
|
}(t), n = "string" == typeof e.modelUrl && e.modelUrl.indexOf("https://tfhub.dev") > -1, [
|
|
4,
|
|
(0, _tfjsConverter.loadGraphModel)(e.modelUrl, {
|
|
fromTFHub: n
|
|
})
|
|
];
|
|
case 1:
|
|
return r = i.sent(), [
|
|
2,
|
|
new xe(e.modelType, r)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function ke(t, e) {
|
|
return D(this, void 0, void 0, function() {
|
|
var n, r;
|
|
return B(this, function(i) {
|
|
switch(t){
|
|
case Se.MediaPipeSelfieSegmentation:
|
|
if (n = void 0, null != (r = e)) {
|
|
if ("tfjs" === r.runtime) return [
|
|
2,
|
|
Me(r)
|
|
];
|
|
if ("mediapipe" === r.runtime) return [
|
|
2,
|
|
se(r)
|
|
];
|
|
n = r.runtime;
|
|
}
|
|
throw new Error("Expect modelConfig.runtime to be either 'tfjs' or 'mediapipe', but got " + n);
|
|
case Se.BodyPix:
|
|
return [
|
|
2,
|
|
ne(r = e)
|
|
];
|
|
default:
|
|
throw new Error(t + " is not a supported model name.");
|
|
}
|
|
});
|
|
});
|
|
}
|
|
!function(t) {
|
|
t.BodyPix = "BodyPix", t.MediaPipeSelfieSegmentation = "MediaPipeSelfieSegmentation";
|
|
}(Se || (Se = {}));
|
|
var Ee = "blurred", Te = "blurred-mask", Pe = "mask", Ie = "lowres-part-mask", Oe = "draw-image", _e = {};
|
|
function He(t, e, n, r) {
|
|
var i = t.width, o = t.height, a = e.width, s = e.height;
|
|
if (i !== a || o !== s) throw new Error("error: dimensions must match. " + n + " has dimensions " + i + "x" + o + ", " + r + " has dimensions " + a + "x" + s);
|
|
}
|
|
function Ae(t) {
|
|
if ("undefined" != typeof HTMLCanvasElement && t instanceof HTMLCanvasElement || "undefined" != typeof OffscreenCanvas && t instanceof OffscreenCanvas || "undefined" != typeof HTMLImageElement && t instanceof HTMLImageElement) return function(t) {
|
|
if ("offsetHeight" in t && 0 !== t.offsetHeight && "offsetWidth" in t && 0 !== t.offsetWidth) return [
|
|
t.offsetHeight,
|
|
t.offsetWidth
|
|
];
|
|
if (null != t.height && null != t.width) return [
|
|
t.height,
|
|
t.width
|
|
];
|
|
throw new Error("HTMLImageElement must have height and width attributes set.");
|
|
}(t);
|
|
if ("undefined" != typeof ImageData && t instanceof ImageData) return [
|
|
t.height,
|
|
t.width
|
|
];
|
|
if ("undefined" != typeof HTMLVideoElement && t instanceof HTMLVideoElement) return function(t) {
|
|
return t.hasAttribute("height") && t.hasAttribute("width") ? [
|
|
t.height,
|
|
t.width
|
|
] : [
|
|
t.videoHeight,
|
|
t.videoWidth
|
|
];
|
|
}(t);
|
|
if (t instanceof (0, _tfjsCore.Tensor)) return [
|
|
t.shape[0],
|
|
t.shape[1]
|
|
];
|
|
throw new Error("error: Unknown input type: " + t + ".");
|
|
}
|
|
function Re(t) {
|
|
return _e[t] || (_e[t] = function() {
|
|
if ("undefined" != typeof document) return document.createElement("canvas");
|
|
if ("undefined" != typeof OffscreenCanvas) return new OffscreenCanvas(0, 0);
|
|
throw new Error("Cannot create a canvas in this context");
|
|
}()), _e[t];
|
|
}
|
|
function Fe(t, e) {
|
|
var n = Re(e);
|
|
return function(t, e) {
|
|
e.width = t.width, e.height = t.height, e.getContext("2d").putImageData(t, 0, 0);
|
|
}(t, n), n;
|
|
}
|
|
function Ce(t, r, i, o, a, s) {
|
|
return D(this, void 0, void 0, function() {
|
|
var u, f, l, c;
|
|
return B(this, function(d) {
|
|
switch(d.label){
|
|
case 0:
|
|
return r instanceof (0, _tfjsCore.Tensor) ? [
|
|
4,
|
|
(0, _tfjsCore.browser).toPixels(r)
|
|
] : [
|
|
3,
|
|
2
|
|
];
|
|
case 1:
|
|
u = d.sent(), f = Ae(r), l = f[0], c = f[1], r = new ImageData(u, c, l), d.label = 2;
|
|
case 2:
|
|
return r instanceof ImageData && (r = Fe(r, Oe)), null == a || null == s ? t.drawImage(r, i, o) : t.drawImage(r, i, o, a, s), [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function De(t, e) {
|
|
return D(this, void 0, void 0, function() {
|
|
var n, r, i;
|
|
return B(this, function(o) {
|
|
switch(o.label){
|
|
case 0:
|
|
return n = Ae(t), r = n[0], i = n[1], e.width = i, e.height = r, [
|
|
4,
|
|
Ce(e.getContext("2d"), t, 0, 0, i, r)
|
|
];
|
|
case 1:
|
|
return o.sent(), [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Be(t) {
|
|
var e = t.getContext("2d");
|
|
e.scale(-1, 1), e.translate(-t.width, 0);
|
|
}
|
|
function Le(t, e, n) {
|
|
return D(this, void 0, void 0, function() {
|
|
return B(this, function(r) {
|
|
switch(r.label){
|
|
case 0:
|
|
return t.globalCompositeOperation = n, [
|
|
4,
|
|
Ce(t, e, 0, 0)
|
|
];
|
|
case 1:
|
|
return r.sent(), [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function ze(t, e, n) {
|
|
return D(this, void 0, void 0, function() {
|
|
var r, i, o, a, s, u, f, l;
|
|
return B(this, function(c) {
|
|
switch(c.label){
|
|
case 0:
|
|
for(r = t.getContext("2d"), i = 0, o = 5, a = 1 / (2 * Math.PI * o * o), s = n < 3 ? 1 : 2, f = -n; f <= n; f += s)for(l = -n; l <= n; l += s)u = a * Math.exp(-(l * l + f * f) / (2 * o * o)), i += u;
|
|
f = -n, c.label = 1;
|
|
case 1:
|
|
if (!(f <= n)) return [
|
|
3,
|
|
6
|
|
];
|
|
l = -n, c.label = 2;
|
|
case 2:
|
|
return l <= n ? (r.globalAlpha = a * Math.exp(-(l * l + f * f) / (2 * o * o)) / i * n, [
|
|
4,
|
|
Ce(r, e, l, f)
|
|
]) : [
|
|
3,
|
|
5
|
|
];
|
|
case 3:
|
|
c.sent(), c.label = 4;
|
|
case 4:
|
|
return l += s, [
|
|
3,
|
|
2
|
|
];
|
|
case 5:
|
|
return f += s, [
|
|
3,
|
|
1
|
|
];
|
|
case 6:
|
|
return r.globalAlpha = 1, [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function We(t, e, n) {
|
|
return D(this, void 0, void 0, function() {
|
|
var r, i, o, a;
|
|
return B(this, function(s) {
|
|
switch(s.label){
|
|
case 0:
|
|
return r = Ae(t), i = r[0], o = r[1], a = n.getContext("2d"), n.width = o, n.height = i, a.clearRect(0, 0, o, i), a.save(), /^((?!chrome|android).)*safari/i.test(navigator.userAgent) ? [
|
|
4,
|
|
ze(n, t, e)
|
|
] : [
|
|
3,
|
|
2
|
|
];
|
|
case 1:
|
|
return s.sent(), [
|
|
3,
|
|
4
|
|
];
|
|
case 2:
|
|
return a.filter = "blur(" + e + "px)", [
|
|
4,
|
|
Ce(a, t, 0, 0, o, i)
|
|
];
|
|
case 3:
|
|
s.sent(), s.label = 4;
|
|
case 4:
|
|
return a.restore(), [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function je(t, e, n) {
|
|
return D(this, void 0, void 0, function() {
|
|
var r;
|
|
return B(this, function(i) {
|
|
switch(i.label){
|
|
case 0:
|
|
return r = Re(n), 0 !== e ? [
|
|
3,
|
|
2
|
|
] : [
|
|
4,
|
|
De(t, r)
|
|
];
|
|
case 1:
|
|
return i.sent(), [
|
|
3,
|
|
4
|
|
];
|
|
case 2:
|
|
return [
|
|
4,
|
|
We(t, e, r)
|
|
];
|
|
case 3:
|
|
i.sent(), i.label = 4;
|
|
case 4:
|
|
return [
|
|
2,
|
|
r
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Ve(t, e, n, r, i, o) {
|
|
void 0 === o && (o = {
|
|
r: 0,
|
|
g: 255,
|
|
b: 255,
|
|
a: 255
|
|
});
|
|
for(var a = -i; a <= i; a++)for(var s = -i; s <= i; s++)if (0 !== a && 0 !== s) {
|
|
var u = (e + a) * r + (n + s);
|
|
t[4 * u + 0] = o.r, t[4 * u + 1] = o.g, t[4 * u + 2] = o.b, t[4 * u + 3] = o.a;
|
|
}
|
|
}
|
|
function Ke(t, e, n, r, i, o, a) {
|
|
void 0 === a && (a = 1);
|
|
for(var s = 0, u = -a; u <= a; u++)for(var f = -a; f <= a; f++)if (0 !== u && 0 !== f) {
|
|
var l = (e + u) * r + (n + f);
|
|
(!i[t[4 * l]] || t[4 * l + 3] < o) && (s += 1);
|
|
}
|
|
return s > 0;
|
|
}
|
|
function Ue(t, e, n, r, i, o) {
|
|
return void 0 === e && (e = {
|
|
r: 0,
|
|
g: 0,
|
|
b: 0,
|
|
a: 0
|
|
}), void 0 === n && (n = {
|
|
r: 0,
|
|
g: 0,
|
|
b: 0,
|
|
a: 255
|
|
}), void 0 === r && (r = !1), void 0 === i && (i = .5), void 0 === o && (o = Array.from(Array(256).keys())), D(this, void 0, void 0, function() {
|
|
var a, s, u, f, l, c, d, h, p, m, g, v, w, y;
|
|
return B(this, function(b) {
|
|
switch(b.label){
|
|
case 0:
|
|
return 0 === (a = Array.isArray(t) ? t : [
|
|
t
|
|
]).length ? [
|
|
2,
|
|
null
|
|
] : [
|
|
4,
|
|
Promise.all(a.map(function(t) {
|
|
return t.mask.toImageData();
|
|
}))
|
|
];
|
|
case 1:
|
|
for(s = b.sent(), u = s[0], f = u.width, l = u.height, c = new Uint8ClampedArray(f * l * 4), d = Math.round(255 * i), h = new Array(256).fill(!1), o.forEach(function(t) {
|
|
return h[t] = !0;
|
|
}), p = 0; p < l; p++)for(m = 0; m < f; m++)for(c[4 * (g = p * f + m) + 0] = n.r, c[4 * g + 1] = n.g, c[4 * g + 2] = n.b, c[4 * g + 3] = n.a, v = 0, w = s; v < w.length; v++)y = w[v], h[y.data[4 * g]] && y.data[4 * g + 3] >= d && (c[4 * g] = e.r, c[4 * g + 1] = e.g, c[4 * g + 2] = e.b, c[4 * g + 3] = e.a, r && p - 1 >= 0 && p + 1 < l && m - 1 >= 0 && m + 1 < f && Ke(y.data, p, m, f, h, d) && Ve(c, p, m, f, 1));
|
|
return [
|
|
2,
|
|
new ImageData(c, f, l)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function qe(t, e, n, r) {
|
|
return void 0 === n && (n = {
|
|
r: 0,
|
|
g: 0,
|
|
b: 0,
|
|
a: 255
|
|
}), void 0 === r && (r = .5), D(this, void 0, void 0, function() {
|
|
var i, o, a, s, u, f, l, c, d, h, p, m, g, v;
|
|
return B(this, function(w) {
|
|
switch(w.label){
|
|
case 0:
|
|
return 0 === (i = Array.isArray(t) ? t : [
|
|
t
|
|
]).length ? [
|
|
2,
|
|
null
|
|
] : [
|
|
4,
|
|
Promise.all(i.map(function(t) {
|
|
return t.mask.toImageData();
|
|
}))
|
|
];
|
|
case 1:
|
|
for(o = w.sent(), a = o[0], s = a.width, u = a.height, f = new Uint8ClampedArray(s * u * 4), l = Math.round(255 * r), c = 0; c < u * s; ++c)for(f[(d = 4 * c) + 0] = n.r, f[d + 1] = n.g, f[d + 2] = n.b, f[d + 3] = n.a, h = 0, p = o; h < p.length; h++)(m = p[h]).data[d + 3] >= l && (g = m.data[d], v = e(g), f[d + 0] = v.r, f[d + 1] = v.g, f[d + 2] = v.b, f[d + 3] = v.a);
|
|
return [
|
|
2,
|
|
new ImageData(f, s, u)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Ne(t, e, n, r, i, o) {
|
|
return void 0 === r && (r = .7), void 0 === i && (i = 0), void 0 === o && (o = !1), D(this, void 0, void 0, function() {
|
|
var a, s, u, f, l;
|
|
return B(this, function(c) {
|
|
switch(c.label){
|
|
case 0:
|
|
return a = Ae(e), s = a[0], u = a[1], t.width = u, t.height = s, (f = t.getContext("2d")).save(), o && Be(t), [
|
|
4,
|
|
Ce(f, e, 0, 0)
|
|
];
|
|
case 1:
|
|
return c.sent(), f.globalAlpha = r, n ? (He({
|
|
width: u,
|
|
height: s
|
|
}, n, "image", "mask"), [
|
|
4,
|
|
je(Fe(n, Pe), i, Te)
|
|
]) : [
|
|
3,
|
|
3
|
|
];
|
|
case 2:
|
|
l = c.sent(), f.drawImage(l, 0, 0, u, s), c.label = 3;
|
|
case 3:
|
|
return f.restore(), [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Qe(t, e, n, r, i, o, a) {
|
|
return void 0 === r && (r = .7), void 0 === i && (i = 0), void 0 === o && (o = !1), void 0 === a && (a = 10), D(this, void 0, void 0, function() {
|
|
var s, u, f, l, c, d, h;
|
|
return B(this, function(p) {
|
|
switch(p.label){
|
|
case 0:
|
|
return s = Ae(e), u = s[0], He({
|
|
width: s[1],
|
|
height: u
|
|
}, n, "image", "mask"), [
|
|
4,
|
|
je(Fe(n, Pe), i, Te)
|
|
];
|
|
case 1:
|
|
for(f = p.sent(), t.width = f.width, t.height = f.height, (l = t.getContext("2d")).save(), o && Be(t), c = Re(Ie), d = c.getContext("2d"), c.width = f.width * (1 / a), c.height = f.height * (1 / a), d.drawImage(f, 0, 0, f.width, f.height, 0, 0, c.width, c.height), l.imageSmoothingEnabled = !1, l.drawImage(c, 0, 0, c.width, c.height, 0, 0, t.width, t.height), h = 0; h < c.width; h++)l.beginPath(), l.strokeStyle = "#ffffff", l.moveTo(a * h, 0), l.lineTo(a * h, t.height), l.stroke();
|
|
for(h = 0; h < c.height; h++)l.beginPath(), l.strokeStyle = "#ffffff", l.moveTo(0, a * h), l.lineTo(t.width, a * h), l.stroke();
|
|
return l.globalAlpha = 1 - r, [
|
|
4,
|
|
Ce(l, e, 0, 0, f.width, f.height)
|
|
];
|
|
case 2:
|
|
return p.sent(), l.restore(), [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Xe(t, e, n) {
|
|
return D(this, void 0, void 0, function() {
|
|
var r, i;
|
|
return B(this, function(o) {
|
|
switch(o.label){
|
|
case 0:
|
|
return [
|
|
4,
|
|
Ue(t, {
|
|
r: 0,
|
|
g: 0,
|
|
b: 0,
|
|
a: 255
|
|
}, {
|
|
r: 0,
|
|
g: 0,
|
|
b: 0,
|
|
a: 0
|
|
}, !1, e)
|
|
];
|
|
case 1:
|
|
return r = o.sent(), i = Fe(r, Pe), 0 === n ? [
|
|
2,
|
|
i
|
|
] : [
|
|
2,
|
|
je(i, n, Te)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Ye(t, e, n, r, i, o, a) {
|
|
return void 0 === r && (r = .5), void 0 === i && (i = 3), void 0 === o && (o = 3), void 0 === a && (a = !1), D(this, void 0, void 0, function() {
|
|
var s, u, f, l, c, d;
|
|
return B(this, function(h) {
|
|
switch(h.label){
|
|
case 0:
|
|
return [
|
|
4,
|
|
je(e, i, Ee)
|
|
];
|
|
case 1:
|
|
return s = h.sent(), t.width = s.width, t.height = s.height, u = t.getContext("2d"), Array.isArray(n) && 0 === n.length ? (u.drawImage(s, 0, 0), [
|
|
2
|
|
]) : [
|
|
4,
|
|
Xe(n, r, o)
|
|
];
|
|
case 2:
|
|
return f = h.sent(), u.save(), a && Be(t), l = Ae(e), c = l[0], d = l[1], [
|
|
4,
|
|
Ce(u, e, 0, 0, d, c)
|
|
];
|
|
case 3:
|
|
return h.sent(), [
|
|
4,
|
|
Le(u, f, "destination-in")
|
|
];
|
|
case 4:
|
|
return h.sent(), [
|
|
4,
|
|
Le(u, s, "destination-over")
|
|
];
|
|
case 5:
|
|
return h.sent(), u.restore(), [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function Ge(t, e, n, r) {
|
|
return D(this, void 0, void 0, function() {
|
|
var i, o;
|
|
return B(this, function(a) {
|
|
switch(a.label){
|
|
case 0:
|
|
return [
|
|
4,
|
|
Ue(t, {
|
|
r: 0,
|
|
g: 0,
|
|
b: 0,
|
|
a: 0
|
|
}, {
|
|
r: 0,
|
|
g: 0,
|
|
b: 0,
|
|
a: 255
|
|
}, !0, n, e)
|
|
];
|
|
case 1:
|
|
return i = a.sent(), o = Fe(i, Pe), 0 === r ? [
|
|
2,
|
|
o
|
|
] : [
|
|
2,
|
|
je(o, r, Te)
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function $e(t, e, n, r, i, o, a, s) {
|
|
return void 0 === i && (i = .5), void 0 === o && (o = 3), void 0 === a && (a = 3), void 0 === s && (s = !1), D(this, void 0, void 0, function() {
|
|
var u, f, l, c, d, h;
|
|
return B(this, function(p) {
|
|
switch(p.label){
|
|
case 0:
|
|
return [
|
|
4,
|
|
je(e, o, Ee)
|
|
];
|
|
case 1:
|
|
return u = p.sent(), t.width = u.width, t.height = u.height, f = t.getContext("2d"), Array.isArray(n) && 0 === n.length ? (f.drawImage(u, 0, 0), [
|
|
2
|
|
]) : [
|
|
4,
|
|
Ge(n, r, i, a)
|
|
];
|
|
case 2:
|
|
return l = p.sent(), f.save(), s && Be(t), c = Ae(e), d = c[0], h = c[1], [
|
|
4,
|
|
Ce(f, e, 0, 0, h, d)
|
|
];
|
|
case 3:
|
|
return p.sent(), [
|
|
4,
|
|
Le(f, l, "destination-in")
|
|
];
|
|
case 4:
|
|
return p.sent(), [
|
|
4,
|
|
Le(f, u, "destination-over")
|
|
];
|
|
case 5:
|
|
return p.sent(), f.restore(), [
|
|
2
|
|
];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@tensorflow/tfjs-converter":"g4re1","@mediapipe/selfie_segmentation":"j6iw2","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g4re1":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "GraphModel", ()=>(0, _graphModel.GraphModel));
|
|
parcelHelpers.export(exports, "loadGraphModel", ()=>(0, _graphModel.loadGraphModel));
|
|
parcelHelpers.export(exports, "loadGraphModelSync", ()=>(0, _graphModel.loadGraphModelSync));
|
|
parcelHelpers.export(exports, "deregisterOp", ()=>(0, _register.deregisterOp));
|
|
parcelHelpers.export(exports, "registerOp", ()=>(0, _register.registerOp));
|
|
parcelHelpers.export(exports, "version_converter", ()=>(0, _version.version));
|
|
var _flags = require("./flags");
|
|
var _graphModel = require("./executor/graph_model");
|
|
var _register = require("./operations/custom_op/register");
|
|
var _version = require("./version");
|
|
|
|
},{"./flags":"angKf","./executor/graph_model":"e4ep5","./operations/custom_op/register":"fBdpJ","./version":"by8XT","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"angKf":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const ENV = (0, _tfjsCore.env)();
|
|
/** Whether to keep intermediate tensors. */ ENV.registerFlag("KEEP_INTERMEDIATE_TENSORS", ()=>false, (debugValue)=>{
|
|
if (debugValue) console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.");
|
|
});
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl"}],"e4ep5":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "TFHUB_SEARCH_PARAM", ()=>TFHUB_SEARCH_PARAM);
|
|
parcelHelpers.export(exports, "DEFAULT_MODEL_NAME", ()=>DEFAULT_MODEL_NAME);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "GraphModel", ()=>GraphModel);
|
|
/**
|
|
* 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'}
|
|
*/ parcelHelpers.export(exports, "loadGraphModel", ()=>loadGraphModel);
|
|
/**
|
|
* Load a graph model given a synchronous IO handler with a 'load' method.
|
|
*
|
|
* @param modelSource The `io.IOHandlerSync` that loads the model, or the
|
|
* `io.ModelArtifacts` that encode the model, or a tuple of
|
|
* `[io.ModelJSON, ArrayBuffer]` of which the first element encodes the
|
|
* model and the second contains the weights.
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Loading'}
|
|
*/ parcelHelpers.export(exports, "loadGraphModelSync", ()=>loadGraphModelSync);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _operationMapper = require("../operations/operation_mapper");
|
|
var _graphExecutor = require("./graph_executor");
|
|
var _resourceManager = require("./resource_manager");
|
|
// tslint:disable-next-line: no-imports-from-dist
|
|
var _ioUtils = require("@tensorflow/tfjs-core/dist/io/io_utils");
|
|
const TFHUB_SEARCH_PARAM = "?tfjs-format=file";
|
|
const DEFAULT_MODEL_NAME = "model.json";
|
|
class GraphModel {
|
|
// 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;
|
|
}
|
|
get metadata() {
|
|
return this.artifacts.userDefinedMetadata;
|
|
}
|
|
get modelSignature() {
|
|
return this.signature;
|
|
}
|
|
get modelStructuredOutputKeys() {
|
|
return this.structuredOutputKeys;
|
|
}
|
|
/**
|
|
* @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 = {}, tfio = (0, _tfjsCore.io)){
|
|
this.modelUrl = modelUrl;
|
|
this.loadOptions = loadOptions;
|
|
this.version = "n/a";
|
|
this.io = tfio;
|
|
if (loadOptions == null) this.loadOptions = {};
|
|
this.resourceManager = new (0, _resourceManager.ResourceManager)();
|
|
}
|
|
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 = this.io.browserHTTPRequest(path, this.loadOptions);
|
|
else {
|
|
const handlers = this.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(this.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.
|
|
*/ 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 loadResult = this.handler.load();
|
|
if ((0, _tfjsCore.util).isPromise(loadResult)) return loadResult.then((artifacts)=>{
|
|
if (artifacts.getWeightStream == null) return this.loadSync(artifacts);
|
|
return this.loadStreaming(artifacts);
|
|
});
|
|
return this.loadSync(loadResult);
|
|
}
|
|
/**
|
|
* Synchronously construct the in memory weight map and
|
|
* compile the inference graph.
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
|
|
*/ loadSync(artifacts) {
|
|
const weightMap = this.io.decodeWeights(artifacts.weightData, artifacts.weightSpecs);
|
|
return this.loadWithWeightMap(artifacts, weightMap);
|
|
}
|
|
async loadStreaming(artifacts) {
|
|
if (artifacts.getWeightStream == null) throw new Error("Model artifacts missing streamWeights function");
|
|
const weightMap = await (0, _ioUtils.decodeWeightsStream)(artifacts.getWeightStream(), artifacts.weightSpecs);
|
|
return this.loadWithWeightMap(artifacts, weightMap);
|
|
}
|
|
loadWithWeightMap(artifacts, weightMap) {
|
|
this.artifacts = artifacts;
|
|
const graph = this.artifacts.modelTopology;
|
|
let signature = this.artifacts.signature;
|
|
if (this.artifacts.userDefinedMetadata != null) {
|
|
const metadata = this.artifacts.userDefinedMetadata;
|
|
if (metadata.signature != null) signature = metadata.signature;
|
|
if (metadata.structuredOutputKeys != null) this.structuredOutputKeys = metadata.structuredOutputKeys;
|
|
}
|
|
this.signature = signature;
|
|
this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`;
|
|
this.executor = new (0, _graphExecutor.GraphExecutor)((0, _operationMapper.OperationMapper).Instance.transformGraph(graph, this.signature));
|
|
this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);
|
|
// Attach a model-level resourceManager to each executor to share resources,
|
|
// such as `HashTable`.
|
|
this.executor.resourceManager = this.resourceManager;
|
|
if (artifacts.modelInitializer != null && artifacts.modelInitializer.node != null) {
|
|
const initializer = (0, _operationMapper.OperationMapper).Instance.transformGraph(artifacts.modelInitializer);
|
|
this.initializer = new (0, _graphExecutor.GraphExecutor)(initializer);
|
|
this.initializer.weightMap = this.executor.weightMap;
|
|
// Attach a model-level resourceManager to the initializer, the
|
|
// hashTables created from when executing the initializer will be stored
|
|
// in the resourceManager.
|
|
this.initializer.resourceManager = this.resourceManager;
|
|
this.initializerSignature = artifacts.initializerSignature;
|
|
}
|
|
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 = this.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);
|
|
}
|
|
addStructuredOutputNames(outputTensors) {
|
|
if (this.structuredOutputKeys) {
|
|
const outputTensorsArray = outputTensors instanceof (0, _tfjsCore.Tensor) ? [
|
|
outputTensors
|
|
] : outputTensors;
|
|
const outputTensorMap = {};
|
|
outputTensorsArray.forEach((outputTensor, i)=>outputTensorMap[this.structuredOutputKeys[i]] = outputTensor);
|
|
return outputTensorMap;
|
|
}
|
|
return outputTensors;
|
|
}
|
|
/**
|
|
* 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 multiple 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.
|
|
* Currently the batch size option is ignored for graph model.
|
|
*
|
|
* @returns Inference result tensors. If the model is converted and it
|
|
* originally had structured_outputs in tensorflow, then a NamedTensorMap
|
|
* will be returned matching the structured_outputs. If no structured_outputs
|
|
* are present, the output will be single `tf.Tensor` if the model has single
|
|
* output node, otherwise Tensor[].
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Classes'}
|
|
*/ predict(inputs, config) {
|
|
const outputTensors = this.execute(inputs, this.outputNodes);
|
|
return this.addStructuredOutputNames(outputTensors);
|
|
}
|
|
/**
|
|
* Execute the inference for the input tensors in async fashion, use this
|
|
* method when your model contains control flow ops.
|
|
*
|
|
* @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.
|
|
* Currently the batch size option is ignored for graph model.
|
|
*
|
|
* @returns A Promise of inference result tensors. If the model is converted
|
|
* and it originally had structured_outputs in tensorflow, then a
|
|
* NamedTensorMap will be returned matching the structured_outputs. If no
|
|
* structured_outputs are present, the output will be single `tf.Tensor` if
|
|
* the model has single output node, otherwise Tensor[].
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Classes'}
|
|
*/ async predictAsync(inputs, config) {
|
|
const outputTensors = await this.executeAsync(inputs, this.outputNodes);
|
|
return this.addStructuredOutputNames(outputTensors);
|
|
}
|
|
normalizeInputs(inputs) {
|
|
var _a;
|
|
if (!(inputs instanceof (0, _tfjsCore.Tensor)) && !Array.isArray(inputs)) {
|
|
// The input is already a NamedTensorMap.
|
|
const signatureInputs = (_a = this.signature) === null || _a === void 0 ? void 0 : _a.inputs;
|
|
if (signatureInputs != null) for(const input in signatureInputs){
|
|
const tensor = signatureInputs[input];
|
|
if (tensor.resourceId != null) inputs[input] = this.resourceIdToCapturedInput[tensor.resourceId];
|
|
}
|
|
return inputs;
|
|
}
|
|
inputs = Array.isArray(inputs) ? inputs : [
|
|
inputs
|
|
];
|
|
const numCapturedInputs = Object.keys(this.resourceIdToCapturedInput).length;
|
|
if (inputs.length + numCapturedInputs !== this.inputNodes.length) throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length - numCapturedInputs} non-resource placeholders, while there are ${inputs.length} input tensors provided.`);
|
|
let inputIndex = 0;
|
|
return this.inputNodes.reduce((map, inputName)=>{
|
|
var _a, _b, _c;
|
|
const resourceId = (_c = (_b = (_a = this.signature) === null || _a === void 0 ? void 0 : _a.inputs) === null || _b === void 0 ? void 0 : _b[inputName]) === null || _c === void 0 ? void 0 : _c.resourceId;
|
|
if (resourceId != null) map[inputName] = this.resourceIdToCapturedInput[resourceId];
|
|
else map[inputName] = inputs[inputIndex++];
|
|
return map;
|
|
}, {});
|
|
}
|
|
normalizeOutputs(outputs) {
|
|
outputs = outputs || this.outputNodes;
|
|
return !Array.isArray(outputs) ? [
|
|
outputs
|
|
] : outputs;
|
|
}
|
|
executeInitializerGraph() {
|
|
if (this.initializer == null) return [];
|
|
if (this.initializerSignature == null) return this.initializer.execute({}, []);
|
|
else return this.initializer.execute({}, Object.keys(this.initializerSignature.outputs));
|
|
}
|
|
async executeInitializerGraphAsync() {
|
|
if (this.initializer == null) return [];
|
|
if (this.initializerSignature == null) return this.initializer.executeAsync({}, []);
|
|
else return this.initializer.executeAsync({}, Object.keys(this.initializerSignature.outputs));
|
|
}
|
|
setResourceIdToCapturedInput(outputs) {
|
|
this.resourceIdToCapturedInput = {};
|
|
if (this.initializerSignature) {
|
|
const signatureOutputs = this.initializerSignature.outputs;
|
|
const outputNames = Object.keys(signatureOutputs);
|
|
for(let i = 0; i < outputNames.length; i++){
|
|
const outputName = outputNames[i];
|
|
const tensorInfo = signatureOutputs[outputName];
|
|
this.resourceIdToCapturedInput[tensorInfo.resourceId] = outputs[i];
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* 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) {
|
|
if (this.resourceIdToCapturedInput == null) this.setResourceIdToCapturedInput(this.executeInitializerGraph());
|
|
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) {
|
|
if (this.resourceIdToCapturedInput == null) this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync());
|
|
inputs = this.normalizeInputs(inputs);
|
|
outputs = this.normalizeOutputs(outputs);
|
|
const result = await this.executor.executeAsync(inputs, outputs);
|
|
return result.length > 1 ? result : result[0];
|
|
}
|
|
/**
|
|
* Get intermediate tensors for model debugging mode (flag
|
|
* KEEP_INTERMEDIATE_TENSORS is true).
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Classes'}
|
|
*/ getIntermediateTensors() {
|
|
return this.executor.getIntermediateTensors();
|
|
}
|
|
/**
|
|
* Dispose intermediate tensors for model debugging mode (flag
|
|
* KEEP_INTERMEDIATE_TENSORS is true).
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Classes'}
|
|
*/ disposeIntermediateTensors() {
|
|
this.executor.disposeIntermediateTensors();
|
|
}
|
|
convertTensorMapToTensorsMap(map) {
|
|
return Object.keys(map).reduce((newMap, key)=>{
|
|
newMap[key] = [
|
|
map[key]
|
|
];
|
|
return newMap;
|
|
}, {});
|
|
}
|
|
/**
|
|
* Releases the memory used by the weight tensors and resourceManager.
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Classes'}
|
|
*/ dispose() {
|
|
this.executor.dispose();
|
|
if (this.initializer) {
|
|
this.initializer.dispose();
|
|
if (this.resourceIdToCapturedInput) (0, _tfjsCore.dispose)(this.resourceIdToCapturedInput);
|
|
}
|
|
this.resourceManager.dispose();
|
|
}
|
|
}
|
|
async function loadGraphModel(modelUrl, options = {}, tfio = (0, _tfjsCore.io)) {
|
|
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 && typeof modelUrl === "string") modelUrl = getTFHubUrl(modelUrl);
|
|
const model = new GraphModel(modelUrl, options, tfio);
|
|
await model.load();
|
|
return model;
|
|
}
|
|
function loadGraphModelSync(modelSource) {
|
|
if (modelSource == null) throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");
|
|
let ioHandler;
|
|
if (modelSource instanceof Array) {
|
|
const [modelJSON, weights] = modelSource;
|
|
if (!modelJSON) throw new Error("modelJSON must be the first element of the array");
|
|
if (!weights || !(weights instanceof ArrayBuffer)) throw new Error("An ArrayBuffer of weights must be the second element of the array");
|
|
if (!("modelTopology" in modelJSON)) throw new Error("Model JSON is missing 'modelTopology'");
|
|
if (!("weightsManifest" in modelJSON)) throw new Error("Model JSON is missing 'weightsManifest'");
|
|
const weightSpecs = (0, _tfjsCore.io).getWeightSpecs(modelJSON.weightsManifest);
|
|
const modelArtifacts = (0, _tfjsCore.io).getModelArtifactsForJSONSync(modelJSON, weightSpecs, weights);
|
|
ioHandler = (0, _tfjsCore.io).fromMemorySync(modelArtifacts);
|
|
} else if ("load" in modelSource) // Then modelSource is already an IOHandlerSync.
|
|
ioHandler = modelSource;
|
|
else if ("modelTopology" in modelSource && "weightSpecs" in modelSource && "weightData" in modelSource) // modelSource is of type ModelArtifacts.
|
|
ioHandler = (0, _tfjsCore.io).fromMemorySync(modelSource);
|
|
else throw new Error("Unknown model format");
|
|
const model = new GraphModel(ioHandler);
|
|
model.load();
|
|
return model;
|
|
}
|
|
function getTFHubUrl(modelUrl) {
|
|
if (!modelUrl.endsWith("/")) modelUrl = modelUrl + "/";
|
|
return `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../operations/operation_mapper":"ewPe6","./graph_executor":"iu0wq","./resource_manager":"9Yk8c","@tensorflow/tfjs-core/dist/io/io_utils":"hW5iQ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ewPe6":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "OperationMapper", ()=>OperationMapper);
|
|
parcelHelpers.export(exports, "decodeBase64", ()=>decodeBase64);
|
|
parcelHelpers.export(exports, "parseStringParam", ()=>parseStringParam);
|
|
parcelHelpers.export(exports, "getStringParam", ()=>getStringParam);
|
|
parcelHelpers.export(exports, "getBoolParam", ()=>getBoolParam);
|
|
parcelHelpers.export(exports, "getNumberParam", ()=>getNumberParam);
|
|
parcelHelpers.export(exports, "parseDtypeParam", ()=>parseDtypeParam);
|
|
parcelHelpers.export(exports, "getFuncParam", ()=>getFuncParam);
|
|
parcelHelpers.export(exports, "getDtypeParam", ()=>getDtypeParam);
|
|
parcelHelpers.export(exports, "getDtypeArrayParam", ()=>getDtypeArrayParam);
|
|
parcelHelpers.export(exports, "parseTensorShapeParam", ()=>parseTensorShapeParam);
|
|
parcelHelpers.export(exports, "getTensorShapeParam", ()=>getTensorShapeParam);
|
|
parcelHelpers.export(exports, "getNumericArrayParam", ()=>getNumericArrayParam);
|
|
parcelHelpers.export(exports, "getStringArrayParam", ()=>getStringArrayParam);
|
|
parcelHelpers.export(exports, "getTensorShapeArrayParam", ()=>getTensorShapeArrayParam);
|
|
parcelHelpers.export(exports, "getBoolArrayParam", ()=>getBoolArrayParam);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _compiledApi = require("../data/compiled_api");
|
|
var _register = require("./custom_op/register");
|
|
var _utils = require("./executors/utils");
|
|
var _arithmetic = require("./op_list/arithmetic");
|
|
var _basicMath = require("./op_list/basic_math");
|
|
var _control = require("./op_list/control");
|
|
var _convolution = require("./op_list/convolution");
|
|
var _creation = require("./op_list/creation");
|
|
var _dynamic = require("./op_list/dynamic");
|
|
var _evaluation = require("./op_list/evaluation");
|
|
var _graph = require("./op_list/graph");
|
|
var _hashTable = require("./op_list/hash_table");
|
|
var _image = require("./op_list/image");
|
|
var _logical = require("./op_list/logical");
|
|
var _matrices = require("./op_list/matrices");
|
|
var _normalization = require("./op_list/normalization");
|
|
var _reduction = require("./op_list/reduction");
|
|
var _sliceJoin = require("./op_list/slice_join");
|
|
var _sparse = require("./op_list/sparse");
|
|
var _spectral = require("./op_list/spectral");
|
|
var _string = require("./op_list/string");
|
|
var _transformation = require("./op_list/transformation");
|
|
var Buffer = require("509fe566240bdc8b").Buffer;
|
|
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 = [
|
|
_arithmetic,
|
|
_basicMath,
|
|
_control,
|
|
_convolution,
|
|
_creation,
|
|
_dynamic,
|
|
_evaluation,
|
|
_graph,
|
|
_hashTable,
|
|
_image,
|
|
_logical,
|
|
_matrices,
|
|
_normalization,
|
|
_reduction,
|
|
_sliceJoin,
|
|
_sparse,
|
|
_spectral,
|
|
_string,
|
|
_transformation
|
|
];
|
|
const mappersJson = [].concat(...ops.map((op)=>op.json));
|
|
this.opMappers = mappersJson.reduce((map, mapper)=>{
|
|
map[mapper.tfOpName] = mapper;
|
|
return map;
|
|
}, {});
|
|
}
|
|
// Converts the model inference graph from Tensorflow GraphDef to local
|
|
// representation for TensorFlow.js API
|
|
transformGraph(graph, signature = {}) {
|
|
const tfNodes = graph.node;
|
|
const placeholders = [];
|
|
const weights = [];
|
|
const initNodes = [];
|
|
const nodes = tfNodes.reduce((map, node)=>{
|
|
map[node.name] = this.mapNode(node);
|
|
if (node.op.startsWith("Placeholder")) placeholders.push(map[node.name]);
|
|
else if (node.op === "Const") weights.push(map[node.name]);
|
|
else if (node.input == null || node.input.length === 0) initNodes.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, index)=>{
|
|
const [nodeName, , outputName] = (0, _utils.getNodeNameAndIndex)(name);
|
|
const inputNode = nodes[nodeName];
|
|
if (inputNode.outputs != null) {
|
|
const outputIndex = inputNode.outputs.indexOf(outputName);
|
|
if (outputIndex !== -1) {
|
|
const inputName = `${nodeName}:${outputIndex}`;
|
|
// update the input name to use the mapped output index directly.
|
|
node.inputNames[index] = inputName;
|
|
}
|
|
}
|
|
node.inputs.push(inputNode);
|
|
inputNode.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] = (0, _utils.getNodeNameAndIndex)(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] = (0, _utils.getNodeNameAndIndex)(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;
|
|
}, {});
|
|
const result = {
|
|
nodes,
|
|
inputs,
|
|
outputs,
|
|
weights,
|
|
placeholders,
|
|
signature,
|
|
functions
|
|
};
|
|
if (initNodes.length > 0) result.initNodes = initNodes;
|
|
return result;
|
|
}
|
|
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 = (0, _register.getRegisteredOp)(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.slice(1) : input),
|
|
inputs: [],
|
|
children: [],
|
|
inputParams: {},
|
|
attrParams: {},
|
|
rawAttrs: node.attr,
|
|
outputs: mapper.outputs
|
|
};
|
|
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] = (0, _utils.getNodeNameAndIndex)(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, index)=>{
|
|
const [nodeName, , outputName] = (0, _utils.getNodeNameAndIndex)(name);
|
|
const inputNode = nodes[nodeName];
|
|
if (inputNode.outputs != null) {
|
|
const outputIndex = inputNode.outputs.indexOf(outputName);
|
|
if (outputIndex !== -1) {
|
|
const inputName = `${nodeName}:${outputIndex}`;
|
|
// update the input name to use the mapped output index directly.
|
|
node.inputNames[index] = inputName;
|
|
}
|
|
}
|
|
node.inputs.push(inputNode);
|
|
inputNode.children.push(node);
|
|
});
|
|
});
|
|
const returnNodeMap = functionDef.ret;
|
|
functionDef.signature.outputArg.forEach((output)=>{
|
|
const [nodeName, index] = (0, _utils.getNodeNameAndIndex)(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 = (0, _tfjsCore.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 = _compiledApi.DataType[value];
|
|
switch(value){
|
|
case _compiledApi.DataType.DT_FLOAT:
|
|
case _compiledApi.DataType.DT_HALF:
|
|
return "float32";
|
|
case _compiledApi.DataType.DT_INT32:
|
|
case _compiledApi.DataType.DT_INT64:
|
|
case _compiledApi.DataType.DT_INT8:
|
|
case _compiledApi.DataType.DT_UINT8:
|
|
return "int32";
|
|
case _compiledApi.DataType.DT_BOOL:
|
|
return "bool";
|
|
case _compiledApi.DataType.DT_DOUBLE:
|
|
return "float32";
|
|
case _compiledApi.DataType.DT_STRING:
|
|
return "string";
|
|
case _compiledApi.DataType.DT_COMPLEX64:
|
|
case _compiledApi.DataType.DT_COMPLEX128:
|
|
return "complex64";
|
|
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;
|
|
}
|
|
|
|
},{"509fe566240bdc8b":"kLBSi","@tensorflow/tfjs-core":"21Ftl","../data/compiled_api":"9JlGI","./custom_op/register":"fBdpJ","./executors/utils":"lA8AN","./op_list/arithmetic":"ji9iB","./op_list/basic_math":"jvEs5","./op_list/control":"lLjRP","./op_list/convolution":"6d1E7","./op_list/creation":"bqRRS","./op_list/dynamic":"dk8bW","./op_list/evaluation":"2nQsa","./op_list/graph":"5sTUq","./op_list/hash_table":"aL6VI","./op_list/image":"20Hqa","./op_list/logical":"lRZZd","./op_list/matrices":"fzvw9","./op_list/normalization":"5PcxC","./op_list/reduction":"aLLnY","./op_list/slice_join":"byP8Z","./op_list/sparse":"1gqiT","./op_list/spectral":"dJaL2","./op_list/string":"j8hv4","./op_list/transformation":"eSckc","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9JlGI":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "DataType", ()=>DataType);
|
|
parcelHelpers.export(exports, "SaverDef", ()=>SaverDef);
|
|
var DataType;
|
|
(function(DataType) {
|
|
// These properties must be quoted since they are used by parseDtypeParam
|
|
// in tfjs-converter/src/operations/operation_mapper.ts to look up dtypes
|
|
// by string name. If they are not quoted, Closure will mangle their names.
|
|
// Not a legal value for DataType. Used to indicate a DataType field
|
|
// has not been set.
|
|
DataType[DataType["DT_INVALID"] = 0] = "DT_INVALID";
|
|
// Data types that all computation devices are expected to be
|
|
// capable to support.
|
|
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_QINT16"] = 15] = "DT_QINT16";
|
|
DataType[DataType["DT_QUINT16"] = 16] = "DT_QUINT16";
|
|
DataType[DataType["DT_UINT16"] = 17] = "DT_UINT16";
|
|
DataType[DataType["DT_COMPLEX128"] = 18] = "DT_COMPLEX128";
|
|
DataType[DataType["DT_HALF"] = 19] = "DT_HALF";
|
|
DataType[DataType["DT_RESOURCE"] = 20] = "DT_RESOURCE";
|
|
DataType[DataType["DT_VARIANT"] = 21] = "DT_VARIANT";
|
|
DataType[DataType["DT_UINT32"] = 22] = "DT_UINT32";
|
|
DataType[DataType["DT_UINT64"] = 23] = "DT_UINT64";
|
|
// Do not use! These are only for parameters. Every enum above
|
|
// should have a corresponding value below (verified by types_test).
|
|
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["DT_QINT16_REF"] = 115] = "DT_QINT16_REF";
|
|
DataType[DataType["DT_QUINT16_REF"] = 116] = "DT_QUINT16_REF";
|
|
DataType[DataType["DT_UINT16_REF"] = 117] = "DT_UINT16_REF";
|
|
DataType[DataType["DT_COMPLEX128_REF"] = 118] = "DT_COMPLEX128_REF";
|
|
DataType[DataType["DT_HALF_REF"] = 119] = "DT_HALF_REF";
|
|
DataType[DataType["DT_RESOURCE_REF"] = 120] = "DT_RESOURCE_REF";
|
|
DataType[DataType["DT_VARIANT_REF"] = 121] = "DT_VARIANT_REF";
|
|
DataType[DataType["DT_UINT32_REF"] = 122] = "DT_UINT32_REF";
|
|
DataType[DataType["DT_UINT64_REF"] = 123] = "DT_UINT64_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 = {}));
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fBdpJ":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Register an Op for graph model executor. This allows 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 are 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'}
|
|
*/ parcelHelpers.export(exports, "registerOp", ()=>registerOp);
|
|
/**
|
|
* Retrieve the OpMapper object for the registered op.
|
|
*
|
|
* @param name The Tensorflow Op name.
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Op Registry'}
|
|
*/ parcelHelpers.export(exports, "getRegisteredOp", ()=>getRegisteredOp);
|
|
/**
|
|
* Deregister the Op for graph model executor.
|
|
*
|
|
* @param name The Tensorflow Op name.
|
|
*
|
|
* @doc {heading: 'Models', subheading: 'Op Registry'}
|
|
*/ parcelHelpers.export(exports, "deregisterOp", ()=>deregisterOp);
|
|
const CUSTOM_OPS = {};
|
|
function registerOp(name, opFunc) {
|
|
const opMapper = {
|
|
tfOpName: name,
|
|
category: "custom",
|
|
inputs: [],
|
|
attrs: [],
|
|
customExecutor: opFunc
|
|
};
|
|
CUSTOM_OPS[name] = opMapper;
|
|
}
|
|
function getRegisteredOp(name) {
|
|
return CUSTOM_OPS[name];
|
|
}
|
|
function deregisterOp(name) {
|
|
delete CUSTOM_OPS[name];
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lA8AN":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "getParamValue", ()=>getParamValue);
|
|
/**
|
|
* Retrieve the tensor from tensorsMap based on input name.
|
|
* @param name Node input name
|
|
* @param tensorsMap Tensors map keyed by the node
|
|
* @param context contains tensors and information for running the current node.
|
|
* @param resourceManager Optional. Contains global resources of the model.
|
|
*/ parcelHelpers.export(exports, "getTensor", ()=>getTensor);
|
|
/**
|
|
* Retrieve the tensors based on input name for current context.
|
|
* @param name Node input name
|
|
* @param tensorsMap Tensors map keyed by the node
|
|
*/ parcelHelpers.export(exports, "getTensorsForCurrentContext", ()=>getTensorsForCurrentContext);
|
|
/**
|
|
* Returns the node name, outputName 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.
|
|
* If the input name contains output name i.e. StringSplit:indices:0, it will
|
|
* return ['StringSplit', 0, 'indices'].
|
|
*/ parcelHelpers.export(exports, "getNodeNameAndIndex", ()=>getNodeNameAndIndex);
|
|
parcelHelpers.export(exports, "parseNodeName", ()=>parseNodeName);
|
|
parcelHelpers.export(exports, "split", ()=>split);
|
|
parcelHelpers.export(exports, "getPadding", ()=>getPadding);
|
|
/**
|
|
* Reuse the tensor if it is marked as keep, otherwise clone the tensor to
|
|
* avoid disposal. This is important for TensorArray and TensorList ops, since
|
|
* internally they use a tensor as the id for TensorArray and TensorList, and
|
|
* to simplify lookup, they also use Tensor.id as the key to the internal map.
|
|
* These id tensors have been marked as kept in the backend, we need avoid clone
|
|
* them in order to create new Tensor.id.
|
|
* @param tensor
|
|
*/ parcelHelpers.export(exports, "cloneTensor", ()=>cloneTensor);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function getParamValue(paramName, node, tensorMap, context, resourceManager) {
|
|
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;
|
|
const shiftedStart = start < 0 ? node.inputNames.length + start : start;
|
|
if (inputParam.type === "tensor") return getTensor(node.inputNames[shiftedStart], tensorMap, context, resourceManager);
|
|
if (inputParam.type === "tensors") {
|
|
// TODO(mattSoulanille): This filters out NoOp nodes during execution, but
|
|
// these should really never be in the execution graph in the first place.
|
|
// They're necessary for ordering the graph, but should not be visible
|
|
// during execution. Perhaps have different sets of children, one for
|
|
// control dependencies and another for real dependencies.
|
|
const inputs = node.inputs.slice(start, end);
|
|
const inputNames = node.inputNames.slice(start, end).filter((_name, index)=>{
|
|
var _a;
|
|
return ((_a = inputs[index]) === null || _a === void 0 ? void 0 : _a.op) !== "NoOp";
|
|
});
|
|
return inputNames.map((name)=>getTensor(name, tensorMap, context, resourceManager));
|
|
}
|
|
const tensor = getTensor(node.inputNames[shiftedStart], tensorMap, context, resourceManager);
|
|
const data = tensor.dataSync();
|
|
return inputParam.type === "number" ? data[0] : (0, _tfjsCore.util).toNestedArray(tensor.shape, data);
|
|
}
|
|
const attrParam = node.attrParams[paramName];
|
|
return attrParam && attrParam.value;
|
|
}
|
|
function getTensor(name, tensorsMap, context, resourceManager) {
|
|
const [nodeName, index] = parseNodeName(name, context);
|
|
if (resourceManager != null) {
|
|
const tensor = resourceManager.getHashTableHandleByName(nodeName);
|
|
if (tensor != null) return tensor;
|
|
}
|
|
const contextId = context.currentContextIds.find((contextId)=>{
|
|
return !!tensorsMap[getNodeNameWithContextId(nodeName, contextId)];
|
|
});
|
|
return contextId !== undefined ? tensorsMap[getNodeNameWithContextId(nodeName, contextId)][index] : undefined;
|
|
}
|
|
function getTensorsForCurrentContext(name, tensorsMap, context) {
|
|
return tensorsMap[getNodeNameWithContextId(name, context.currentContextId)];
|
|
}
|
|
function getNodeNameAndIndex(inputName, context) {
|
|
const [nodeName, index, outputName] = parseNodeName(inputName, context);
|
|
return [
|
|
getNodeNameWithContextId(nodeName, context && context.currentContextId),
|
|
index,
|
|
outputName
|
|
];
|
|
}
|
|
function getNodeNameWithContextId(name, contextId) {
|
|
return !!contextId ? `${name}-${contextId}` : name;
|
|
}
|
|
function parseNodeName(name, context) {
|
|
if (name === "") return [
|
|
"",
|
|
0,
|
|
undefined
|
|
];
|
|
const isCacheEnabled = context != null && context.parseNodeNameCache != null;
|
|
if (isCacheEnabled) {
|
|
const cachedResult = context.parseNodeNameCache.get(name);
|
|
if (cachedResult != null) return cachedResult;
|
|
}
|
|
const parts = name.split(":");
|
|
let result;
|
|
if (parts.length === 1) result = [
|
|
name,
|
|
0,
|
|
undefined
|
|
];
|
|
else {
|
|
const nodeName = parts[0];
|
|
const outputName = parts.length === 3 ? parts[1] : undefined;
|
|
const index = Number(parts[parts.length - 1]);
|
|
result = [
|
|
nodeName,
|
|
index,
|
|
outputName
|
|
];
|
|
}
|
|
if (isCacheEnabled) context.parseNodeNameCache.set(name, result);
|
|
return result;
|
|
}
|
|
function split(arr, size) {
|
|
const res = [];
|
|
for(let i = 0; i < arr.length; i += size)res.push(arr.slice(i, i + size));
|
|
return res;
|
|
}
|
|
function getPadding(node, tensorMap, context) {
|
|
let pad = getParamValue("pad", node, tensorMap, context);
|
|
if (pad === "explicit") {
|
|
// This is 1d array, we need to convert it to 2d array
|
|
pad = getParamValue("explicitPaddings", node, tensorMap, context);
|
|
const explicitPadding = [
|
|
[
|
|
0,
|
|
0
|
|
],
|
|
[
|
|
0,
|
|
0
|
|
],
|
|
[
|
|
0,
|
|
0
|
|
],
|
|
[
|
|
0,
|
|
0
|
|
]
|
|
];
|
|
for(let i = 0; i < 4; i++){
|
|
explicitPadding[i][0] = pad[i * 2];
|
|
explicitPadding[i][1] = pad[i * 2 + 1];
|
|
}
|
|
return explicitPadding;
|
|
}
|
|
return pad;
|
|
}
|
|
function cloneTensor(tensor) {
|
|
return tensor.kept ? tensor : (0, _tfjsCore.clone)(tensor);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ji9iB":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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
|
|
},
|
|
{
|
|
"tfName": "data_format",
|
|
"name": "dataFormat",
|
|
"type": "string",
|
|
"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"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "Minimum",
|
|
"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": "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
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jvEs5":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "clipValueMin",
|
|
"type": "number"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "clipValueMax",
|
|
"type": "number"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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": "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
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "IsNan",
|
|
"category": "basic_math",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "IsFinite",
|
|
"category": "basic_math",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "IsInf",
|
|
"category": "basic_math",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lLjRP":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
const json = [
|
|
{
|
|
"tfOpName": "EmptyTensorList",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "maxNumElements",
|
|
"type": "number"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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": "tensor"
|
|
},
|
|
{
|
|
"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": "tensor"
|
|
},
|
|
{
|
|
"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": "tensor"
|
|
},
|
|
{
|
|
"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": "tensor"
|
|
},
|
|
{
|
|
"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": "tensor"
|
|
},
|
|
{
|
|
"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": "tensor"
|
|
},
|
|
{
|
|
"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": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "flowIn",
|
|
"type": "number"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorArrayCloseV3",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorArrayId",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListScatter",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensor",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "indices",
|
|
"type": "number[]"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListScatterV2",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensor",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "indices",
|
|
"type": "number[]"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
},
|
|
{
|
|
"start": 3,
|
|
"name": "numElements",
|
|
"type": "number"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListGather",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "indices",
|
|
"type": "number[]"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListGetItem",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "index",
|
|
"type": "number"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListSetItem",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "index",
|
|
"type": "number"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "tensor",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListReserve",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "numElements",
|
|
"type": "number"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListFromTensor",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensor",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListStack",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
},
|
|
{
|
|
"tfName": "num_elements",
|
|
"name": "numElements",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListSplit",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensor",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "lengths",
|
|
"type": "number[]"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListConcat",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_shape",
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
},
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListConcatV2",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_shape",
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
},
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListPopBack",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "elementShape",
|
|
"type": "shape"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListPushBack",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "tensor",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "element_dtype",
|
|
"name": "elementDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListLength",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorListResize",
|
|
"category": "control",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensorListId",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "size",
|
|
"type": "number"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6d1E7":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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": "explicit_paddings",
|
|
"name": "explicitPaddings",
|
|
"type": "number[]",
|
|
"defaultValue": [],
|
|
"notSupported": true
|
|
},
|
|
{
|
|
"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
|
|
},
|
|
{
|
|
"tfName": "leakyrelu_alpha",
|
|
"name": "leakyreluAlpha",
|
|
"type": "number",
|
|
"defaultValue": 0.2
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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": []
|
|
},
|
|
{
|
|
"tfName": "dilations",
|
|
"name": "dilations",
|
|
"type": "number[]",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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": []
|
|
},
|
|
{
|
|
"tfName": "explicit_paddings",
|
|
"name": "explicitPaddings",
|
|
"type": "number[]",
|
|
"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[]"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "Dilation2D",
|
|
"category": "convolution",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "filter",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "strides",
|
|
"name": "strides",
|
|
"type": "number[]"
|
|
},
|
|
{
|
|
"tfName": "rates",
|
|
"name": "dilations",
|
|
"type": "number[]"
|
|
},
|
|
{
|
|
"tfName": "padding",
|
|
"name": "pad",
|
|
"type": "string"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bqRRS":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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": "RandomStandardNormal",
|
|
"category": "creation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "shape",
|
|
"type": "number[]"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "seed",
|
|
"name": "seed",
|
|
"type": "number",
|
|
"defaultValue": 0
|
|
},
|
|
{
|
|
"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": "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": "RandomUniformInt",
|
|
"category": "creation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "shape",
|
|
"type": "number[]"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "minval",
|
|
"name": "minval",
|
|
"type": "number"
|
|
},
|
|
{
|
|
"tfName": "maxval",
|
|
"name": "maxval",
|
|
"type": "number"
|
|
},
|
|
{
|
|
"tfName": "seed",
|
|
"name": "seed",
|
|
"type": "number",
|
|
"defaultValue": 0
|
|
},
|
|
{
|
|
"tfName": "seed2",
|
|
"name": "seed2",
|
|
"type": "number",
|
|
"defaultValue": 0,
|
|
"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
|
|
},
|
|
{
|
|
"tfName": "stddev",
|
|
"name": "stdDev",
|
|
"type": "number",
|
|
"defaultValue": 1
|
|
},
|
|
{
|
|
"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"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dk8bW":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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": "NonMaxSuppressionV4",
|
|
"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"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
},
|
|
{
|
|
"tfName": "T_threshold",
|
|
"name": "threshold",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
},
|
|
{
|
|
"tfName": "pad_to_max_output_size",
|
|
"name": "padToMaxOutputSize",
|
|
"type": "bool"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2nQsa":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
const json = [
|
|
{
|
|
"tfOpName": "LowerBound",
|
|
"category": "evaluation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "sortedSequence",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "values",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TopKV2",
|
|
"category": "evaluation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "k",
|
|
"type": "number"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "sorted",
|
|
"name": "sorted",
|
|
"type": "bool"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "UpperBound",
|
|
"category": "evaluation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "sortedSequence",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "values",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "Unique",
|
|
"category": "evaluation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "UniqueV2",
|
|
"category": "evaluation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "axis",
|
|
"type": "number"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5sTUq":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aL6VI":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
const json = [
|
|
{
|
|
"tfOpName": "HashTable",
|
|
"category": "hash_table",
|
|
"inputs": [],
|
|
"attrs": [
|
|
{
|
|
"tfName": "shared_name",
|
|
"name": "sharedName",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "use_node_name_sharing",
|
|
"name": "useNodeNameSharing",
|
|
"type": "bool"
|
|
},
|
|
{
|
|
"tfName": "key_dtype",
|
|
"name": "keyDType",
|
|
"type": "dtype"
|
|
},
|
|
{
|
|
"tfName": "value_dtype",
|
|
"name": "valueDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "HashTableV2",
|
|
"category": "hash_table",
|
|
"inputs": [],
|
|
"attrs": [
|
|
{
|
|
"tfName": "shared_name",
|
|
"name": "sharedName",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "use_node_name_sharing",
|
|
"name": "useNodeNameSharing",
|
|
"type": "bool"
|
|
},
|
|
{
|
|
"tfName": "key_dtype",
|
|
"name": "keyDType",
|
|
"type": "dtype"
|
|
},
|
|
{
|
|
"tfName": "value_dtype",
|
|
"name": "valueDType",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "LookupTableImport",
|
|
"category": "hash_table",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tableHandle",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "keys",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "values",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "Tin",
|
|
"name": "tIn",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
},
|
|
{
|
|
"tfName": "Tout",
|
|
"name": "tOut",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "LookupTableImportV2",
|
|
"category": "hash_table",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tableHandle",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "keys",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "values",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "Tin",
|
|
"name": "tIn",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
},
|
|
{
|
|
"tfName": "Tout",
|
|
"name": "tOut",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "LookupTableFind",
|
|
"category": "hash_table",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tableHandle",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "keys",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "defaultValue",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "Tin",
|
|
"name": "tIn",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
},
|
|
{
|
|
"tfName": "Tout",
|
|
"name": "tOut",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "LookupTableFindV2",
|
|
"category": "hash_table",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tableHandle",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "keys",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "defaultValue",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "Tin",
|
|
"name": "tIn",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
},
|
|
{
|
|
"tfName": "Tout",
|
|
"name": "tOut",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "LookupTableSize",
|
|
"category": "hash_table",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tableHandle",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "LookupTableSizeV2",
|
|
"category": "hash_table",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tableHandle",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "InitializeTable",
|
|
"category": "hash_table",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tableHandle",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "keys",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "values",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "InitializeTableV2",
|
|
"category": "hash_table",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tableHandle",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "keys",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "values",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"20Hqa":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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": "half_pixel_centers",
|
|
"name": "halfPixelCenters",
|
|
"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": "half_pixel_centers",
|
|
"name": "halfPixelCenters",
|
|
"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"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "ImageProjectiveTransformV3",
|
|
"category": "image",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "images",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "transforms",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "outputShape",
|
|
"type": "number[]"
|
|
},
|
|
{
|
|
"start": 3,
|
|
"name": "fillValue",
|
|
"type": "number"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "interpolation",
|
|
"name": "interpolation",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "fill_mode",
|
|
"name": "fillMode",
|
|
"type": "string"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lRZZd":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "BitwiseAnd",
|
|
"category": "logical",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "y",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fzvw9":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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": "leakyrelu_alpha",
|
|
"name": "leakyreluAlpha",
|
|
"type": "number",
|
|
"defaultValue": 0.2
|
|
},
|
|
{
|
|
"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
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "Einsum",
|
|
"category": "matrices",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"end": 0,
|
|
"name": "tensors",
|
|
"type": "tensors"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "equation",
|
|
"name": "equation",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "N",
|
|
"name": "n",
|
|
"type": "number",
|
|
"defaultValue": 2
|
|
},
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "MatrixBandPart",
|
|
"category": "matrices",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "a",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "numLower",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "numUpper",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5PcxC":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
const json = [
|
|
{
|
|
"tfOpName": "EuclideanNorm",
|
|
"category": "normalization",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "axis",
|
|
"type": "number[]"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "keep_dims",
|
|
"name": "keepDims",
|
|
"type": "bool",
|
|
"defaultValue": false
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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
|
|
},
|
|
{
|
|
"tfName": "alpha",
|
|
"name": "alpha",
|
|
"type": "number",
|
|
"defaultValue": 1
|
|
},
|
|
{
|
|
"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"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aLLnY":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
const json = [
|
|
{
|
|
"tfOpName": "Bincount",
|
|
"category": "reduction",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "size",
|
|
"type": "number"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "weights",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "DenseBincount",
|
|
"category": "reduction",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "size",
|
|
"type": "number"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "weights",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "binary_output",
|
|
"name": "binaryOutput",
|
|
"type": "bool"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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"
|
|
},
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "Cumprod",
|
|
"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"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"byP8Z":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "batch_dims",
|
|
"name": "batchDims",
|
|
"type": "number",
|
|
"defaultValue": 0
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "Gather",
|
|
"category": "slice_join",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "indices",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"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[]"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "TensorScatterUpdate",
|
|
"category": "slice_join",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "tensor",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "indices",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "values",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1gqiT":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
const json = [
|
|
{
|
|
"tfOpName": "SparseFillEmptyRows",
|
|
"category": "sparse",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "indices",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "values",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "denseShape",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 3,
|
|
"name": "defaultValue",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "SparseReshape",
|
|
"category": "sparse",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "inputIndices",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "inputShape",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "newShape",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "T",
|
|
"name": "dtype",
|
|
"type": "dtype",
|
|
"notSupported": true
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "SparseSegmentMean",
|
|
"category": "sparse",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "data",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "indices",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "segmentIds",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "SparseSegmentSum",
|
|
"category": "sparse",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "data",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "indices",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 2,
|
|
"name": "segmentIds",
|
|
"type": "tensor"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dJaL2":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"j8hv4":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
const json = [
|
|
{
|
|
"tfOpName": "StaticRegexReplace",
|
|
"category": "string",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "input",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "pattern",
|
|
"name": "pattern",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "rewrite",
|
|
"name": "rewrite",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "replace_global",
|
|
"name": "replaceGlobal",
|
|
"type": "bool"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "StringNGrams",
|
|
"category": "string",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "data",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "dataSplits",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "separator",
|
|
"name": "separator",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "ngram_widths",
|
|
"name": "nGramWidths",
|
|
"type": "number[]"
|
|
},
|
|
{
|
|
"tfName": "left_pad",
|
|
"name": "leftPad",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "right_pad",
|
|
"name": "rightPad",
|
|
"type": "string"
|
|
},
|
|
{
|
|
"tfName": "pad_width",
|
|
"name": "padWidth",
|
|
"type": "number"
|
|
},
|
|
{
|
|
"tfName": "preserve_short_sequences",
|
|
"name": "preserveShortSequences",
|
|
"type": "bool"
|
|
}
|
|
],
|
|
"outputs": [
|
|
"ngrams",
|
|
"ngrams_splits"
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "StringSplit",
|
|
"category": "string",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "input",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "delimiter",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "skip_empty",
|
|
"name": "skipEmpty",
|
|
"type": "bool"
|
|
}
|
|
],
|
|
"outputs": [
|
|
"indices",
|
|
"values",
|
|
"shape"
|
|
]
|
|
},
|
|
{
|
|
"tfOpName": "StringToHashBucketFast",
|
|
"category": "string",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "input",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "num_buckets",
|
|
"name": "numBuckets",
|
|
"type": "number"
|
|
}
|
|
]
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eSckc":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "json", ()=>json);
|
|
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": "MirrorPad",
|
|
"category": "transformation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "x",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "padding",
|
|
"type": "number[]"
|
|
}
|
|
],
|
|
"attrs": [
|
|
{
|
|
"tfName": "mode",
|
|
"name": "mode",
|
|
"type": "string"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"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": "EnsureShape",
|
|
"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": []
|
|
},
|
|
{
|
|
"tfOpName": "BroadcastArgs",
|
|
"category": "transformation",
|
|
"inputs": [
|
|
{
|
|
"start": 0,
|
|
"name": "s0",
|
|
"type": "tensor"
|
|
},
|
|
{
|
|
"start": 1,
|
|
"name": "s1",
|
|
"type": "tensor"
|
|
}
|
|
],
|
|
"attrs": []
|
|
}
|
|
];
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iu0wq":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "GraphExecutor", ()=>GraphExecutor);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _utils = require("../operations/executors/utils");
|
|
var _operationExecutor = require("../operations/operation_executor");
|
|
var _executionContext = require("./execution_context");
|
|
var _modelAnalysis = require("./model_analysis");
|
|
class GraphExecutor {
|
|
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;
|
|
}
|
|
/**
|
|
* Set `ResourceManager` shared by executors of a model.
|
|
* @param resourceManager: `ResourceManager` of the `GraphModel`.
|
|
*/ set resourceManager(resourceManager) {
|
|
this._resourceManager = resourceManager;
|
|
}
|
|
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;
|
|
}, {});
|
|
}
|
|
/**
|
|
*
|
|
* @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.parseNodeNameCache = new Map();
|
|
this._weightMap = {};
|
|
this.SEPARATOR = ",";
|
|
this._functions = {};
|
|
this._functionExecutorMap = {};
|
|
this.keepIntermediateTensors = false;
|
|
this._outputs = graph.outputs;
|
|
this._inputs = graph.inputs;
|
|
this._initNodes = graph.initNodes;
|
|
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 GraphExecutor(graph.functions[name], this);
|
|
});
|
|
}
|
|
getCompilationKey(inputs, outputs) {
|
|
const sortedInputs = inputs.map((node)=>node.name).sort();
|
|
const sortedOutputs = outputs.map((node)=>node.name).sort();
|
|
return sortedInputs.join(this.SEPARATOR) + "--" + sortedOutputs.join(this.SEPARATOR);
|
|
}
|
|
/**
|
|
* Compiles the inference graph and returns the minimal set of nodes that are
|
|
* required for execution, in the correct execution order.
|
|
* @returns {Object} compilation The compile result.
|
|
* @returns {Node[]} compilation.orderedNodes Nodes in the correct execution
|
|
* order.
|
|
* @returns {Map<string, Node[]>} compilation.nodeLiveUntilMap A map from node
|
|
* to disposable nodes after its execution. That is, for a node `x`,
|
|
* `nodeLiveUntilMap[x]` indicates all nodes whose intermediate
|
|
* tensors should be disposed after `x` is executed.
|
|
*/ compile(inputs, outputs) {
|
|
const executionInfo = (0, _modelAnalysis.getExecutionSubgraph)(inputs, outputs, this.weightMap, this._initNodes);
|
|
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}]`);
|
|
}
|
|
const orderedNodes = (0, _modelAnalysis.getNodesInTopologicalOrder)(this.graph, executionInfo);
|
|
const nodeLiveUntilMap = (0, _modelAnalysis.getNodeLiveUntilMap)(orderedNodes);
|
|
return {
|
|
orderedNodes,
|
|
nodeLiveUntilMap
|
|
};
|
|
}
|
|
cloneAndKeepTensor(tensor) {
|
|
if (tensor == null) return null;
|
|
const clone = tensor.clone();
|
|
// Keep the clone because`model.execute()` may be called within
|
|
// a `tidy()`, but the user may inspect these tensors after the
|
|
// tidy.
|
|
(0, _tfjsCore.keep)(clone);
|
|
return clone;
|
|
}
|
|
cloneTensorList(tensors) {
|
|
if (!tensors) return null;
|
|
const clonedTensor = tensors.map((tensor)=>{
|
|
return this.cloneAndKeepTensor(tensor);
|
|
});
|
|
return clonedTensor;
|
|
}
|
|
cloneTensorMap(tensorsMap) {
|
|
return Object.fromEntries(Object.entries(tensorsMap).map(([name, tensorsList])=>{
|
|
return [
|
|
name,
|
|
this.cloneTensorList(tensorsList)
|
|
];
|
|
}));
|
|
}
|
|
/**
|
|
* Executes the inference for given input tensors.
|
|
* @param inputs Tensor map for the model inputs, keyed by the input node
|
|
* names.
|
|
* @param outputs Optional. 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) {
|
|
// Dispose any tensors from a prior run to avoid leaking them.
|
|
this.disposeIntermediateTensors();
|
|
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[(0, _utils.parseNodeName)(name)[0]]);
|
|
const outputNodeNames = outputs.map((name)=>(0, _utils.parseNodeName)(name)[0]);
|
|
const outputNodeNameSet = new Set(outputNodeNames);
|
|
let outputNodes = outputNodeNames.map((name)=>this.graph.nodes[name]);
|
|
// If no outputs are specified, then use the default outputs of the model.
|
|
if (outputNodes.length === 0) outputNodes = this._outputs;
|
|
const compilationKey = this.getCompilationKey(inputNodes, outputNodes);
|
|
// Do nothing if the compiled graph cache contains the input.
|
|
let compilation = this.compiledMap.get(compilationKey);
|
|
if (compilation == null) {
|
|
compilation = this.compile(inputs, outputNodes);
|
|
this.compiledMap.set(compilationKey, compilation);
|
|
}
|
|
// Keep tensors if KEEP_INTERMEDIATE_TENSORS is on.
|
|
try {
|
|
this.keepIntermediateTensors = (0, _tfjsCore.env)().getBool("KEEP_INTERMEDIATE_TENSORS");
|
|
} catch (e) {
|
|
this.keepIntermediateTensors = false;
|
|
console.warn(e.message);
|
|
}
|
|
const tensorArrayMap = {};
|
|
const tensorListMap = {};
|
|
return (0, _tfjsCore.tidy)(()=>{
|
|
const context = new (0, _executionContext.ExecutionContext)(this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap, this.parseNodeNameCache);
|
|
const tensorsMap = Object.assign({}, this.weightMap);
|
|
if (this.keepIntermediateTensors) this.clonedTensorsMap = this.cloneTensorMap(this.weightMap);
|
|
Object.keys(inputs).forEach((name)=>{
|
|
const [nodeName, index] = (0, _utils.parseNodeName)(name, context);
|
|
const tensors = [];
|
|
tensors[index] = inputs[name];
|
|
tensorsMap[nodeName] = tensors;
|
|
if (this.keepIntermediateTensors) this.clonedTensorsMap[nodeName] = this.cloneTensorList(tensors);
|
|
});
|
|
const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);
|
|
const { orderedNodes, nodeLiveUntilMap } = compilation;
|
|
for (const node of orderedNodes){
|
|
if (tensorsMap[node.name]) continue;
|
|
const tensors = (0, _operationExecutor.executeOp)(node, tensorsMap, context, this._resourceManager);
|
|
if ((0, _tfjsCore.util).isPromise(tensors)) throw new Error(`The execution of the op '${node.op}' returned a promise. ` + `Please use model.executeAsync() instead.`);
|
|
tensorsMap[node.name] = tensors;
|
|
if (this.keepIntermediateTensors) this.clonedTensorsMap[node.name] = this.cloneTensorList(tensors);
|
|
this.checkTensorForDisposalWithNodeLiveUntilInfo(node, tensorsMap, context, tensorsToKeep, outputNodeNameSet, nodeLiveUntilMap.get(node.name));
|
|
}
|
|
// dispose the context for the root executor
|
|
if (this.parent == null) context.dispose(tensorsToKeep);
|
|
return outputs.map((name)=>(0, _utils.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, outputNodeNameSet, intermediateTensorConsumerCount) {
|
|
// Skip output nodes and any control flow nodes, since its dependency is
|
|
// tricky to track correctly.
|
|
if ((0, _modelAnalysis.isControlFlow)(node) || outputNodeNameSet.has(nodeName)) return;
|
|
for (const tensor of tensorMap[nodeName]){
|
|
if (tensor == null) continue;
|
|
intermediateTensorConsumerCount[tensor.id] = (intermediateTensorConsumerCount[tensor.id] || 0) + node.children.length;
|
|
}
|
|
for (const input of node.inputs){
|
|
// Skip any control flow nodes, since its dependency is tricky to track
|
|
// correctly.
|
|
if ((0, _modelAnalysis.isControlFlow)(input)) continue;
|
|
const tensors = (0, _utils.getTensorsForCurrentContext)(input.name, tensorMap, context);
|
|
if (tensors == null) continue;
|
|
for (const tensor of tensors){
|
|
if (!tensor || tensor.kept || tensorsToKeep.has(tensor.id)) continue;
|
|
// Only intermediate nodes' tensors have counts set, not marked as
|
|
// kept, and not in `tensorsToKeep`.
|
|
// Input and weight nodes' tensors should exist in `tensorsToKeep`.
|
|
// Output and control flow nodes' tensors should never have count set.
|
|
const count = intermediateTensorConsumerCount[tensor.id];
|
|
if (count === 1) {
|
|
tensor.dispose();
|
|
delete intermediateTensorConsumerCount[tensor.id];
|
|
} else if (count != null) intermediateTensorConsumerCount[tensor.id]--;
|
|
}
|
|
}
|
|
}
|
|
checkTensorForDisposalWithNodeLiveUntilInfo(node, tensorMap, context, tensorsToKeep, outputNodeNameSet, liveUntilNodes) {
|
|
function isNonDisposableNode(node) {
|
|
// Skip output nodes and any control flow nodes, since its dependency is
|
|
// tricky to track correctly.
|
|
return (0, _modelAnalysis.isControlFlow)(node) || outputNodeNameSet.has(node.name);
|
|
}
|
|
if ((0, _modelAnalysis.isControlFlow)(node) || liveUntilNodes == null) return;
|
|
for (const nodeToDispose of liveUntilNodes){
|
|
if (isNonDisposableNode(nodeToDispose)) continue;
|
|
const tensors = (0, _utils.getTensorsForCurrentContext)(nodeToDispose.name, tensorMap, context);
|
|
for (const tensor of tensors){
|
|
if (!tensor || tensor.kept || tensorsToKeep.has(tensor.id)) continue;
|
|
tensor.dispose();
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* 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.
|
|
*/ async executeAsync(inputs, outputs) {
|
|
return this._executeAsync(inputs, outputs);
|
|
}
|
|
disposeIntermediateTensors() {
|
|
if (!this.clonedTensorsMap) return;
|
|
Object.values(this.clonedTensorsMap).forEach((tensorsList)=>{
|
|
for (const tensor of tensorsList)if (tensor && !tensor.isDisposed) tensor.dispose();
|
|
});
|
|
this.clonedTensorsMap = null;
|
|
}
|
|
getIntermediateTensors() {
|
|
return this.clonedTensorsMap;
|
|
}
|
|
/**
|
|
* 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 Optional. 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 isFunctionExecution Optional. Flag for executing a function.
|
|
* @param tensorArrayMap Optional, global TensorArray map by id. Used for
|
|
* function execution.
|
|
* @param tensorArrayMap Optional global TensorList map by id. Used for
|
|
* function execution.
|
|
*/ async _executeAsync(inputs, outputs, isFunctionExecution = false, tensorArrayMap = {}, tensorListMap = {}) {
|
|
// Dispose any tensors from a prior run to avoid leaking them.
|
|
this.disposeIntermediateTensors();
|
|
if (!isFunctionExecution) {
|
|
inputs = this.mapInputs(inputs);
|
|
this.checkInputs(inputs);
|
|
this.checkInputShapeAndType(inputs);
|
|
outputs = this.mapOutputs(outputs);
|
|
this.checkOutputs(outputs);
|
|
}
|
|
// Keep tensors if KEEP_INTERMEDIATE_TENSORS is on.
|
|
try {
|
|
this.keepIntermediateTensors = (0, _tfjsCore.env)().getBool("KEEP_INTERMEDIATE_TENSORS");
|
|
} catch (e) {
|
|
this.keepIntermediateTensors = false;
|
|
console.warn(e.message);
|
|
}
|
|
const context = new (0, _executionContext.ExecutionContext)(this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap, this.parseNodeNameCache);
|
|
if (this.keepIntermediateTensors) this.clonedTensorsMap = this.cloneTensorMap(this.weightMap);
|
|
// 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 tensorsMap = await this.executeWithControlFlow(inputs, context, outputs, isFunctionExecution);
|
|
const results = outputs.map((name)=>(0, _utils.getTensor)(name, tensorsMap, context));
|
|
// dispose all the intermediate tensors
|
|
const outputIds = results.map((t)=>t.id);
|
|
const inputIds = Object.keys(inputs).map((name)=>inputs[name].id);
|
|
const keepIds = new Set([
|
|
...outputIds,
|
|
...inputIds,
|
|
...this.weightIds
|
|
]);
|
|
Object.values(tensorsMap).forEach((tensorsList)=>{
|
|
tensorsList.forEach((tensor)=>{
|
|
if (tensor && !tensor.isDisposed && !keepIds.has(tensor.id)) tensor.dispose();
|
|
});
|
|
});
|
|
// dispose the context for the root executor
|
|
if (this.parent == null) context.dispose(keepIds);
|
|
return results;
|
|
}
|
|
async executeFunctionAsync(inputs, tensorArrayMap, tensorListMap) {
|
|
const mappedInputs = inputs.reduce((map, tensor, index)=>{
|
|
map[this.inputs[index].name] = tensor;
|
|
return map;
|
|
}, {});
|
|
return this._executeAsync(mappedInputs, this.outputNodes, true, tensorArrayMap, tensorListMap);
|
|
}
|
|
/**
|
|
* 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 outputNames Optional. 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 isFunctionExecution Flag for executing a function.
|
|
*/ async executeWithControlFlow(inputs, context, outputNames, isFunctionExecution) {
|
|
const names = Object.keys(inputs);
|
|
const inputNodes = names.map((name)=>this.graph.nodes[(0, _utils.parseNodeName)(name)[0]]);
|
|
const outputNodeNames = outputNames.map((name)=>(0, _utils.parseNodeName)(name)[0]);
|
|
const outputNodeNameSet = new Set(outputNodeNames);
|
|
let outputNodes = outputNodeNames.map((name)=>this.graph.nodes[name]);
|
|
// If no outputs are specified, then use the default outputs of the model.
|
|
if (outputNodes.length === 0) outputNodes = this._outputs;
|
|
const { usedNodes, missingInputs, dynamicNode, syncInputs } = (0, _modelAnalysis.getExecutionSubgraph)(inputs, outputNodes, this.weightMap, this._initNodes);
|
|
// First nodes to execute include inputNodes, weights, and initNodes.
|
|
const stack = [
|
|
...inputNodes,
|
|
...this.graph.weights,
|
|
...this._initNodes || []
|
|
].map((node)=>{
|
|
return {
|
|
node,
|
|
contexts: context.currentContext
|
|
};
|
|
});
|
|
const tensorsMap = Object.assign({}, this.weightMap);
|
|
Object.keys(inputs).forEach((name)=>{
|
|
const [nodeName, index] = (0, _utils.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, outputNodeNameSet, intermediateTensorConsumerCount, usedNodes);
|
|
await Promise.all(promises);
|
|
}
|
|
if (dynamicNode == null && !isFunctionExecution) 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)=>!(0, _modelAnalysis.isControlFlow)(node) && !(0, _utils.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, outputNodeNameSet, 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" && (0, _utils.getParamValue)("isConstant", item.node, tensorMap, context)) [nodeName] = (0, _utils.getNodeNameAndIndex)(item.node.name, context);
|
|
// only process nodes that are not in the tensorMap yet, this include
|
|
// inputNodes and internal initNodes.
|
|
if (tensorMap[item.node.name] == null) {
|
|
const tensors = (0, _operationExecutor.executeOp)(item.node, tensorMap, context, this._resourceManager);
|
|
if (!nodeName) [nodeName] = (0, _utils.getNodeNameAndIndex)(item.node.name, context);
|
|
const currentContext = context.currentContext;
|
|
if ((0, _tfjsCore.util).isPromise(tensors)) promises.push(tensors.then((t)=>{
|
|
tensorMap[nodeName] = t;
|
|
if (this.keepIntermediateTensors) this.clonedTensorsMap[nodeName] = this.cloneTensorList(t);
|
|
context.currentContext = currentContext;
|
|
this.checkTensorForDisposal(nodeName, item.node, tensorMap, context, tensorsToKeep, outputNodeNameSet, intermediateTensorConsumerCount);
|
|
this.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
|
|
return t;
|
|
}));
|
|
else {
|
|
tensorMap[nodeName] = tensors;
|
|
if (this.keepIntermediateTensors) this.clonedTensorsMap[nodeName] = this.cloneTensorList(tensors);
|
|
this.checkTensorForDisposal(nodeName, item.node, tensorMap, context, tensorsToKeep, outputNodeNameSet, 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] = (0, _utils.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 !!(0, _utils.getTensor)(name, tensorMap, context);
|
|
})) {
|
|
added[nodeName] = true;
|
|
stack.push({
|
|
contexts: context.currentContext,
|
|
node: childNode
|
|
});
|
|
}
|
|
} else if (childNode.inputNames.every((name)=>{
|
|
return !!(0, _utils.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] = (0, _utils.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);
|
|
(0, _tfjsCore.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) (0, _tfjsCore.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) {
|
|
var _a, _b;
|
|
const result = {};
|
|
for(const inputName in inputs){
|
|
const tensor = (_b = (_a = this._signature) === null || _a === void 0 ? void 0 : _a.inputs) === null || _b === void 0 ? void 0 : _b[inputName];
|
|
if (tensor != null) result[tensor.name] = inputs[inputName];
|
|
else result[inputName] = inputs[inputName];
|
|
}
|
|
return result;
|
|
}
|
|
checkInputs(inputs) {
|
|
const notInGraph = Object.keys(inputs).filter((name)=>{
|
|
const [nodeName] = (0, _utils.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)=>{
|
|
var _a, _b;
|
|
const tensor = (_b = (_a = this._signature) === null || _a === void 0 ? void 0 : _a.outputs) === null || _b === void 0 ? void 0 : _b[name];
|
|
if (tensor != null) return tensor.name;
|
|
return name;
|
|
}, {});
|
|
}
|
|
checkOutputs(outputs) {
|
|
outputs.forEach((name)=>{
|
|
const [normalizedName] = (0, _utils.parseNodeName)(name);
|
|
if (!this.graph.nodes[normalizedName]) throw new Error(`The output '${name}' is not found in the graph`);
|
|
});
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../operations/executors/utils":"lA8AN","../operations/operation_executor":"4Dits","./execution_context":"gK8yG","./model_analysis":"kpmwj","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4Dits":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Executes the op defined by the node object.
|
|
* @param node
|
|
* @param tensorMap contains tensors for executed nodes and weights
|
|
* @param context contains tensors and information for running the current node.
|
|
* @param resourceManager Optional. Contains global resources of the model.
|
|
*/ parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _nodeValueImpl = require("./custom_op/node_value_impl");
|
|
var _register = require("./custom_op/register");
|
|
var _arithmeticExecutor = require("./executors/arithmetic_executor");
|
|
var _basicMathExecutor = require("./executors/basic_math_executor");
|
|
var _controlExecutor = require("./executors/control_executor");
|
|
var _convolutionExecutor = require("./executors/convolution_executor");
|
|
var _creationExecutor = require("./executors/creation_executor");
|
|
var _dynamicExecutor = require("./executors/dynamic_executor");
|
|
var _evaluationExecutor = require("./executors/evaluation_executor");
|
|
var _graphExecutor = require("./executors/graph_executor");
|
|
var _hashTableExecutor = require("./executors/hash_table_executor");
|
|
var _imageExecutor = require("./executors/image_executor");
|
|
var _logicalExecutor = require("./executors/logical_executor");
|
|
var _matricesExecutor = require("./executors/matrices_executor");
|
|
var _normalizationExecutor = require("./executors/normalization_executor");
|
|
var _raggedExecutor = require("./executors/ragged_executor");
|
|
var _reductionExecutor = require("./executors/reduction_executor");
|
|
var _sliceJoinExecutor = require("./executors/slice_join_executor");
|
|
var _sparseExecutor = require("./executors/sparse_executor");
|
|
var _spectralExecutor = require("./executors/spectral_executor");
|
|
var _stringExecutor = require("./executors/string_executor");
|
|
var _transformationExecutor = require("./executors/transformation_executor");
|
|
function executeOp(node, tensorMap, context, resourceManager, tidy = _tfjsCore.tidy) {
|
|
const value = ((node, tensorMap, context)=>{
|
|
switch(node.category){
|
|
case "arithmetic":
|
|
return tidy(()=>_arithmeticExecutor.executeOp(node, tensorMap, context));
|
|
case "basic_math":
|
|
return tidy(()=>_basicMathExecutor.executeOp(node, tensorMap, context));
|
|
case "control":
|
|
return _controlExecutor.executeOp(node, tensorMap, context);
|
|
case "convolution":
|
|
return tidy(()=>_convolutionExecutor.executeOp(node, tensorMap, context));
|
|
case "creation":
|
|
return tidy(()=>_creationExecutor.executeOp(node, tensorMap, context));
|
|
case "dynamic":
|
|
return _dynamicExecutor.executeOp(node, tensorMap, context);
|
|
case "evaluation":
|
|
return tidy(()=>_evaluationExecutor.executeOp(node, tensorMap, context));
|
|
case "image":
|
|
return tidy(()=>_imageExecutor.executeOp(node, tensorMap, context));
|
|
case "graph":
|
|
return tidy(()=>_graphExecutor.executeOp(node, tensorMap, context));
|
|
case "logical":
|
|
return tidy(()=>_logicalExecutor.executeOp(node, tensorMap, context));
|
|
case "matrices":
|
|
return tidy(()=>_matricesExecutor.executeOp(node, tensorMap, context));
|
|
case "normalization":
|
|
return tidy(()=>_normalizationExecutor.executeOp(node, tensorMap, context));
|
|
case "ragged":
|
|
return tidy(()=>_raggedExecutor.executeOp(node, tensorMap, context));
|
|
case "reduction":
|
|
return tidy(()=>_reductionExecutor.executeOp(node, tensorMap, context));
|
|
case "slice_join":
|
|
return tidy(()=>_sliceJoinExecutor.executeOp(node, tensorMap, context));
|
|
case "sparse":
|
|
return tidy(()=>_sparseExecutor.executeOp(node, tensorMap, context));
|
|
case "spectral":
|
|
return tidy(()=>_spectralExecutor.executeOp(node, tensorMap, context));
|
|
case "string":
|
|
return tidy(()=>_stringExecutor.executeOp(node, tensorMap, context));
|
|
case "transformation":
|
|
return tidy(()=>_transformationExecutor.executeOp(node, tensorMap, context));
|
|
case "hash_table":
|
|
return _hashTableExecutor.executeOp(node, tensorMap, context, resourceManager);
|
|
case "custom":
|
|
const opMapper = (0, _register.getRegisteredOp)(node.op);
|
|
if (opMapper && opMapper.customExecutor) return opMapper.customExecutor(new (0, _nodeValueImpl.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 (_tfjsCore.util.isPromise(value)) return value.then((data)=>[].concat(data));
|
|
return [].concat(value);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./custom_op/node_value_impl":"af83H","./custom_op/register":"fBdpJ","./executors/arithmetic_executor":"8J0UN","./executors/basic_math_executor":"j2IHU","./executors/control_executor":"1V4dK","./executors/convolution_executor":"b2H1R","./executors/creation_executor":"kSSii","./executors/dynamic_executor":"37XKU","./executors/evaluation_executor":"9cjVI","./executors/graph_executor":"jqg8t","./executors/hash_table_executor":"9g7sC","./executors/image_executor":"5sGLS","./executors/logical_executor":"30ObX","./executors/matrices_executor":"hCdlL","./executors/normalization_executor":"iGve1","./executors/ragged_executor":"aEvoT","./executors/reduction_executor":"bj9OH","./executors/slice_join_executor":"3HYHo","./executors/sparse_executor":"cwC1Y","./executors/spectral_executor":"jduek","./executors/string_executor":"4NdVa","./executors/transformation_executor":"3LErR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"af83H":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Helper class for lookup inputs and params for nodes in the model graph.
|
|
*/ parcelHelpers.export(exports, "NodeValueImpl", ()=>NodeValueImpl);
|
|
var _utils = require("../executors/utils");
|
|
var _operationMapper = require("../operation_mapper");
|
|
class 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 (0, _utils.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 (0, _utils.getTensor)(name, this.tensorMap, this.context);
|
|
if (value.i != null || value.f != null) return (0, _operationMapper.getNumberParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.s != null) return (0, _operationMapper.getStringParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.b != null) return (0, _operationMapper.getBoolParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.shape != null) return (0, _operationMapper.getTensorShapeParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.type != null) return (0, _operationMapper.getDtypeParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.list != null) {
|
|
if (value.list.i != null || value.list.f != null) return (0, _operationMapper.getNumericArrayParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.list.s != null) return (0, _operationMapper.getStringArrayParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.list.shape != null) return (0, _operationMapper.getTensorShapeArrayParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.list.b != null) return (0, _operationMapper.getBoolArrayParam)(this.node.rawAttrs, name, defaultValue);
|
|
if (value.list.type != null) return (0, _operationMapper.getDtypeArrayParam)(this.node.rawAttrs, name, defaultValue);
|
|
}
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
},{"../executors/utils":"lA8AN","../operation_mapper":"ewPe6","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8J0UN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "BiasAdd":
|
|
case "AddV2":
|
|
case "Add":
|
|
return [
|
|
ops.add((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "AddN":
|
|
return [
|
|
ops.addN((0, _utils.getParamValue)("tensors", node, tensorMap, context))
|
|
];
|
|
case "FloorMod":
|
|
case "Mod":
|
|
return [
|
|
ops.mod((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "Mul":
|
|
return [
|
|
ops.mul((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "RealDiv":
|
|
case "Div":
|
|
return [
|
|
ops.div((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "DivNoNan":
|
|
return [
|
|
ops.divNoNan((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "FloorDiv":
|
|
return [
|
|
ops.floorDiv((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "Sub":
|
|
return [
|
|
ops.sub((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "Minimum":
|
|
return [
|
|
ops.minimum((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "Maximum":
|
|
return [
|
|
ops.maximum((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "Pow":
|
|
return [
|
|
ops.pow((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "SquaredDifference":
|
|
return [
|
|
ops.squaredDifference((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "arithmetic";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iUHBn":[function(require,module,exports) {
|
|
/**
|
|
* @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 file exports ops used by the converters executors. By default it
|
|
* re-exports all ops. In a custom build this is aliased to a file that will
|
|
* only exports ops for a given model.json.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
var _ops = require("./ops");
|
|
parcelHelpers.exportAll(_ops, exports);
|
|
|
|
},{"./ops":"13k1e","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"j2IHU":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "Abs":
|
|
case "ComplexAbs":
|
|
return [
|
|
ops.abs((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Acos":
|
|
return [
|
|
ops.acos((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Acosh":
|
|
return [
|
|
ops.acosh((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Asin":
|
|
return [
|
|
ops.asin((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Asinh":
|
|
return [
|
|
ops.asinh((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Atan":
|
|
return [
|
|
ops.atan((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Atan2":
|
|
return [
|
|
ops.atan2((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("y", node, tensorMap, context))
|
|
];
|
|
case "Atanh":
|
|
return [
|
|
ops.atanh((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Ceil":
|
|
return [
|
|
ops.ceil((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Complex":
|
|
return [
|
|
ops.complex((0, _utils.getParamValue)("real", node, tensorMap, context), (0, _utils.getParamValue)("imag", node, tensorMap, context))
|
|
];
|
|
case "Cos":
|
|
return [
|
|
ops.cos((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Cosh":
|
|
return [
|
|
ops.cosh((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Elu":
|
|
return [
|
|
ops.elu((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Erf":
|
|
return [
|
|
ops.erf((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Exp":
|
|
return [
|
|
ops.exp((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Expm1":
|
|
return [
|
|
ops.expm1((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Floor":
|
|
return [
|
|
ops.floor((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Log":
|
|
return [
|
|
ops.log((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Log1p":
|
|
return [
|
|
ops.log1p((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Imag":
|
|
return [
|
|
ops.imag((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Neg":
|
|
return [
|
|
ops.neg((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Reciprocal":
|
|
return [
|
|
ops.reciprocal((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Real":
|
|
return [
|
|
ops.real((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Relu":
|
|
return [
|
|
ops.relu((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Round":
|
|
return [
|
|
ops.round((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Selu":
|
|
return [
|
|
ops.selu((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Sigmoid":
|
|
return [
|
|
ops.sigmoid((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Sin":
|
|
return [
|
|
ops.sin((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Sign":
|
|
return [
|
|
ops.sign((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Sinh":
|
|
return [
|
|
ops.sinh((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Softplus":
|
|
return [
|
|
ops.softplus((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Sqrt":
|
|
return [
|
|
ops.sqrt((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Square":
|
|
return [
|
|
ops.square((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Tanh":
|
|
return [
|
|
ops.tanh((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Tan":
|
|
return [
|
|
ops.tan((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "ClipByValue":
|
|
return [
|
|
ops.clipByValue((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("clipValueMin", node, tensorMap, context), (0, _utils.getParamValue)("clipValueMax", node, tensorMap, context))
|
|
];
|
|
case "Relu6":
|
|
return [
|
|
ops.relu6((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "Rsqrt":
|
|
return [
|
|
ops.rsqrt((0, _utils.getTensor)(node.inputNames[0], tensorMap, context))
|
|
];
|
|
case "LeakyRelu":
|
|
return [
|
|
ops.leakyRelu((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("alpha", node, tensorMap, context))
|
|
];
|
|
case "Prelu":
|
|
return [
|
|
ops.prelu((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("alpha", node, tensorMap, context))
|
|
];
|
|
case "IsNan":
|
|
return [
|
|
ops.isNaN((0, _utils.getTensor)(node.inputNames[0], tensorMap, context))
|
|
];
|
|
case "IsInf":
|
|
return [
|
|
ops.isInf((0, _utils.getTensor)(node.inputNames[0], tensorMap, context))
|
|
];
|
|
case "IsFinite":
|
|
return [
|
|
ops.isFinite((0, _utils.getTensor)(node.inputNames[0], tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "basic_math";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1V4dK":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _tensorArray = require("../../executor/tensor_array");
|
|
var _tensorList = require("../../executor/tensor_list");
|
|
var _utils = require("./utils");
|
|
const executeOp = async (node, tensorMap, context)=>{
|
|
switch(node.op){
|
|
case "If":
|
|
case "StatelessIf":
|
|
{
|
|
const thenFunc = (0, _utils.getParamValue)("thenBranch", node, tensorMap, context);
|
|
const elseFunc = (0, _utils.getParamValue)("elseBranch", node, tensorMap, context);
|
|
const cond = (0, _utils.getParamValue)("cond", node, tensorMap, context);
|
|
const args = (0, _utils.getParamValue)("args", node, tensorMap, context);
|
|
const condValue = await cond.data();
|
|
if (condValue[0]) return context.functionMap[thenFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap);
|
|
else return context.functionMap[elseFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap);
|
|
}
|
|
case "While":
|
|
case "StatelessWhile":
|
|
{
|
|
const bodyFunc = (0, _utils.getParamValue)("body", node, tensorMap, context);
|
|
const condFunc = (0, _utils.getParamValue)("cond", node, tensorMap, context);
|
|
const args = (0, _utils.getParamValue)("args", node, tensorMap, context);
|
|
// Calculate the condition of the loop
|
|
const condResult = await context.functionMap[condFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap);
|
|
const argIds = args.map((tensor)=>tensor.id);
|
|
let condValue = await condResult[0].data();
|
|
// Dispose the intermediate tensors for condition function
|
|
condResult.forEach((tensor)=>{
|
|
if (!tensor.kept && argIds.indexOf(tensor.id) === -1) tensor.dispose();
|
|
});
|
|
let result = args;
|
|
while(condValue[0]){
|
|
// Record the previous result for intermediate tensor tracking
|
|
const origResult = result;
|
|
// Execution the body of the loop
|
|
result = await context.functionMap[bodyFunc].executeFunctionAsync(result, context.tensorArrayMap, context.tensorListMap);
|
|
const resultIds = result.map((tensor)=>tensor.id);
|
|
// Dispose the intermediate tensor for body function that is not global
|
|
// kept, not input/output of the body function
|
|
origResult.forEach((tensor)=>{
|
|
if (!tensor.kept && argIds.indexOf(tensor.id) === -1 && resultIds.indexOf(tensor.id) === -1) tensor.dispose();
|
|
});
|
|
// Recalcuate the condition of the loop using the latest results.
|
|
const condResult = await context.functionMap[condFunc].executeFunctionAsync(result, context.tensorArrayMap, context.tensorListMap);
|
|
condValue = await condResult[0].data();
|
|
// Dispose the intermediate tensors for condition function
|
|
condResult.forEach((tensor)=>{
|
|
if (!tensor.kept && argIds.indexOf(tensor.id) === -1 && resultIds.indexOf(tensor.id) === -1) tensor.dispose();
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
case "LoopCond":
|
|
{
|
|
const pred = (0, _utils.getParamValue)("pred", node, tensorMap, context);
|
|
return [
|
|
(0, _utils.cloneTensor)(pred)
|
|
];
|
|
}
|
|
case "Switch":
|
|
{
|
|
const pred = (0, _utils.getParamValue)("pred", node, tensorMap, context);
|
|
let data = (0, _utils.getParamValue)("data", node, tensorMap, context);
|
|
if (!data.kept) data = (0, _utils.cloneTensor)(data);
|
|
// Outputs nodes :0 => false, :1 => true
|
|
return (await pred.data())[0] ? [
|
|
undefined,
|
|
data
|
|
] : [
|
|
data,
|
|
undefined
|
|
];
|
|
}
|
|
case "Merge":
|
|
{
|
|
const inputName = node.inputNames.find((name)=>(0, _utils.getTensor)(name, tensorMap, context) !== undefined);
|
|
if (inputName) {
|
|
const data = (0, _utils.getTensor)(inputName, tensorMap, context);
|
|
return [
|
|
(0, _utils.cloneTensor)(data)
|
|
];
|
|
}
|
|
return undefined;
|
|
}
|
|
case "Enter":
|
|
{
|
|
const frameId = (0, _utils.getParamValue)("frameName", node, tensorMap, context);
|
|
const data = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
context.enterFrame(frameId);
|
|
return [
|
|
(0, _utils.cloneTensor)(data)
|
|
];
|
|
}
|
|
case "Exit":
|
|
{
|
|
const data = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
context.exitFrame();
|
|
return [
|
|
(0, _utils.cloneTensor)(data)
|
|
];
|
|
}
|
|
case "NextIteration":
|
|
{
|
|
const data = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
context.nextIteration();
|
|
return [
|
|
(0, _utils.cloneTensor)(data)
|
|
];
|
|
}
|
|
case "TensorArrayV3":
|
|
{
|
|
const size = (0, _utils.getParamValue)("size", node, tensorMap, context);
|
|
const dtype = (0, _utils.getParamValue)("dtype", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const dynamicSize = (0, _utils.getParamValue)("dynamicSize", node, tensorMap, context);
|
|
const clearAfterRead = (0, _utils.getParamValue)("clearAfterRead", node, tensorMap, context);
|
|
const identicalElementShapes = (0, _utils.getParamValue)("identicalElementShapes", node, tensorMap, context);
|
|
const name = (0, _utils.getParamValue)("name", node, tensorMap, context);
|
|
const tensorArray = new (0, _tensorArray.TensorArray)(name, dtype, size, elementShape, identicalElementShapes, dynamicSize, clearAfterRead);
|
|
context.addTensorArray(tensorArray);
|
|
return [
|
|
tensorArray.idTensor,
|
|
(0, _tfjsCore.scalar)(1.0)
|
|
];
|
|
}
|
|
case "TensorArrayWriteV3":
|
|
{
|
|
const id = (0, _utils.getParamValue)("tensorArrayId", node, tensorMap, context);
|
|
const index = (0, _utils.getParamValue)("index", node, tensorMap, context);
|
|
const writeTensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
const writeTensorArray = context.getTensorArray(id.id);
|
|
writeTensorArray.write(index, writeTensor);
|
|
return [
|
|
writeTensorArray.idTensor
|
|
];
|
|
}
|
|
case "TensorArrayReadV3":
|
|
{
|
|
const readId = (0, _utils.getParamValue)("tensorArrayId", node, tensorMap, context);
|
|
const readIndex = (0, _utils.getParamValue)("index", node, tensorMap, context);
|
|
const readTensorArray = context.getTensorArray(readId.id);
|
|
return [
|
|
readTensorArray.read(readIndex)
|
|
];
|
|
}
|
|
case "TensorArrayGatherV3":
|
|
{
|
|
const gatherId = (0, _utils.getParamValue)("tensorArrayId", node, tensorMap, context);
|
|
const gatherIndices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
const gatherDtype = (0, _utils.getParamValue)("dtype", node, tensorMap, context);
|
|
const gatherTensorArray = context.getTensorArray(gatherId.id);
|
|
return [
|
|
gatherTensorArray.gather(gatherIndices, gatherDtype)
|
|
];
|
|
}
|
|
case "TensorArrayScatterV3":
|
|
{
|
|
const scatterId = (0, _utils.getParamValue)("tensorArrayId", node, tensorMap, context);
|
|
const scatterIndices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
const scatterTensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
const scatterTensorArray = context.getTensorArray(scatterId.id);
|
|
scatterTensorArray.scatter(scatterIndices, scatterTensor);
|
|
return [
|
|
scatterTensorArray.idTensor
|
|
];
|
|
}
|
|
case "TensorArrayConcatV3":
|
|
{
|
|
const concatId = (0, _utils.getParamValue)("tensorArrayId", node, tensorMap, context);
|
|
const concatTensorArray = context.getTensorArray(concatId.id);
|
|
const concatDtype = (0, _utils.getParamValue)("dtype", node, tensorMap, context);
|
|
return [
|
|
concatTensorArray.concat(concatDtype)
|
|
];
|
|
}
|
|
case "TensorArraySplitV3":
|
|
{
|
|
const splitId = (0, _utils.getParamValue)("tensorArrayId", node, tensorMap, context);
|
|
const splitTensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
const lengths = (0, _utils.getParamValue)("lengths", node, tensorMap, context);
|
|
const splitTensorArray = context.getTensorArray(splitId.id);
|
|
splitTensorArray.split(lengths, splitTensor);
|
|
return [
|
|
splitTensorArray.idTensor
|
|
];
|
|
}
|
|
case "TensorArraySizeV3":
|
|
{
|
|
const sizeId = (0, _utils.getParamValue)("tensorArrayId", node, tensorMap, context);
|
|
const sizeTensorArray = context.getTensorArray(sizeId.id);
|
|
return [
|
|
(0, _tfjsCore.scalar)(sizeTensorArray.size(), "int32")
|
|
];
|
|
}
|
|
case "TensorArrayCloseV3":
|
|
{
|
|
const closeId = (0, _utils.getParamValue)("tensorArrayId", node, tensorMap, context);
|
|
const closeTensorArray = context.getTensorArray(closeId.id);
|
|
closeTensorArray.clearAndClose();
|
|
return [
|
|
closeTensorArray.idTensor
|
|
];
|
|
}
|
|
case "TensorListSetItem":
|
|
{
|
|
const idTensor = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const index = (0, _utils.getParamValue)("index", node, tensorMap, context);
|
|
const writeTensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
const tensorList = context.getTensorList(idTensor.id);
|
|
tensorList.setItem(index, writeTensor);
|
|
return [
|
|
tensorList.idTensor
|
|
];
|
|
}
|
|
case "TensorListGetItem":
|
|
{
|
|
const idTensor = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const readIndex = (0, _utils.getParamValue)("index", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const elementDType = (0, _utils.getParamValue)("elementDType", node, tensorMap, context);
|
|
const tensorList = context.getTensorList(idTensor.id);
|
|
return [
|
|
tensorList.getItem(readIndex, elementShape, elementDType)
|
|
];
|
|
}
|
|
case "TensorListScatterV2":
|
|
case "TensorListScatter":
|
|
{
|
|
const scatterIndices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
const scatterTensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const numElements = (0, _utils.getParamValue)("numElements", node, tensorMap, context);
|
|
const tensorList = (0, _tensorList.scatter)(scatterTensor, scatterIndices, elementShape, numElements);
|
|
context.addTensorList(tensorList);
|
|
return [
|
|
tensorList.idTensor
|
|
];
|
|
}
|
|
case "TensorListReserve":
|
|
case "EmptyTensorList":
|
|
{
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const elementDtype = (0, _utils.getParamValue)("elementDType", node, tensorMap, context);
|
|
let numElementsParam;
|
|
if (node.op === "TensorListReserve") numElementsParam = "numElements";
|
|
else numElementsParam = "maxNumElements";
|
|
const numElements = (0, _utils.getParamValue)(numElementsParam, node, tensorMap, context);
|
|
const maxNumElements = node.op === "TensorListReserve" ? -1 : numElements;
|
|
const tensorList = (0, _tensorList.reserve)(elementShape, elementDtype, numElements, maxNumElements);
|
|
context.addTensorList(tensorList);
|
|
return [
|
|
tensorList.idTensor
|
|
];
|
|
}
|
|
case "TensorListGather":
|
|
{
|
|
const gatherId = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const gatherIndices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const elementDtype = (0, _utils.getParamValue)("elementDType", node, tensorMap, context);
|
|
const tensorList = context.getTensorList(gatherId.id);
|
|
return [
|
|
tensorList.gather(gatherIndices, elementDtype, elementShape)
|
|
];
|
|
}
|
|
case "TensorListStack":
|
|
{
|
|
const idTensor = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const elementDtype = (0, _utils.getParamValue)("elementDType", node, tensorMap, context);
|
|
const numElements = (0, _utils.getParamValue)("numElements", node, tensorMap, context);
|
|
const tensorList = context.getTensorList(idTensor.id);
|
|
return [
|
|
tensorList.stack(elementShape, elementDtype, numElements)
|
|
];
|
|
}
|
|
case "TensorListFromTensor":
|
|
{
|
|
const tensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const elementDtype = (0, _utils.getParamValue)("elementDType", node, tensorMap, context);
|
|
const tensorList = (0, _tensorList.fromTensor)(tensor, elementShape, elementDtype);
|
|
context.addTensorList(tensorList);
|
|
return [
|
|
tensorList.idTensor
|
|
];
|
|
}
|
|
case "TensorListConcat":
|
|
case "TensorListConcatV2":
|
|
{
|
|
const concatId = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const tensorList = context.getTensorList(concatId.id);
|
|
const concatDtype = (0, _utils.getParamValue)("dtype", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
return [
|
|
tensorList.concat(concatDtype, elementShape)
|
|
];
|
|
}
|
|
case "TensorListPushBack":
|
|
{
|
|
const idTensor = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const writeTensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
const tensorList = context.getTensorList(idTensor.id);
|
|
tensorList.pushBack(writeTensor);
|
|
return [
|
|
tensorList.idTensor
|
|
];
|
|
}
|
|
case "TensorListPopBack":
|
|
{
|
|
const idTensor = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const elementDType = (0, _utils.getParamValue)("elementDType", node, tensorMap, context);
|
|
const tensorList = context.getTensorList(idTensor.id);
|
|
return [
|
|
tensorList.popBack(elementShape, elementDType)
|
|
];
|
|
}
|
|
case "TensorListSplit":
|
|
{
|
|
const splitTensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
const elementShape = (0, _utils.getParamValue)("elementShape", node, tensorMap, context);
|
|
const lengths = (0, _utils.getParamValue)("lengths", node, tensorMap, context);
|
|
const tensorList = (0, _tensorList.split)(splitTensor, lengths, elementShape);
|
|
context.addTensorList(tensorList);
|
|
return [
|
|
tensorList.idTensor
|
|
];
|
|
}
|
|
case "TensorListLength":
|
|
{
|
|
const idTensor = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const tensorList = context.getTensorList(idTensor.id);
|
|
return [
|
|
(0, _tfjsCore.scalar)(tensorList.size(), "int32")
|
|
];
|
|
}
|
|
case "TensorListResize":
|
|
{
|
|
const idTensor = (0, _utils.getParamValue)("tensorListId", node, tensorMap, context);
|
|
const size = (0, _utils.getParamValue)("size", node, tensorMap, context);
|
|
const srcTensorList = context.getTensorList(idTensor.id);
|
|
const destTensorList = srcTensorList.resize(size);
|
|
context.addTensorList(destTensorList);
|
|
return [
|
|
destTensorList.idTensor
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "control";
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../../executor/tensor_array":"1VnUW","../../executor/tensor_list":"bKjQu","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1VnUW":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* The TensorArray object keeps an array of Tensors. It
|
|
* allows reading from the array and writing to the array.
|
|
*/ parcelHelpers.export(exports, "TensorArray", ()=>TensorArray);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _tensorUtils = require("./tensor_utils");
|
|
class 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.idTensor = (0, _tfjsCore.scalar)(0);
|
|
(0, _tfjsCore.keep)(this.idTensor);
|
|
}
|
|
get id() {
|
|
return this.idTensor.id;
|
|
}
|
|
get closed() {
|
|
return this.closed_;
|
|
}
|
|
/**
|
|
* Dispose the tensors and idTensor and mark the TensoryArray as closed.
|
|
*/ clearAndClose(keepIds) {
|
|
this.tensors.forEach((tensor)=>{
|
|
if (keepIds == null || !keepIds.has(tensor.tensor.id)) tensor.tensor.dispose();
|
|
});
|
|
this.tensors = [];
|
|
this.closed_ = true;
|
|
this.idTensor.dispose();
|
|
}
|
|
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;
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(this.elementShape, tensor.shape, `TensorArray ${this.name}: Could not write to TensorArray index ${index}.`);
|
|
if (t.read) throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${index}, because it has already been read.`);
|
|
if (t.written) throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${index}, because it has already been written.`);
|
|
t.tensor = tensor;
|
|
(0, _tfjsCore.keep)(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 (0, _tfjsCore.tensor)([], [
|
|
0
|
|
].concat(this.elementShape));
|
|
// Read all the PersistentTensors into a vector to keep track of
|
|
// their memory.
|
|
const tensors = this.readMany(indices);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(this.elementShape, tensors[0].shape, "TensorArray shape mismatch: ");
|
|
return (0, _tfjsCore.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 (0, _tfjsCore.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);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(this.elementShape, tensors[0].shape, `TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${tensors[0].shape})`);
|
|
return (0, _tfjsCore.concat)(tensors, 0);
|
|
}
|
|
/**
|
|
* Scatter the values of a Tensor in specific indices of a TensorArray.
|
|
* @param indices number[] 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, (0, _tfjsCore.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 = [];
|
|
(0, _tfjsCore.tidy)(()=>{
|
|
tensor = (0, _tfjsCore.reshape)(tensor, [
|
|
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] = (0, _tfjsCore.reshape)((0, _tfjsCore.slice)(tensor, indices, sizes), this.elementShape);
|
|
}
|
|
return tensors;
|
|
});
|
|
const indices = [];
|
|
for(let i = 0; i < length.length; i++)indices[i] = i;
|
|
this.writeMany(indices, tensors);
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./tensor_utils":"bzuYR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bzuYR":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Used by TensorList and TensorArray to verify if elementShape matches, support
|
|
* negative value as the dim shape.
|
|
* @param shapeA
|
|
* @param shapeB
|
|
* @param errorMessagePrefix
|
|
*/ parcelHelpers.export(exports, "assertShapesMatchAllowUndefinedSize", ()=>assertShapesMatchAllowUndefinedSize);
|
|
parcelHelpers.export(exports, "fullDefinedShape", ()=>fullDefinedShape);
|
|
/**
|
|
* Generate the output element shape from the list elementShape, list tensors
|
|
* and input param.
|
|
* @param listElementShape
|
|
* @param tensors
|
|
* @param elementShape
|
|
*/ parcelHelpers.export(exports, "inferElementShape", ()=>inferElementShape);
|
|
parcelHelpers.export(exports, "mergeElementShape", ()=>mergeElementShape);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function assertShapesMatchAllowUndefinedSize(shapeA, shapeB, errorMessagePrefix = "") {
|
|
// constant shape means unknown rank
|
|
if (typeof shapeA === "number" || typeof shapeB === "number") return;
|
|
(0, _tfjsCore.util).assert(shapeA.length === shapeB.length, ()=>errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);
|
|
for(let i = 0; i < shapeA.length; i++){
|
|
const dim0 = shapeA[i];
|
|
const dim1 = shapeB[i];
|
|
(0, _tfjsCore.util).assert(dim0 < 0 || dim1 < 0 || dim0 === dim1, ()=>errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);
|
|
}
|
|
}
|
|
function fullDefinedShape(elementShape) {
|
|
if (typeof elementShape === "number" || elementShape.some((dim)=>dim < 0)) return false;
|
|
return true;
|
|
}
|
|
function inferElementShape(listElementShape, tensors, elementShape) {
|
|
let partialShape = mergeElementShape(listElementShape, elementShape);
|
|
const notfullDefinedShape = !fullDefinedShape(partialShape);
|
|
if (notfullDefinedShape && tensors.length === 0) throw new Error(`Tried to calculate elements of an empty list` + ` with non-fully-defined elementShape: ${partialShape}`);
|
|
if (notfullDefinedShape) tensors.forEach((tensor)=>{
|
|
partialShape = mergeElementShape(tensor.shape, partialShape);
|
|
});
|
|
if (!fullDefinedShape(partialShape)) throw new Error(`Non-fully-defined elementShape: ${partialShape}`);
|
|
return partialShape;
|
|
}
|
|
function mergeElementShape(elementShapeA, elementShapeB) {
|
|
if (typeof elementShapeA === "number") return elementShapeB;
|
|
if (typeof elementShapeB === "number") return elementShapeA;
|
|
if (elementShapeA.length !== elementShapeB.length) throw new Error(`Incompatible ranks during merge: ${elementShapeA} vs. ${elementShapeB}`);
|
|
const result = [];
|
|
for(let i = 0; i < elementShapeA.length; ++i){
|
|
const dim0 = elementShapeA[i];
|
|
const dim1 = elementShapeB[i];
|
|
if (dim0 >= 0 && dim1 >= 0 && dim0 !== dim1) throw new Error(`Incompatible shape during merge: ${elementShapeA} vs. ${elementShapeB}`);
|
|
result[i] = dim0 >= 0 ? dim0 : dim1;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bKjQu":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* TensorList stores a container of `tf.Tensor` objects, which are accessible
|
|
* via tensors field.
|
|
*
|
|
* In order to get a copy of the underlying list, use the copy method:
|
|
* ```
|
|
* TensorList b = a.copy();
|
|
* b.tensors().pushBack(t); // This does not modify a.tensors().
|
|
* ```
|
|
*
|
|
* Note that this is not a deep copy: the memory locations of the underlying
|
|
* tensors will still point to the same locations of the corresponding tensors
|
|
* in the original.
|
|
*/ parcelHelpers.export(exports, "TensorList", ()=>TensorList);
|
|
/**
|
|
* Creates a TensorList which, when stacked, has the value of tensor.
|
|
* @param tensor from tensor
|
|
* @param elementShape output tensor element shape
|
|
*/ parcelHelpers.export(exports, "fromTensor", ()=>fromTensor);
|
|
/**
|
|
* Return a TensorList of the given size with empty elements.
|
|
* @param elementShape the shape of the future elements of the list
|
|
* @param elementDtype the desired type of elements in the list
|
|
* @param numElements the number of elements to reserve
|
|
* @param maxNumElements the maximum number of elements in th list
|
|
*/ parcelHelpers.export(exports, "reserve", ()=>reserve);
|
|
/**
|
|
* Put tensors at specific indices of a stacked tensor into a TensorList.
|
|
* @param indices list of indices on how to scatter the tensor.
|
|
* @param tensor input tensor.
|
|
* @param elementShape the shape of the future elements of the list
|
|
* @param numElements the number of elements to scatter
|
|
*/ parcelHelpers.export(exports, "scatter", ()=>scatter);
|
|
/**
|
|
* Split the values of a Tensor into a TensorList.
|
|
* @param length the lengths to use when splitting value along
|
|
* its first dimension.
|
|
* @param tensor the tensor to split.
|
|
* @param elementShape the shape of the future elements of the list
|
|
*/ parcelHelpers.export(exports, "split", ()=>split);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _tensorUtils = require("./tensor_utils");
|
|
class TensorList {
|
|
get id() {
|
|
return this.idTensor.id;
|
|
}
|
|
/**
|
|
*
|
|
* @param tensors list of tensors
|
|
* @param elementShape shape of each tensor, this can be a single number (any
|
|
* shape is allowed) or partial shape (dim = -1).
|
|
* @param elementDtype data type of each tensor
|
|
* @param maxNumElements The maximum allowed size of `tensors`. Defaults to -1
|
|
* meaning that the size of `tensors` is unbounded.
|
|
*/ constructor(tensors, elementShape, elementDtype, maxNumElements = -1){
|
|
this.tensors = tensors;
|
|
this.elementShape = elementShape;
|
|
this.elementDtype = elementDtype;
|
|
if (tensors != null) tensors.forEach((tensor)=>{
|
|
if (elementDtype !== tensor.dtype) throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${tensor.dtype}`);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(elementShape, tensor.shape, "TensorList shape mismatch: ");
|
|
(0, _tfjsCore.keep)(tensor);
|
|
});
|
|
this.idTensor = (0, _tfjsCore.scalar)(0);
|
|
this.maxNumElements = maxNumElements;
|
|
(0, _tfjsCore.keep)(this.idTensor);
|
|
}
|
|
/**
|
|
* Get a new TensorList containing a copy of the underlying tensor container.
|
|
*/ copy() {
|
|
return new TensorList([
|
|
...this.tensors
|
|
], this.elementShape, this.elementDtype);
|
|
}
|
|
/**
|
|
* Dispose the tensors and idTensor and clear the tensor list.
|
|
*/ clearAndClose(keepIds) {
|
|
this.tensors.forEach((tensor)=>{
|
|
if (keepIds == null || !keepIds.has(tensor.id)) tensor.dispose();
|
|
});
|
|
this.tensors.length = 0;
|
|
this.idTensor.dispose();
|
|
}
|
|
/**
|
|
* The size of the tensors in the tensor list.
|
|
*/ size() {
|
|
return this.tensors.length;
|
|
}
|
|
/**
|
|
* Return a tensor that stacks a list of rank-R tf.Tensors into one rank-(R+1)
|
|
* tf.Tensor.
|
|
* @param elementShape shape of each tensor
|
|
* @param elementDtype data type of each tensor
|
|
* @param numElements the number of elements to stack
|
|
*/ stack(elementShape, elementDtype, numElements = -1) {
|
|
if (elementDtype !== this.elementDtype) throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${this.elementDtype}`);
|
|
if (numElements !== -1 && this.tensors.length !== numElements) throw new Error(`Operation expected a list with ${numElements} elements but got a list with ${this.tensors.length} elements.`);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(elementShape, this.elementShape, "TensorList shape mismatch: ");
|
|
const outputElementShape = (0, _tensorUtils.inferElementShape)(this.elementShape, this.tensors, elementShape);
|
|
return (0, _tfjsCore.tidy)(()=>{
|
|
const reshapedTensors = this.tensors.map((tensor)=>(0, _tfjsCore.reshape)(tensor, outputElementShape));
|
|
return (0, _tfjsCore.stack)(reshapedTensors, 0);
|
|
});
|
|
}
|
|
/**
|
|
* Pop a tensor from the end of the list.
|
|
* @param elementShape shape of the tensor
|
|
* @param elementDtype data type of the tensor
|
|
*/ popBack(elementShape, elementDtype) {
|
|
if (elementDtype !== this.elementDtype) throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${this.elementDtype}`);
|
|
if (this.size() === 0) throw new Error("Trying to pop from an empty list.");
|
|
const outputElementShape = (0, _tensorUtils.inferElementShape)(this.elementShape, this.tensors, elementShape);
|
|
const tensor = this.tensors.pop();
|
|
tensor.kept = false;
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(tensor.shape, elementShape, "TensorList shape mismatch: ");
|
|
return (0, _tfjsCore.reshape)(tensor, outputElementShape);
|
|
}
|
|
/**
|
|
* Push a tensor to the end of the list.
|
|
* @param tensor Tensor to be pushed.
|
|
*/ pushBack(tensor) {
|
|
if (tensor.dtype !== this.elementDtype) throw new Error(`Invalid data types; op elements ${tensor.dtype}, but list elements ${this.elementDtype}`);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(tensor.shape, this.elementShape, "TensorList shape mismatch: ");
|
|
if (this.maxNumElements === this.size()) throw new Error(`Trying to push element into a full list.`);
|
|
(0, _tfjsCore.keep)(tensor);
|
|
this.tensors.push(tensor);
|
|
}
|
|
/**
|
|
* Update the size of the list.
|
|
* @param size the new size of the list.
|
|
*/ resize(size) {
|
|
if (size < 0) throw new Error(`TensorListResize expects size to be non-negative. Got: ${size}`);
|
|
if (this.maxNumElements !== -1 && size > this.maxNumElements) throw new Error(`TensorListResize input size ${size} is greater maxNumElement ${this.maxNumElements}.`);
|
|
const destTensorList = new TensorList([], this.elementShape, this.elementDtype, this.maxNumElements);
|
|
destTensorList.tensors.length = size;
|
|
for(let i = 0; i < Math.min(this.tensors.length, size); ++i)destTensorList.tensors[i] = this.tensors[i];
|
|
return destTensorList;
|
|
}
|
|
/**
|
|
* Retrieve the element at the provided index
|
|
* @param elementShape shape of the tensor
|
|
* @param elementDtype dtype of the tensor
|
|
* @param elementIndex index of the tensor
|
|
*/ getItem(elementIndex, elementShape, elementDtype) {
|
|
if (elementDtype !== this.elementDtype) throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${this.elementDtype}`);
|
|
if (elementIndex < 0 || elementIndex > this.tensors.length) throw new Error(`Trying to access element ${elementIndex} in a list with ${this.tensors.length} elements.`);
|
|
if (this.tensors[elementIndex] == null) throw new Error(`element at index ${elementIndex} is null.`);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(this.tensors[elementIndex].shape, elementShape, "TensorList shape mismatch: ");
|
|
const outputElementShape = (0, _tensorUtils.inferElementShape)(this.elementShape, this.tensors, elementShape);
|
|
return (0, _tfjsCore.reshape)(this.tensors[elementIndex], outputElementShape);
|
|
}
|
|
/**
|
|
* Set the tensor at the index
|
|
* @param elementIndex index of the tensor
|
|
* @param tensor the tensor to be inserted into the list
|
|
*/ setItem(elementIndex, tensor) {
|
|
if (tensor.dtype !== this.elementDtype) throw new Error(`Invalid data types; op elements ${tensor.dtype}, but list elements ${this.elementDtype}`);
|
|
if (elementIndex < 0 || this.maxNumElements !== -1 && elementIndex >= this.maxNumElements) throw new Error(`Trying to set element ${elementIndex} in a list with max ${this.maxNumElements} elements.`);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(this.elementShape, tensor.shape, "TensorList shape mismatch: ");
|
|
(0, _tfjsCore.keep)(tensor);
|
|
// dispose the previous value if it is replacing.
|
|
if (this.tensors[elementIndex] != null) this.tensors[elementIndex].kept = false;
|
|
this.tensors[elementIndex] = tensor;
|
|
}
|
|
/**
|
|
* Return selected values in the TensorList as a stacked Tensor. All of
|
|
* selected values must have been written and their shapes must all match.
|
|
* @param indices indices of tensors to gather
|
|
* @param elementDtype output tensor dtype
|
|
* @param elementShape output tensor element shape
|
|
*/ gather(indices, elementDtype, elementShape) {
|
|
if (elementDtype !== this.elementDtype) throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${this.elementDtype}`);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(this.elementShape, elementShape, "TensorList shape mismatch: ");
|
|
// When indices is greater than the size of the list, indices beyond the
|
|
// size of the list are ignored.
|
|
indices = indices.slice(0, this.size());
|
|
const outputElementShape = (0, _tensorUtils.inferElementShape)(this.elementShape, this.tensors, elementShape);
|
|
if (indices.length === 0) return (0, _tfjsCore.tensor)([], [
|
|
0
|
|
].concat(outputElementShape));
|
|
return (0, _tfjsCore.tidy)(()=>{
|
|
const tensors = indices.map((i)=>(0, _tfjsCore.reshape)(this.tensors[i], outputElementShape));
|
|
return (0, _tfjsCore.stack)(tensors, 0);
|
|
});
|
|
}
|
|
/**
|
|
* Return the values in the TensorList as a concatenated Tensor.
|
|
* @param elementDtype output tensor dtype
|
|
* @param elementShape output tensor element shape
|
|
*/ concat(elementDtype, elementShape) {
|
|
if (!!elementDtype && elementDtype !== this.elementDtype) throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${elementDtype}`);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(this.elementShape, elementShape, "TensorList shape mismatch: ");
|
|
const outputElementShape = (0, _tensorUtils.inferElementShape)(this.elementShape, this.tensors, elementShape);
|
|
if (this.size() === 0) return (0, _tfjsCore.tensor)([], [
|
|
0
|
|
].concat(outputElementShape));
|
|
return (0, _tfjsCore.tidy)(()=>{
|
|
const tensors = this.tensors.map((t)=>(0, _tfjsCore.reshape)(t, outputElementShape));
|
|
return (0, _tfjsCore.concat)(tensors, 0);
|
|
});
|
|
}
|
|
}
|
|
function fromTensor(tensor, elementShape, elementDtype) {
|
|
const dtype = tensor.dtype;
|
|
if (tensor.shape.length < 1) throw new Error(`Tensor must be at least a vector, but saw shape: ${tensor.shape}`);
|
|
if (tensor.dtype !== elementDtype) throw new Error(`Invalid data types; op elements ${tensor.dtype}, but list elements ${elementDtype}`);
|
|
const tensorElementShape = tensor.shape.slice(1);
|
|
(0, _tensorUtils.assertShapesMatchAllowUndefinedSize)(tensorElementShape, elementShape, "TensorList shape mismatch: ");
|
|
const tensorList = (0, _tfjsCore.unstack)(tensor);
|
|
return new TensorList(tensorList, elementShape, dtype);
|
|
}
|
|
function reserve(elementShape, elementDtype, numElements, maxNumElements) {
|
|
return new TensorList([], elementShape, elementDtype, maxNumElements);
|
|
}
|
|
function scatter(tensor, indices, elementShape, numElements) {
|
|
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 (numElements != null && numElements !== -1 && maxIndex >= numElements) throw new Error(`Max index must be < array size (${maxIndex} vs. ${numElements})`);
|
|
const list = new TensorList([], elementShape, tensor.dtype, numElements);
|
|
const tensors = (0, _tfjsCore.unstack)(tensor, 0);
|
|
indices.forEach((value, index)=>{
|
|
list.setItem(value, tensors[index]);
|
|
});
|
|
return list;
|
|
}
|
|
function split(tensor, length, elementShape) {
|
|
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}`);
|
|
const shapeWithoutFirstDim = tensor.shape.slice(1);
|
|
const outputElementShape = (0, _tensorUtils.mergeElementShape)(shapeWithoutFirstDim, elementShape);
|
|
const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;
|
|
const tensors = (0, _tfjsCore.tidy)(()=>{
|
|
const tensors = [];
|
|
tensor = (0, _tfjsCore.reshape)(tensor, [
|
|
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] = (0, _tfjsCore.reshape)((0, _tfjsCore.slice)(tensor, indices, sizes), outputElementShape);
|
|
}
|
|
tensor.dispose();
|
|
return tensors;
|
|
});
|
|
const list = new TensorList([], elementShape, tensor.dtype, length.length);
|
|
for(let i = 0; i < tensors.length; i++)list.setItem(i, tensors[i]);
|
|
return list;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./tensor_utils":"bzuYR","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"b2H1R":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
function fusedConvAndDepthWiseParams(node, tensorMap, context) {
|
|
const [extraOp, activationFunc] = (0, _utils.getParamValue)("fusedOps", node, tensorMap, context);
|
|
const isBiasAdd = extraOp === "biasadd";
|
|
const noBiasAdd = !isBiasAdd;
|
|
const isPrelu = activationFunc === "prelu";
|
|
const isBatchNorm = extraOp === "fusedbatchnorm";
|
|
const numArgs = (0, _utils.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 && isBiasAdd && 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 = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getPadding)(node, tensorMap, context);
|
|
const dataFormat = (0, _utils.getParamValue)("dataFormat", node, tensorMap, context).toUpperCase();
|
|
const dilations = (0, _utils.getParamValue)("dilations", node, tensorMap, context);
|
|
let [biasArg, preluArg] = (0, _utils.getParamValue)("args", node, tensorMap, context);
|
|
if (noBiasAdd) {
|
|
preluArg = biasArg;
|
|
biasArg = undefined;
|
|
}
|
|
const leakyreluAlpha = (0, _utils.getParamValue)("leakyreluAlpha", node, tensorMap, context);
|
|
return {
|
|
stride,
|
|
pad,
|
|
dataFormat,
|
|
dilations,
|
|
biasArg,
|
|
preluArg,
|
|
activationFunc,
|
|
leakyreluAlpha
|
|
};
|
|
}
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "Conv1D":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("stride", node, tensorMap, context);
|
|
const pad = (0, _utils.getParamValue)("pad", node, tensorMap, context);
|
|
const dataFormat = (0, _utils.getParamValue)("dataFormat", node, tensorMap, context).toUpperCase();
|
|
const dilation = (0, _utils.getParamValue)("dilation", node, tensorMap, context);
|
|
return [
|
|
ops.conv1d((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("filter", node, tensorMap, context), stride, pad, dataFormat, dilation)
|
|
];
|
|
}
|
|
case "Conv2D":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getPadding)(node, tensorMap, context);
|
|
const dataFormat = (0, _utils.getParamValue)("dataFormat", node, tensorMap, context).toUpperCase();
|
|
const dilations = (0, _utils.getParamValue)("dilations", node, tensorMap, context);
|
|
return [
|
|
ops.conv2d((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("filter", node, tensorMap, context), [
|
|
stride[1],
|
|
stride[2]
|
|
], pad, dataFormat, [
|
|
dilations[1],
|
|
dilations[2]
|
|
])
|
|
];
|
|
}
|
|
case "_FusedConv2D":
|
|
{
|
|
const { stride, pad, dataFormat, dilations, biasArg, preluArg, activationFunc, leakyreluAlpha } = fusedConvAndDepthWiseParams(node, tensorMap, context);
|
|
return [
|
|
ops.fused.conv2d({
|
|
x: (0, _utils.getParamValue)("x", node, tensorMap, context),
|
|
filter: (0, _utils.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,
|
|
leakyreluAlpha
|
|
})
|
|
];
|
|
}
|
|
case "FusedDepthwiseConv2dNative":
|
|
{
|
|
const { stride, pad, dataFormat, dilations, biasArg, preluArg, activationFunc, leakyreluAlpha } = fusedConvAndDepthWiseParams(node, tensorMap, context);
|
|
return [
|
|
ops.fused.depthwiseConv2d({
|
|
x: (0, _utils.getParamValue)("x", node, tensorMap, context),
|
|
filter: (0, _utils.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,
|
|
leakyreluAlpha
|
|
})
|
|
];
|
|
}
|
|
case "Conv2DBackpropInput":
|
|
case "Conv2dTranspose":
|
|
{
|
|
const shape = (0, _utils.getParamValue)("outputShape", node, tensorMap, context);
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getPadding)(node, tensorMap, context);
|
|
return [
|
|
ops.conv2dTranspose((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("filter", node, tensorMap, context), shape, [
|
|
stride[1],
|
|
stride[2]
|
|
], pad)
|
|
];
|
|
}
|
|
case "DepthwiseConv2dNative":
|
|
case "DepthwiseConv2d":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getPadding)(node, tensorMap, context);
|
|
const dilations = (0, _utils.getParamValue)("dilations", node, tensorMap, context);
|
|
const dataFormat = (0, _utils.getParamValue)("dataFormat", node, tensorMap, context).toUpperCase();
|
|
return [
|
|
ops.depthwiseConv2d((0, _utils.getParamValue)("input", node, tensorMap, context), (0, _utils.getParamValue)("filter", node, tensorMap, context), [
|
|
stride[1],
|
|
stride[2]
|
|
], pad, dataFormat, [
|
|
dilations[1],
|
|
dilations[2]
|
|
])
|
|
];
|
|
}
|
|
case "Conv3D":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getParamValue)("pad", node, tensorMap, context);
|
|
const dataFormat = (0, _utils.getParamValue)("dataFormat", node, tensorMap, context).toUpperCase();
|
|
const dilations = (0, _utils.getParamValue)("dilations", node, tensorMap, context);
|
|
return [
|
|
ops.conv3d((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("filter", node, tensorMap, context), [
|
|
stride[1],
|
|
stride[2],
|
|
stride[3]
|
|
], pad, dataFormat, [
|
|
dilations[1],
|
|
dilations[2],
|
|
dilations[3]
|
|
])
|
|
];
|
|
}
|
|
case "AvgPool":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getParamValue)("pad", node, tensorMap, context);
|
|
const kernelSize = (0, _utils.getParamValue)("kernelSize", node, tensorMap, context);
|
|
return [
|
|
ops.avgPool((0, _utils.getParamValue)("x", node, tensorMap, context), [
|
|
kernelSize[1],
|
|
kernelSize[2]
|
|
], [
|
|
stride[1],
|
|
stride[2]
|
|
], pad)
|
|
];
|
|
}
|
|
case "MaxPool":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getParamValue)("pad", node, tensorMap, context);
|
|
const kernelSize = (0, _utils.getParamValue)("kernelSize", node, tensorMap, context);
|
|
return [
|
|
ops.maxPool((0, _utils.getParamValue)("x", node, tensorMap, context), [
|
|
kernelSize[1],
|
|
kernelSize[2]
|
|
], [
|
|
stride[1],
|
|
stride[2]
|
|
], pad)
|
|
];
|
|
}
|
|
case "MaxPoolWithArgmax":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getParamValue)("pad", node, tensorMap, context);
|
|
const kernelSize = (0, _utils.getParamValue)("kernelSize", node, tensorMap, context);
|
|
const includeBatchInIndex = (0, _utils.getParamValue)("includeBatchInIndex", node, tensorMap, context);
|
|
const { result, indexes } = ops.maxPoolWithArgmax((0, _utils.getParamValue)("x", node, tensorMap, context), [
|
|
kernelSize[1],
|
|
kernelSize[2]
|
|
], [
|
|
stride[1],
|
|
stride[2]
|
|
], pad, includeBatchInIndex);
|
|
return [
|
|
result,
|
|
indexes
|
|
];
|
|
}
|
|
case "AvgPool3D":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getParamValue)("pad", node, tensorMap, context);
|
|
const kernelSize = (0, _utils.getParamValue)("kernelSize", node, tensorMap, context);
|
|
return [
|
|
ops.avgPool3d((0, _utils.getParamValue)("x", node, tensorMap, context), [
|
|
kernelSize[1],
|
|
kernelSize[2],
|
|
kernelSize[3]
|
|
], [
|
|
stride[1],
|
|
stride[2],
|
|
stride[3]
|
|
], pad)
|
|
];
|
|
}
|
|
case "MaxPool3D":
|
|
{
|
|
const stride = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getParamValue)("pad", node, tensorMap, context);
|
|
const kernelSize = (0, _utils.getParamValue)("kernelSize", node, tensorMap, context);
|
|
return [
|
|
ops.maxPool3d((0, _utils.getParamValue)("x", node, tensorMap, context), [
|
|
kernelSize[1],
|
|
kernelSize[2],
|
|
kernelSize[3]
|
|
], [
|
|
stride[1],
|
|
stride[2],
|
|
stride[3]
|
|
], pad)
|
|
];
|
|
}
|
|
case "Dilation2D":
|
|
{
|
|
const strides = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const pad = (0, _utils.getParamValue)("pad", node, tensorMap, context);
|
|
const dilations = (0, _utils.getParamValue)("dilations", node, tensorMap, context);
|
|
// strides: [1, stride_height, stride_width, 1].
|
|
const strideHeight = strides[1];
|
|
const strideWidth = strides[2];
|
|
// dilations: [1, dilation_height, dilation_width, 1].
|
|
const dilationHeight = dilations[1];
|
|
const dilationWidth = dilations[2];
|
|
return [
|
|
ops.dilation2d((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("filter", node, tensorMap, context), [
|
|
strideHeight,
|
|
strideWidth
|
|
], pad, [
|
|
dilationHeight,
|
|
dilationWidth
|
|
], "NHWC" /* dataFormat */ )
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "convolution";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kSSii":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "Fill":
|
|
{
|
|
const shape = (0, _utils.getParamValue)("shape", node, tensorMap, context);
|
|
const dtype = (0, _utils.getParamValue)("dtype", node, tensorMap, context);
|
|
const value = (0, _utils.getParamValue)("value", node, tensorMap, context);
|
|
return [
|
|
ops.fill(shape, value, dtype)
|
|
];
|
|
}
|
|
case "LinSpace":
|
|
{
|
|
const start = (0, _utils.getParamValue)("start", node, tensorMap, context);
|
|
const stop = (0, _utils.getParamValue)("stop", node, tensorMap, context);
|
|
const num = (0, _utils.getParamValue)("num", node, tensorMap, context);
|
|
return [
|
|
ops.linspace(start, stop, num)
|
|
];
|
|
}
|
|
case "Multinomial":
|
|
{
|
|
const logits = (0, _utils.getParamValue)("logits", node, tensorMap, context);
|
|
const numSamples = (0, _utils.getParamValue)("numSamples", node, tensorMap, context);
|
|
const seed = (0, _utils.getParamValue)("seed", node, tensorMap, context);
|
|
return [
|
|
ops.multinomial(logits, numSamples, seed)
|
|
];
|
|
}
|
|
case "OneHot":
|
|
{
|
|
const indices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
const depth = (0, _utils.getParamValue)("depth", node, tensorMap, context);
|
|
const onValue = (0, _utils.getParamValue)("onValue", node, tensorMap, context);
|
|
const offValue = (0, _utils.getParamValue)("offValue", node, tensorMap, context);
|
|
const dtype = (0, _utils.getParamValue)("dtype", node, tensorMap, context);
|
|
return [
|
|
ops.oneHot(indices, depth, onValue, offValue, dtype)
|
|
];
|
|
}
|
|
case "Ones":
|
|
return [
|
|
ops.ones((0, _utils.getParamValue)("shape", node, tensorMap, context), (0, _utils.getParamValue)("dtype", node, tensorMap, context))
|
|
];
|
|
case "OnesLike":
|
|
return [
|
|
ops.onesLike((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "RandomStandardNormal":
|
|
return [
|
|
ops.randomStandardNormal((0, _utils.getParamValue)("shape", node, tensorMap, context), (0, _utils.getParamValue)("dtype", node, tensorMap, context), (0, _utils.getParamValue)("seed", node, tensorMap, context))
|
|
];
|
|
case "RandomUniform":
|
|
return [
|
|
ops.randomUniform(// tslint:disable-next-line:no-any
|
|
(0, _utils.getParamValue)("shape", node, tensorMap, context), (0, _utils.getParamValue)("minval", node, tensorMap, context), (0, _utils.getParamValue)("maxval", node, tensorMap, context), (0, _utils.getParamValue)("dtype", node, tensorMap, context))
|
|
];
|
|
case "RandomUniformInt":
|
|
return [
|
|
ops.randomUniformInt((0, _utils.getParamValue)("shape", node, tensorMap, context), (0, _utils.getParamValue)("minval", node, tensorMap, context), (0, _utils.getParamValue)("maxval", node, tensorMap, context), (0, _utils.getParamValue)("seed", node, tensorMap, context))
|
|
];
|
|
case "Range":
|
|
{
|
|
const start = (0, _utils.getParamValue)("start", node, tensorMap, context);
|
|
const stop = (0, _utils.getParamValue)("stop", node, tensorMap, context);
|
|
const step = (0, _utils.getParamValue)("step", node, tensorMap, context);
|
|
return [
|
|
ops.range(start, stop, step, (0, _utils.getParamValue)("dtype", node, tensorMap, context))
|
|
];
|
|
}
|
|
case "TruncatedNormal":
|
|
{
|
|
const shape = (0, _utils.getParamValue)("shape", node, tensorMap, context);
|
|
const mean = (0, _utils.getParamValue)("mean", node, tensorMap, context);
|
|
const stdDev = (0, _utils.getParamValue)("stdDev", node, tensorMap, context);
|
|
const seed = (0, _utils.getParamValue)("seed", node, tensorMap, context);
|
|
return [
|
|
ops.truncatedNormal(shape, mean, stdDev, (0, _utils.getParamValue)("dtype", node, tensorMap, context), seed)
|
|
];
|
|
}
|
|
case "Zeros":
|
|
return [
|
|
ops.zeros((0, _utils.getParamValue)("shape", node, tensorMap, context), (0, _utils.getParamValue)("dtype", node, tensorMap, context))
|
|
];
|
|
case "ZerosLike":
|
|
return [
|
|
ops.zerosLike((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "creation";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"37XKU":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
function nmsParams(node, tensorMap, context) {
|
|
const boxes = (0, _utils.getParamValue)("boxes", node, tensorMap, context);
|
|
const scores = (0, _utils.getParamValue)("scores", node, tensorMap, context);
|
|
const maxOutputSize = (0, _utils.getParamValue)("maxOutputSize", node, tensorMap, context);
|
|
const iouThreshold = (0, _utils.getParamValue)("iouThreshold", node, tensorMap, context);
|
|
const scoreThreshold = (0, _utils.getParamValue)("scoreThreshold", node, tensorMap, context);
|
|
const softNmsSigma = (0, _utils.getParamValue)("softNmsSigma", node, tensorMap, context);
|
|
return {
|
|
boxes,
|
|
scores,
|
|
maxOutputSize,
|
|
iouThreshold,
|
|
scoreThreshold,
|
|
softNmsSigma
|
|
};
|
|
}
|
|
const executeOp = async (node, tensorMap, context, resourceManager, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "NonMaxSuppressionV5":
|
|
{
|
|
const { boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma } = nmsParams(node, tensorMap, context);
|
|
const result = await ops.image.nonMaxSuppressionWithScoreAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
|
|
return [
|
|
result.selectedIndices,
|
|
result.selectedScores
|
|
];
|
|
}
|
|
case "NonMaxSuppressionV4":
|
|
{
|
|
const { boxes, scores, maxOutputSize, iouThreshold, scoreThreshold } = nmsParams(node, tensorMap, context);
|
|
const padToMaxOutputSize = (0, _utils.getParamValue)("padToMaxOutputSize", node, tensorMap, context);
|
|
const result = await ops.image.nonMaxSuppressionPaddedAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize);
|
|
return [
|
|
result.selectedIndices,
|
|
result.validOutputs
|
|
];
|
|
}
|
|
case "NonMaxSuppressionV3":
|
|
case "NonMaxSuppressionV2":
|
|
{
|
|
const { boxes, scores, maxOutputSize, iouThreshold, scoreThreshold } = nmsParams(node, tensorMap, context);
|
|
return [
|
|
await ops.image.nonMaxSuppressionAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold)
|
|
];
|
|
}
|
|
case "Where":
|
|
{
|
|
const condition = ops.cast((0, _utils.getParamValue)("condition", node, tensorMap, context), "bool");
|
|
const result = [
|
|
await ops.whereAsync(condition)
|
|
];
|
|
condition.dispose();
|
|
return result;
|
|
}
|
|
case "ListDiff":
|
|
return ops.setdiff1dAsync((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("y", node, tensorMap, context));
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "dynamic";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9cjVI":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "LowerBound":
|
|
{
|
|
const sortedSequence = (0, _utils.getParamValue)("sortedSequence", node, tensorMap, context);
|
|
const values = (0, _utils.getParamValue)("values", node, tensorMap, context);
|
|
return [
|
|
ops.lowerBound(sortedSequence, values)
|
|
];
|
|
}
|
|
case "TopKV2":
|
|
{
|
|
const x = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const k = (0, _utils.getParamValue)("k", node, tensorMap, context);
|
|
const sorted = (0, _utils.getParamValue)("sorted", node, tensorMap, context);
|
|
const result = ops.topk(x, k, sorted);
|
|
return [
|
|
result.values,
|
|
result.indices
|
|
];
|
|
}
|
|
case "UpperBound":
|
|
{
|
|
const sortedSequence = (0, _utils.getParamValue)("sortedSequence", node, tensorMap, context);
|
|
const values = (0, _utils.getParamValue)("values", node, tensorMap, context);
|
|
return [
|
|
ops.upperBound(sortedSequence, values)
|
|
];
|
|
}
|
|
case "Unique":
|
|
{
|
|
const x = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const result = ops.unique(x);
|
|
return [
|
|
result.values,
|
|
result.indices
|
|
];
|
|
}
|
|
case "UniqueV2":
|
|
{
|
|
const x = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const result = ops.unique(x, axis);
|
|
return [
|
|
result.values,
|
|
result.indices
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "evaluation";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jqg8t":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "Const":
|
|
return tensorMap[node.name];
|
|
case "PlaceholderWithDefault":
|
|
const def = (0, _utils.getParamValue)("default", node, tensorMap, context);
|
|
return [
|
|
(0, _utils.getTensor)(node.name, tensorMap, context) || def
|
|
];
|
|
case "Placeholder":
|
|
return [
|
|
(0, _utils.getTensor)(node.name, tensorMap, context)
|
|
];
|
|
case "Identity":
|
|
case "StopGradient":
|
|
case "FakeQuantWithMinMaxVars":
|
|
{
|
|
const data = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
return [
|
|
(0, _utils.cloneTensor)(data)
|
|
];
|
|
}
|
|
case "IdentityN":
|
|
return (0, _utils.getParamValue)("x", node, tensorMap, context).map((t)=>(0, _utils.cloneTensor)(t));
|
|
case "Snapshot":
|
|
const snapshot = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
return [
|
|
(0, _utils.cloneTensor)(snapshot)
|
|
];
|
|
case "Shape":
|
|
return [
|
|
ops.tensor1d((0, _utils.getParamValue)("x", node, tensorMap, context).shape, "int32")
|
|
];
|
|
case "ShapeN":
|
|
return (0, _utils.getParamValue)("x", node, tensorMap, context).map((t)=>ops.tensor1d(t.shape));
|
|
case "Size":
|
|
return [
|
|
ops.scalar((0, _utils.getParamValue)("x", node, tensorMap, context).size, "int32")
|
|
];
|
|
case "Rank":
|
|
return [
|
|
ops.scalar((0, _utils.getParamValue)("x", node, tensorMap, context).rank, "int32")
|
|
];
|
|
case "NoOp":
|
|
return [
|
|
ops.scalar(1)
|
|
];
|
|
case "Print":
|
|
const input = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const data = (0, _utils.getParamValue)("data", node, tensorMap, context);
|
|
const message = (0, _utils.getParamValue)("message", node, tensorMap, context);
|
|
const summarize = (0, _utils.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 CATEGORY = "graph";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9g7sC":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _hashTable = require("../../executor/hash_table");
|
|
var _utils = require("./utils");
|
|
const executeOp = async (node, tensorMap, context, resourceManager)=>{
|
|
switch(node.op){
|
|
case "HashTable":
|
|
case "HashTableV2":
|
|
{
|
|
const existingTableHandle = resourceManager.getHashTableHandleByName(node.name);
|
|
// Table is shared with initializer.
|
|
if (existingTableHandle != null) return [
|
|
existingTableHandle
|
|
];
|
|
else {
|
|
const keyDType = (0, _utils.getParamValue)("keyDType", node, tensorMap, context);
|
|
const valueDType = (0, _utils.getParamValue)("valueDType", node, tensorMap, context);
|
|
const hashTable = new (0, _hashTable.HashTable)(keyDType, valueDType);
|
|
resourceManager.addHashTable(node.name, hashTable);
|
|
return [
|
|
hashTable.handle
|
|
];
|
|
}
|
|
}
|
|
case "InitializeTable":
|
|
case "InitializeTableV2":
|
|
case "LookupTableImport":
|
|
case "LookupTableImportV2":
|
|
{
|
|
const handle = (0, _utils.getParamValue)("tableHandle", node, tensorMap, context, resourceManager);
|
|
const keys = (0, _utils.getParamValue)("keys", node, tensorMap, context);
|
|
const values = (0, _utils.getParamValue)("values", node, tensorMap, context);
|
|
const hashTable = resourceManager.getHashTableById(handle.id);
|
|
return [
|
|
await hashTable.import(keys, values)
|
|
];
|
|
}
|
|
case "LookupTableFind":
|
|
case "LookupTableFindV2":
|
|
{
|
|
const handle = (0, _utils.getParamValue)("tableHandle", node, tensorMap, context, resourceManager);
|
|
const keys = (0, _utils.getParamValue)("keys", node, tensorMap, context);
|
|
const defaultValue = (0, _utils.getParamValue)("defaultValue", node, tensorMap, context);
|
|
const hashTable = resourceManager.getHashTableById(handle.id);
|
|
return [
|
|
await hashTable.find(keys, defaultValue)
|
|
];
|
|
}
|
|
case "LookupTableSize":
|
|
case "LookupTableSizeV2":
|
|
{
|
|
const handle = (0, _utils.getParamValue)("tableHandle", node, tensorMap, context, resourceManager);
|
|
const hashTable = resourceManager.getHashTableById(handle.id);
|
|
return [
|
|
hashTable.tensorSize()
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "hash_table";
|
|
|
|
},{"../../executor/hash_table":"fZZAu","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fZZAu":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Hashtable contains a set of tensors, which can be accessed by key.
|
|
*/ parcelHelpers.export(exports, "HashTable", ()=>HashTable);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
// tslint:disable-next-line: no-imports-from-dist
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
class HashTable {
|
|
get id() {
|
|
return this.handle.id;
|
|
}
|
|
/**
|
|
* Constructor of HashTable. Creates a hash table.
|
|
*
|
|
* @param keyDType `dtype` of the table keys.
|
|
* @param valueDType `dtype` of the table values.
|
|
*/ constructor(keyDType, valueDType){
|
|
this.keyDType = keyDType;
|
|
this.valueDType = valueDType;
|
|
this.handle = (0, _tfjsCore.scalar)(0);
|
|
// tslint:disable-next-line: no-any
|
|
this.tensorMap = new Map();
|
|
(0, _tfjsCore.keep)(this.handle);
|
|
}
|
|
/**
|
|
* Dispose the tensors and handle and clear the hashtable.
|
|
*/ clearAndClose() {
|
|
this.tensorMap.forEach((value)=>value.dispose());
|
|
this.tensorMap.clear();
|
|
this.handle.dispose();
|
|
}
|
|
/**
|
|
* The number of items in the hash table.
|
|
*/ size() {
|
|
return this.tensorMap.size;
|
|
}
|
|
/**
|
|
* The number of items in the hash table as a rank-0 tensor.
|
|
*/ tensorSize() {
|
|
return _opsForConverter.scalar(this.size(), "int32");
|
|
}
|
|
/**
|
|
* Replaces the contents of the table with the specified keys and values.
|
|
* @param keys Keys to store in the hashtable.
|
|
* @param values Values to store in the hashtable.
|
|
*/ async import(keys, values) {
|
|
this.checkKeyAndValueTensor(keys, values);
|
|
// We only store the primitive values of the keys, this allows lookup
|
|
// to be O(1).
|
|
const $keys = await keys.data();
|
|
// Clear the hashTable before inserting new values.
|
|
this.tensorMap.forEach((value)=>value.dispose());
|
|
this.tensorMap.clear();
|
|
return (0, _tfjsCore.tidy)(()=>{
|
|
const $values = (0, _tfjsCore.unstack)(values);
|
|
const keysLength = $keys.length;
|
|
const valuesLength = $values.length;
|
|
(0, _tfjsCore.util).assert(keysLength === valuesLength, ()=>`The number of elements doesn't match, keys has ` + `${keysLength} elements, the values has ${valuesLength} ` + `elements.`);
|
|
for(let i = 0; i < keysLength; i++){
|
|
const key = $keys[i];
|
|
const value = $values[i];
|
|
(0, _tfjsCore.keep)(value);
|
|
this.tensorMap.set(key, value);
|
|
}
|
|
return this.handle;
|
|
});
|
|
}
|
|
/**
|
|
* Looks up keys in a hash table, outputs the corresponding values.
|
|
*
|
|
* Performs batch lookups, for every element in the key tensor, `find`
|
|
* stacks the corresponding value into the return tensor.
|
|
*
|
|
* If an element is not present in the table, the given `defaultValue` is
|
|
* used.
|
|
*
|
|
* @param keys Keys to look up. Must have the same type as the keys of the
|
|
* table.
|
|
* @param defaultValue The scalar `defaultValue` is the value output for keys
|
|
* not present in the table. It must also be of the same type as the
|
|
* table values.
|
|
*/ async find(keys, defaultValue) {
|
|
this.checkKeyAndValueTensor(keys, defaultValue);
|
|
const $keys = await keys.data();
|
|
return (0, _tfjsCore.tidy)(()=>{
|
|
const result = [];
|
|
for(let i = 0; i < $keys.length; i++){
|
|
const key = $keys[i];
|
|
const value = this.findWithDefault(key, defaultValue);
|
|
result.push(value);
|
|
}
|
|
return (0, _tfjsCore.stack)(result);
|
|
});
|
|
}
|
|
// tslint:disable-next-line: no-any
|
|
findWithDefault(key, defaultValue) {
|
|
const result = this.tensorMap.get(key);
|
|
return result != null ? result : defaultValue;
|
|
}
|
|
checkKeyAndValueTensor(key, value) {
|
|
if (key.dtype !== this.keyDType) throw new Error(`Expect key dtype ${this.keyDType}, but got ` + `${key.dtype}`);
|
|
if (value.dtype !== this.valueDType) throw new Error(`Expect value dtype ${this.valueDType}, but got ` + `${value.dtype}`);
|
|
}
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5sGLS":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "ResizeBilinear":
|
|
{
|
|
const images = (0, _utils.getParamValue)("images", node, tensorMap, context);
|
|
const size = (0, _utils.getParamValue)("size", node, tensorMap, context);
|
|
const alignCorners = (0, _utils.getParamValue)("alignCorners", node, tensorMap, context);
|
|
const halfPixelCenters = (0, _utils.getParamValue)("halfPixelCenters", node, tensorMap, context);
|
|
return [
|
|
ops.image.resizeBilinear(images, [
|
|
size[0],
|
|
size[1]
|
|
], alignCorners, halfPixelCenters)
|
|
];
|
|
}
|
|
case "ResizeNearestNeighbor":
|
|
{
|
|
const images = (0, _utils.getParamValue)("images", node, tensorMap, context);
|
|
const size = (0, _utils.getParamValue)("size", node, tensorMap, context);
|
|
const alignCorners = (0, _utils.getParamValue)("alignCorners", node, tensorMap, context);
|
|
const halfPixelCenters = (0, _utils.getParamValue)("halfPixelCenters", node, tensorMap, context);
|
|
return [
|
|
ops.image.resizeNearestNeighbor(images, [
|
|
size[0],
|
|
size[1]
|
|
], alignCorners, halfPixelCenters)
|
|
];
|
|
}
|
|
case "CropAndResize":
|
|
{
|
|
const image = (0, _utils.getParamValue)("image", node, tensorMap, context);
|
|
const boxes = (0, _utils.getParamValue)("boxes", node, tensorMap, context);
|
|
const boxInd = (0, _utils.getParamValue)("boxInd", node, tensorMap, context);
|
|
const cropSize = (0, _utils.getParamValue)("cropSize", node, tensorMap, context);
|
|
const method = (0, _utils.getParamValue)("method", node, tensorMap, context);
|
|
const extrapolationValue = (0, _utils.getParamValue)("extrapolationValue", node, tensorMap, context);
|
|
return [
|
|
ops.image.cropAndResize(image, boxes, boxInd, cropSize, method, extrapolationValue)
|
|
];
|
|
}
|
|
case "ImageProjectiveTransformV3":
|
|
{
|
|
const images = (0, _utils.getParamValue)("images", node, tensorMap, context);
|
|
const transforms = (0, _utils.getParamValue)("transforms", node, tensorMap, context);
|
|
const outputShape = (0, _utils.getParamValue)("outputShape", node, tensorMap, context);
|
|
const fillValue = (0, _utils.getParamValue)("fillValue", node, tensorMap, context);
|
|
const interpolation = (0, _utils.getParamValue)("interpolation", node, tensorMap, context);
|
|
const fillMode = (0, _utils.getParamValue)("fillMode", node, tensorMap, context);
|
|
return [
|
|
ops.image.transform(images, transforms, interpolation.toLowerCase(), fillMode.toLowerCase(), fillValue, outputShape)
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "image";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"30ObX":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "Equal":
|
|
return [
|
|
ops.equal((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "NotEqual":
|
|
return [
|
|
ops.notEqual((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "Greater":
|
|
return [
|
|
ops.greater((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "GreaterEqual":
|
|
return [
|
|
ops.greaterEqual((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "Less":
|
|
return [
|
|
ops.less((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "LessEqual":
|
|
return [
|
|
ops.lessEqual((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "LogicalAnd":
|
|
return [
|
|
ops.logicalAnd((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "LogicalNot":
|
|
return [
|
|
ops.logicalNot((0, _utils.getParamValue)("a", node, tensorMap, context))
|
|
];
|
|
case "LogicalOr":
|
|
return [
|
|
ops.logicalOr((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "Select":
|
|
case "SelectV2":
|
|
return [
|
|
ops.where((0, _utils.getParamValue)("condition", node, tensorMap, context), (0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
case "BitwiseAnd":
|
|
return [
|
|
ops.bitwiseAnd((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "logical";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hCdlL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "BatchMatMul":
|
|
case "BatchMatMulV2":
|
|
case "MatMul":
|
|
return [
|
|
ops.matMul((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("b", node, tensorMap, context), (0, _utils.getParamValue)("transposeA", node, tensorMap, context), (0, _utils.getParamValue)("transposeB", node, tensorMap, context))
|
|
];
|
|
case "Einsum":
|
|
return [
|
|
ops.einsum((0, _utils.getParamValue)("equation", node, tensorMap, context), ...(0, _utils.getParamValue)("tensors", node, tensorMap, context))
|
|
];
|
|
case "Transpose":
|
|
return [
|
|
ops.transpose((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("perm", node, tensorMap, context))
|
|
];
|
|
case "_FusedMatMul":
|
|
const [extraOp, activationFunc] = (0, _utils.getParamValue)("fusedOps", node, tensorMap, context);
|
|
const isBiasAdd = extraOp === "biasadd";
|
|
const isPrelu = activationFunc === "prelu";
|
|
const numArgs = (0, _utils.getParamValue)("numArgs", node, tensorMap, context);
|
|
const leakyreluAlpha = (0, _utils.getParamValue)("leakyreluAlpha", 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] = (0, _utils.getParamValue)("args", node, tensorMap, context);
|
|
return [
|
|
ops.fused.matMul({
|
|
a: (0, _utils.getParamValue)("a", node, tensorMap, context),
|
|
b: (0, _utils.getParamValue)("b", node, tensorMap, context),
|
|
transposeA: (0, _utils.getParamValue)("transposeA", node, tensorMap, context),
|
|
transposeB: (0, _utils.getParamValue)("transposeB", node, tensorMap, context),
|
|
bias: biasArg,
|
|
activation: activationFunc,
|
|
preluActivationWeights: preluArg,
|
|
leakyreluAlpha
|
|
})
|
|
];
|
|
case "MatrixBandPart":
|
|
return [
|
|
ops.linalg.bandPart((0, _utils.getParamValue)("a", node, tensorMap, context), (0, _utils.getParamValue)("numLower", node, tensorMap, context), (0, _utils.getParamValue)("numUpper", node, tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "matrices";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iGve1":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "EuclideanNorm":
|
|
return [
|
|
ops.euclideanNorm((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("axis", node, tensorMap, context), (0, _utils.getParamValue)("keepDims", node, tensorMap, context))
|
|
];
|
|
case "FusedBatchNorm":
|
|
case "FusedBatchNormV2":
|
|
return [
|
|
ops.batchNorm((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("mean", node, tensorMap, context), (0, _utils.getParamValue)("variance", node, tensorMap, context), (0, _utils.getParamValue)("offset", node, tensorMap, context), (0, _utils.getParamValue)("scale", node, tensorMap, context), (0, _utils.getParamValue)("epsilon", node, tensorMap, context))
|
|
];
|
|
case "FusedBatchNormV3":
|
|
return [
|
|
ops.batchNorm((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("mean", node, tensorMap, context), (0, _utils.getParamValue)("variance", node, tensorMap, context), (0, _utils.getParamValue)("offset", node, tensorMap, context), (0, _utils.getParamValue)("scale", node, tensorMap, context), (0, _utils.getParamValue)("epsilon", node, tensorMap, context))
|
|
];
|
|
case "LRN":
|
|
return [
|
|
ops.localResponseNormalization((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("radius", node, tensorMap, context), (0, _utils.getParamValue)("bias", node, tensorMap, context), (0, _utils.getParamValue)("alpha", node, tensorMap, context), (0, _utils.getParamValue)("beta", node, tensorMap, context))
|
|
];
|
|
case "Softmax":
|
|
return [
|
|
ops.softmax((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "LogSoftmax":
|
|
return [
|
|
ops.logSoftmax((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "normalization";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aEvoT":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "RaggedGather":
|
|
{
|
|
const { outputNestedSplits, outputDenseValues } = ops.raggedGather((0, _utils.getParamValue)("paramsNestedSplits", node, tensorMap, context), (0, _utils.getParamValue)("paramsDenseValues", node, tensorMap, context), (0, _utils.getParamValue)("indices", node, tensorMap, context), (0, _utils.getParamValue)("outputRaggedRank", node, tensorMap, context));
|
|
return outputNestedSplits.concat(outputDenseValues);
|
|
}
|
|
case "RaggedRange":
|
|
{
|
|
const { rtNestedSplits, rtDenseValues } = ops.raggedRange((0, _utils.getParamValue)("starts", node, tensorMap, context), (0, _utils.getParamValue)("limits", node, tensorMap, context), (0, _utils.getParamValue)("splits", node, tensorMap, context));
|
|
return [
|
|
rtNestedSplits,
|
|
rtDenseValues
|
|
];
|
|
}
|
|
case "RaggedTensorToTensor":
|
|
return [
|
|
ops.raggedTensorToTensor((0, _utils.getParamValue)("shape", node, tensorMap, context), (0, _utils.getParamValue)("values", node, tensorMap, context), (0, _utils.getParamValue)("defaultValue", node, tensorMap, context), (0, _utils.getParamValue)("rowPartitionTensors", node, tensorMap, context), (0, _utils.getParamValue)("rowPartitionTypes", node, tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "ragged";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bj9OH":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "Max":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const keepDims = (0, _utils.getParamValue)("keepDims", node, tensorMap, context);
|
|
return [
|
|
ops.max((0, _utils.getParamValue)("x", node, tensorMap, context), axis, keepDims)
|
|
];
|
|
}
|
|
case "Mean":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const keepDims = (0, _utils.getParamValue)("keepDims", node, tensorMap, context);
|
|
return [
|
|
ops.mean((0, _utils.getParamValue)("x", node, tensorMap, context), axis, keepDims)
|
|
];
|
|
}
|
|
case "Min":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const keepDims = (0, _utils.getParamValue)("keepDims", node, tensorMap, context);
|
|
return [
|
|
ops.min((0, _utils.getParamValue)("x", node, tensorMap, context), axis, keepDims)
|
|
];
|
|
}
|
|
case "Sum":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const keepDims = (0, _utils.getParamValue)("keepDims", node, tensorMap, context);
|
|
return [
|
|
ops.sum((0, _utils.getParamValue)("x", node, tensorMap, context), axis, keepDims)
|
|
];
|
|
}
|
|
case "All":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const keepDims = (0, _utils.getParamValue)("keepDims", node, tensorMap, context);
|
|
return [
|
|
ops.all((0, _utils.getParamValue)("x", node, tensorMap, context), axis, keepDims)
|
|
];
|
|
}
|
|
case "Any":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const keepDims = (0, _utils.getParamValue)("keepDims", node, tensorMap, context);
|
|
return [
|
|
ops.any((0, _utils.getParamValue)("x", node, tensorMap, context), axis, keepDims)
|
|
];
|
|
}
|
|
case "ArgMax":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
return [
|
|
ops.argMax((0, _utils.getParamValue)("x", node, tensorMap, context), axis)
|
|
];
|
|
}
|
|
case "ArgMin":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
return [
|
|
ops.argMin((0, _utils.getParamValue)("x", node, tensorMap, context), axis)
|
|
];
|
|
}
|
|
case "Prod":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const keepDims = (0, _utils.getParamValue)("keepDims", node, tensorMap, context);
|
|
return [
|
|
ops.prod((0, _utils.getParamValue)("x", node, tensorMap, context), axis, keepDims)
|
|
];
|
|
}
|
|
case "Cumprod":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const exclusive = (0, _utils.getParamValue)("exclusive", node, tensorMap, context);
|
|
const reverse = (0, _utils.getParamValue)("reverse", node, tensorMap, context);
|
|
return [
|
|
ops.cumprod((0, _utils.getParamValue)("x", node, tensorMap, context), axis, exclusive, reverse)
|
|
];
|
|
}
|
|
case "Cumsum":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const exclusive = (0, _utils.getParamValue)("exclusive", node, tensorMap, context);
|
|
const reverse = (0, _utils.getParamValue)("reverse", node, tensorMap, context);
|
|
return [
|
|
ops.cumsum((0, _utils.getParamValue)("x", node, tensorMap, context), axis, exclusive, reverse)
|
|
];
|
|
}
|
|
case "Bincount":
|
|
const x = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const weights = (0, _utils.getParamValue)("weights", node, tensorMap, context);
|
|
const size = (0, _utils.getParamValue)("size", node, tensorMap, context);
|
|
return [
|
|
ops.bincount(x, weights, size)
|
|
];
|
|
case "DenseBincount":
|
|
{
|
|
const x = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const weights = (0, _utils.getParamValue)("weights", node, tensorMap, context);
|
|
const size = (0, _utils.getParamValue)("size", node, tensorMap, context);
|
|
const binaryOutput = (0, _utils.getParamValue)("binaryOutput", node, tensorMap, context);
|
|
return [
|
|
ops.denseBincount(x, weights, size, binaryOutput)
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "reduction";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3HYHo":[function(require,module,exports) {
|
|
/**
|
|
* @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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
// tslint:disable-next-line: no-imports-from-dist
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "ConcatV2":
|
|
case "Concat":
|
|
{
|
|
const n = (0, _utils.getParamValue)("n", node, tensorMap, context);
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
let inputs = (0, _utils.getParamValue)("tensors", node, tensorMap, context);
|
|
inputs = inputs.slice(0, n);
|
|
return [
|
|
ops.concat(inputs, axis)
|
|
];
|
|
}
|
|
case "Gather":
|
|
{
|
|
const input = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const indices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
return [
|
|
ops.gather(input, ops.cast(indices, "int32"), 0)
|
|
];
|
|
}
|
|
case "GatherV2":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const batchDims = (0, _utils.getParamValue)("batchDims", node, tensorMap, context);
|
|
const input = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const indices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
return [
|
|
ops.gather(input, ops.cast(indices, "int32"), axis, batchDims)
|
|
];
|
|
}
|
|
case "Reverse":
|
|
{
|
|
const dims = (0, _utils.getParamValue)("dims", node, tensorMap, context);
|
|
const axis = [];
|
|
for(let i = 0; i < dims.length; i++)if (dims[i]) axis.push(i);
|
|
const input = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
return [
|
|
ops.reverse(input, axis)
|
|
];
|
|
}
|
|
case "ReverseV2":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const input = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
return [
|
|
ops.reverse(input, axis)
|
|
];
|
|
}
|
|
case "Slice":
|
|
{
|
|
// tslint:disable-next-line:no-any
|
|
const begin = (0, _utils.getParamValue)("begin", node, tensorMap, context);
|
|
// tslint:disable-next-line:no-any
|
|
const size = (0, _utils.getParamValue)("size", node, tensorMap, context);
|
|
return [
|
|
ops.slice((0, _utils.getParamValue)("x", node, tensorMap, context), begin, size)
|
|
];
|
|
}
|
|
case "StridedSlice":
|
|
{
|
|
const begin = (0, _utils.getParamValue)("begin", node, tensorMap, context);
|
|
const end = (0, _utils.getParamValue)("end", node, tensorMap, context);
|
|
const strides = (0, _utils.getParamValue)("strides", node, tensorMap, context);
|
|
const beginMask = (0, _utils.getParamValue)("beginMask", node, tensorMap, context);
|
|
const endMask = (0, _utils.getParamValue)("endMask", node, tensorMap, context);
|
|
const ellipsisMask = (0, _utils.getParamValue)("ellipsisMask", node, tensorMap, context);
|
|
const newAxisMask = (0, _utils.getParamValue)("newAxisMask", node, tensorMap, context);
|
|
const shrinkAxisMask = (0, _utils.getParamValue)("shrinkAxisMask", node, tensorMap, context);
|
|
const tensor = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
return [
|
|
ops.stridedSlice(tensor, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask)
|
|
];
|
|
}
|
|
case "Pack":
|
|
return (0, _tfjsCore.tidy)(()=>{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const tensors = (0, _utils.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 = ops.squeeze(tensors[0]).shape;
|
|
const mapped = tensors.map((tensor)=>{
|
|
const sameShape = (0, _tfjsCore.util).arraysEqual(tensor.shape, shape);
|
|
if (!sameShape && !(0, _tfjsCore.util).arraysEqual(ops.squeeze(tensor).shape, squeezedShape)) throw new Error("the input tensors shape does not match");
|
|
return sameShape ? tensor : ops.reshape(tensor, shape);
|
|
});
|
|
return [
|
|
ops.stack(mapped, axis)
|
|
];
|
|
});
|
|
case "Unpack":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const tensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
return ops.unstack(tensor, axis);
|
|
}
|
|
case "Tile":
|
|
{
|
|
const reps = (0, _utils.getParamValue)("reps", node, tensorMap, context);
|
|
return [
|
|
ops.tile((0, _utils.getParamValue)("x", node, tensorMap, context), reps)
|
|
];
|
|
}
|
|
case "Split":
|
|
case "SplitV":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
const numOrSizeSplits = (0, _utils.getParamValue)("numOrSizeSplits", node, tensorMap, context);
|
|
const tensor = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
return ops.split(tensor, numOrSizeSplits, axis);
|
|
}
|
|
case "ScatterNd":
|
|
{
|
|
const indices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
const values = (0, _utils.getParamValue)("values", node, tensorMap, context);
|
|
const shape = (0, _utils.getParamValue)("shape", node, tensorMap, context);
|
|
return [
|
|
ops.scatterND(indices, values, shape)
|
|
];
|
|
}
|
|
case "GatherNd":
|
|
{
|
|
const x = (0, _utils.getParamValue)("x", node, tensorMap, context);
|
|
const indices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
return [
|
|
ops.gatherND(x, indices)
|
|
];
|
|
}
|
|
case "SparseToDense":
|
|
{
|
|
const indices = (0, _utils.getParamValue)("sparseIndices", node, tensorMap, context);
|
|
const shape = (0, _utils.getParamValue)("outputShape", node, tensorMap, context);
|
|
const sparseValues = (0, _utils.getParamValue)("sparseValues", node, tensorMap, context);
|
|
const defaultValue = (0, _utils.getParamValue)("defaultValue", node, tensorMap, context);
|
|
return [
|
|
ops.sparseToDense(indices, sparseValues, shape, sparseValues.dtype === defaultValue.dtype ? defaultValue : ops.cast(defaultValue, sparseValues.dtype))
|
|
];
|
|
}
|
|
case "TensorScatterUpdate":
|
|
{
|
|
const indices = (0, _utils.getParamValue)("indices", node, tensorMap, context);
|
|
const values = (0, _utils.getParamValue)("values", node, tensorMap, context);
|
|
const tensor = (0, _utils.getParamValue)("tensor", node, tensorMap, context);
|
|
return [
|
|
ops.tensorScatterUpdate(tensor, indices, values)
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "slice_join";
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cwC1Y":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "SparseFillEmptyRows":
|
|
{
|
|
const { outputIndices, outputValues, emptyRowIndicator, reverseIndexMap } = ops.sparse.sparseFillEmptyRows((0, _utils.getParamValue)("indices", node, tensorMap, context), (0, _utils.getParamValue)("values", node, tensorMap, context), (0, _utils.getParamValue)("denseShape", node, tensorMap, context), (0, _utils.getParamValue)("defaultValue", node, tensorMap, context));
|
|
return [
|
|
outputIndices,
|
|
outputValues,
|
|
emptyRowIndicator,
|
|
reverseIndexMap
|
|
];
|
|
}
|
|
case "SparseReshape":
|
|
{
|
|
const { outputIndices, outputShape } = ops.sparse.sparseReshape((0, _utils.getParamValue)("inputIndices", node, tensorMap, context), (0, _utils.getParamValue)("inputShape", node, tensorMap, context), (0, _utils.getParamValue)("newShape", node, tensorMap, context));
|
|
return [
|
|
outputIndices,
|
|
outputShape
|
|
];
|
|
}
|
|
case "SparseSegmentMean":
|
|
{
|
|
const outputData = ops.sparse.sparseSegmentMean((0, _utils.getParamValue)("data", node, tensorMap, context), (0, _utils.getParamValue)("indices", node, tensorMap, context), (0, _utils.getParamValue)("segmentIds", node, tensorMap, context));
|
|
return [
|
|
outputData
|
|
];
|
|
}
|
|
case "SparseSegmentSum":
|
|
{
|
|
const outputData = ops.sparse.sparseSegmentSum((0, _utils.getParamValue)("data", node, tensorMap, context), (0, _utils.getParamValue)("indices", node, tensorMap, context), (0, _utils.getParamValue)("segmentIds", node, tensorMap, context));
|
|
return [
|
|
outputData
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "sparse";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jduek":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "FFT":
|
|
return [
|
|
ops.fft((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "IFFT":
|
|
return [
|
|
ops.ifft((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "RFFT":
|
|
return [
|
|
ops.rfft((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
case "IRFFT":
|
|
return [
|
|
ops.irfft((0, _utils.getParamValue)("x", node, tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "spectral";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4NdVa":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "StaticRegexReplace":
|
|
return [
|
|
ops.string.staticRegexReplace((0, _utils.getParamValue)("input", node, tensorMap, context), (0, _utils.getParamValue)("pattern", node, tensorMap, context), (0, _utils.getParamValue)("rewrite", node, tensorMap, context), (0, _utils.getParamValue)("replaceGlobal", node, tensorMap, context))
|
|
];
|
|
case "StringNGrams":
|
|
{
|
|
const { nGrams, nGramsSplits } = ops.string.stringNGrams((0, _utils.getParamValue)("data", node, tensorMap, context), (0, _utils.getParamValue)("dataSplits", node, tensorMap, context), (0, _utils.getParamValue)("separator", node, tensorMap, context), (0, _utils.getParamValue)("nGramWidths", node, tensorMap, context), (0, _utils.getParamValue)("leftPad", node, tensorMap, context), (0, _utils.getParamValue)("rightPad", node, tensorMap, context), (0, _utils.getParamValue)("padWidth", node, tensorMap, context), (0, _utils.getParamValue)("preserveShortSequences", node, tensorMap, context));
|
|
return [
|
|
nGrams,
|
|
nGramsSplits
|
|
];
|
|
}
|
|
case "StringSplit":
|
|
{
|
|
const { indices, values, shape } = ops.string.stringSplit((0, _utils.getParamValue)("input", node, tensorMap, context), (0, _utils.getParamValue)("delimiter", node, tensorMap, context), (0, _utils.getParamValue)("skipEmpty", node, tensorMap, context));
|
|
return [
|
|
indices,
|
|
values,
|
|
shape
|
|
];
|
|
}
|
|
case "StringToHashBucketFast":
|
|
{
|
|
const output = ops.string.stringToHashBucketFast((0, _utils.getParamValue)("input", node, tensorMap, context), (0, _utils.getParamValue)("numBuckets", node, tensorMap, context));
|
|
return [
|
|
output
|
|
];
|
|
}
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "string";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3LErR":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // tslint:disable-next-line: no-imports-from-dist
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "executeOp", ()=>executeOp);
|
|
parcelHelpers.export(exports, "CATEGORY", ()=>CATEGORY);
|
|
var _opsForConverter = require("@tensorflow/tfjs-core/dist/ops/ops_for_converter");
|
|
var _utils = require("./utils");
|
|
const executeOp = (node, tensorMap, context, ops = _opsForConverter)=>{
|
|
switch(node.op){
|
|
case "Cast":
|
|
return [
|
|
ops.cast((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("dtype", node, tensorMap, context))
|
|
];
|
|
case "ExpandDims":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
return [
|
|
ops.expandDims((0, _utils.getParamValue)("x", node, tensorMap, context), axis)
|
|
];
|
|
}
|
|
case "Squeeze":
|
|
{
|
|
const axis = (0, _utils.getParamValue)("axis", node, tensorMap, context);
|
|
return [
|
|
ops.squeeze((0, _utils.getParamValue)("x", node, tensorMap, context), axis)
|
|
];
|
|
}
|
|
case "Reshape":
|
|
return [
|
|
ops.reshape((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("shape", node, tensorMap, context))
|
|
];
|
|
case "EnsureShape":
|
|
return [
|
|
ops.ensureShape((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("shape", node, tensorMap, context))
|
|
];
|
|
case "MirrorPad":
|
|
return [
|
|
ops.mirrorPad((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("padding", node, tensorMap, context), (0, _utils.getParamValue)("mode", node, tensorMap, context))
|
|
];
|
|
case "PadV2":
|
|
case "Pad":
|
|
return [
|
|
ops.pad((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("padding", node, tensorMap, context), (0, _utils.getParamValue)("constantValue", node, tensorMap, context))
|
|
];
|
|
case "SpaceToBatchND":
|
|
{
|
|
const blockShape = (0, _utils.getParamValue)("blockShape", node, tensorMap, context);
|
|
const paddings = (0, _utils.getParamValue)("paddings", node, tensorMap, context);
|
|
return [
|
|
ops.spaceToBatchND((0, _utils.getParamValue)("x", node, tensorMap, context), blockShape, paddings)
|
|
];
|
|
}
|
|
case "BatchToSpaceND":
|
|
{
|
|
const blockShape = (0, _utils.getParamValue)("blockShape", node, tensorMap, context);
|
|
const crops = (0, _utils.getParamValue)("crops", node, tensorMap, context);
|
|
return [
|
|
ops.batchToSpaceND((0, _utils.getParamValue)("x", node, tensorMap, context), blockShape, crops)
|
|
];
|
|
}
|
|
case "DepthToSpace":
|
|
{
|
|
const blockSize = (0, _utils.getParamValue)("blockSize", node, tensorMap, context);
|
|
const dataFormat = (0, _utils.getParamValue)("dataFormat", node, tensorMap, context).toUpperCase();
|
|
return [
|
|
ops.depthToSpace((0, _utils.getParamValue)("x", node, tensorMap, context), blockSize, dataFormat)
|
|
];
|
|
}
|
|
case "BroadcastTo":
|
|
return [
|
|
ops.broadcastTo((0, _utils.getParamValue)("x", node, tensorMap, context), (0, _utils.getParamValue)("shape", node, tensorMap, context))
|
|
];
|
|
case "BroadcastArgs":
|
|
return [
|
|
ops.broadcastArgs((0, _utils.getParamValue)("s0", node, tensorMap, context), (0, _utils.getParamValue)("s1", node, tensorMap, context))
|
|
];
|
|
default:
|
|
throw TypeError(`Node type ${node.op} is not implemented`);
|
|
}
|
|
};
|
|
const CATEGORY = "transformation";
|
|
|
|
},{"@tensorflow/tfjs-core/dist/ops/ops_for_converter":"iUHBn","./utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gK8yG":[function(require,module,exports) {
|
|
/**
|
|
* 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.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ExecutionContext", ()=>ExecutionContext);
|
|
class ExecutionContext {
|
|
constructor(weightMap = {}, tensorArrayMap = {}, tensorListMap = {}, functionMap = {}, parseNodeNameCache){
|
|
this.weightMap = weightMap;
|
|
this.tensorArrayMap = tensorArrayMap;
|
|
this.tensorListMap = tensorListMap;
|
|
this.functionMap = functionMap;
|
|
this.parseNodeNameCache = parseNodeNameCache;
|
|
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];
|
|
}
|
|
addTensorList(tensorList) {
|
|
this.tensorListMap[tensorList.id] = tensorList;
|
|
}
|
|
getTensorList(id) {
|
|
return this.tensorListMap[id];
|
|
}
|
|
dispose(keepIds) {
|
|
for(const key in this.tensorArrayMap)this.tensorArrayMap[key].clearAndClose(keepIds);
|
|
for(const key in this.tensorListMap)this.tensorListMap[key].clearAndClose(keepIds);
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kpmwj":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* 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.
|
|
*/ parcelHelpers.export(exports, "getExecutionSubgraph", ()=>getExecutionSubgraph);
|
|
/**
|
|
* Given the execution info, return a list of nodes in topological order that
|
|
* need to be executed to compute the output.
|
|
*/ parcelHelpers.export(exports, "getNodesInTopologicalOrder", ()=>getNodesInTopologicalOrder);
|
|
/**
|
|
* Given the execution info, return a map from node name to the disposable
|
|
* node name list after its execution.
|
|
*
|
|
* @returns A map from node name to disposable nodes after its
|
|
* execution. That is, for a node `x`, `nodeLiveUntilMap[x]` indicates
|
|
* all nodes which their intermediate tensors should be disposed after `x`
|
|
* being executed.
|
|
*/ parcelHelpers.export(exports, "getNodeLiveUntilMap", ()=>getNodeLiveUntilMap);
|
|
parcelHelpers.export(exports, "isControlFlow", ()=>isControlFlow);
|
|
parcelHelpers.export(exports, "isDynamicShape", ()=>isDynamicShape);
|
|
parcelHelpers.export(exports, "isHashTable", ()=>isHashTable);
|
|
var _utils = require("../operations/executors/utils");
|
|
function getExecutionSubgraph(inputs, outputs, weightMap, initNodes) {
|
|
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 = new Set(Object.keys(inputs).map((name)=>(0, _utils.parseNodeName)(name)[0]));
|
|
initNodes = initNodes || [];
|
|
const initNodeNames = new Set(initNodes.map((node)=>(0, _utils.parseNodeName)(node.name)[0]));
|
|
const frontier = [
|
|
...outputs
|
|
];
|
|
while(frontier.length > 0){
|
|
const node = frontier.pop();
|
|
if (isControlFlow(node) || isDynamicShape(node) || isHashTable(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.has(node.name)) continue;
|
|
// This node is a dead end since it doesn't have any inputs.
|
|
if (initNodeNames.has(node.name)) 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
|
|
};
|
|
}
|
|
function getNodesInTopologicalOrder(graph, executionInfo) {
|
|
const { usedNodes, inputs } = executionInfo;
|
|
const inputNodes = Object.keys(inputs).map((name)=>(0, _utils.parseNodeName)(name)[0]).map((name)=>graph.nodes[name]);
|
|
const initNodes = graph.initNodes || [];
|
|
const isUsed = (node)=>usedNodes.has(typeof node === "string" ? node : node.name);
|
|
function unique(nodes) {
|
|
return [
|
|
...new Map(nodes.map((node)=>[
|
|
node.name,
|
|
node
|
|
])).values()
|
|
];
|
|
}
|
|
const predefinedNodes = unique([
|
|
...inputNodes,
|
|
...graph.weights,
|
|
...initNodes
|
|
]).filter(isUsed);
|
|
const allNodes = unique([
|
|
...predefinedNodes,
|
|
...Object.values(graph.nodes)
|
|
]).filter(isUsed);
|
|
const nameToNode = new Map(allNodes.map((node)=>[
|
|
node.name,
|
|
node
|
|
]));
|
|
const inCounts = {};
|
|
for (const node of allNodes){
|
|
inCounts[node.name] = inCounts[node.name] || 0;
|
|
for (const child of node.children){
|
|
// When the child is unused, set in counts to infinity so that it will
|
|
// never be decreased to 0 and added to the execution list.
|
|
if (!isUsed(child)) inCounts[child.name] = Number.POSITIVE_INFINITY;
|
|
inCounts[child.name] = (inCounts[child.name] || 0) + 1;
|
|
}
|
|
}
|
|
// Build execution order for all used nodes regardless whether they are
|
|
// predefined or not.
|
|
const frontier = Object.entries(inCounts).filter(([, inCount])=>inCount === 0).map(([name])=>name);
|
|
const orderedNodeNames = [
|
|
...frontier
|
|
];
|
|
while(frontier.length > 0){
|
|
const nodeName = frontier.pop();
|
|
const node = nameToNode.get(nodeName);
|
|
for (const child of node.children.filter(isUsed))if (--inCounts[child.name] === 0) {
|
|
orderedNodeNames.push(child.name);
|
|
frontier.push(child.name);
|
|
}
|
|
}
|
|
const orderedNodes = orderedNodeNames.map((name)=>nameToNode.get(name));
|
|
const filteredOrderedNodes = filterPredefinedReachableNodes(orderedNodes, predefinedNodes);
|
|
// TODO: Turn validation on/off with tf env flag.
|
|
validateNodesExecutionOrder(filteredOrderedNodes, predefinedNodes);
|
|
return filteredOrderedNodes;
|
|
}
|
|
/**
|
|
* This is a helper function of `getNodesInTopologicalOrder`.
|
|
* Returns ordered nodes reachable by at least one predefined node.
|
|
* This can help us filter out redundant nodes from the returned node list.
|
|
* For example:
|
|
* If we have four nodes with dependencies like this:
|
|
* a --> b --> c --> d
|
|
* when node `c` is predefined (e.g. given as an input tensor), we can
|
|
* skip node `a` and `b` since their outputs will never be used.
|
|
*
|
|
* @param orderedNodes Graph nodes in execution order.
|
|
* @param predefinedNodes Graph inputs, weights, and init nodes. Nodes in this
|
|
* list must have distinct names.
|
|
*/ function filterPredefinedReachableNodes(orderedNodes, predefinedNodes) {
|
|
const nameToNode = new Map(orderedNodes.map((node)=>[
|
|
node.name,
|
|
node
|
|
]));
|
|
// TODO: Filter out more nodes when >=2 nodes are predefined in a path.
|
|
const stack = predefinedNodes.map((node)=>node.name);
|
|
const predefinedReachableNodeNames = new Set(stack);
|
|
// Perform a DFS starting from the set of all predefined nodes
|
|
// to find the set of all nodes reachable from the predefined nodes.
|
|
while(stack.length > 0){
|
|
const nodeName = stack.pop();
|
|
const node = nameToNode.get(nodeName);
|
|
for (const child of node.children){
|
|
if (!nameToNode.has(child.name) || predefinedReachableNodeNames.has(child.name)) continue;
|
|
predefinedReachableNodeNames.add(child.name);
|
|
stack.push(child.name);
|
|
}
|
|
}
|
|
// Filter out unreachable nodes and build the ordered node list.
|
|
const filteredOrderedNodes = orderedNodes.filter((node)=>predefinedReachableNodeNames.has(node.name));
|
|
return filteredOrderedNodes;
|
|
}
|
|
class NodesExecutionOrderError extends Error {
|
|
constructor(message){
|
|
super(`NodesExecutionOrderError: ${message}`);
|
|
}
|
|
}
|
|
/**
|
|
* This is a helper function of `getNodesInTopologicalOrder`.
|
|
* Validates property: given nodes `a` and `b`, Order(a) > Order(b) if `a`
|
|
* is a child of `b`. This function throws an error if validation fails.
|
|
*
|
|
* @param orderedNodes Graph nodes in execution order.
|
|
* @param predefinedNodes Graph inputs, weights, and init nodes. Nodes in this
|
|
* list must have distinct names.
|
|
*/ function validateNodesExecutionOrder(orderedNodes, predefinedNodes) {
|
|
const nodeNameToOrder = new Map(orderedNodes.map((node, order)=>[
|
|
node.name,
|
|
order
|
|
]));
|
|
const predefinedNodeNames = new Set(predefinedNodes.map((node)=>node.name));
|
|
const isPredefined = (node)=>predefinedNodeNames.has(typeof node === "string" ? node : node.name);
|
|
const willBeExecutedNodeNames = new Set(orderedNodes.map((node)=>node.name));
|
|
const willBeExecuted = (node)=>willBeExecutedNodeNames.has(typeof node === "string" ? node : node.name);
|
|
for (const node of orderedNodes){
|
|
for (const child of node.children.filter(willBeExecuted)){
|
|
if (!nodeNameToOrder.has(child.name)) throw new NodesExecutionOrderError(`Child ${child.name} of node ${node.name} is unreachable.`);
|
|
if (nodeNameToOrder.get(node.name) > nodeNameToOrder.get(child.name)) throw new NodesExecutionOrderError(`Node ${node.name} is scheduled to run after its child ${child.name}.`);
|
|
}
|
|
if (!isPredefined(node)) for (const input of node.inputs){
|
|
if (!nodeNameToOrder.has(input.name)) throw new NodesExecutionOrderError(`Input ${input.name} of node ${node.name} is unreachable.`);
|
|
if (nodeNameToOrder.get(input.name) > nodeNameToOrder.get(node.name)) throw new NodesExecutionOrderError(`Node ${node.name} is scheduled to run before its input ${input.name}.`);
|
|
}
|
|
}
|
|
}
|
|
function getNodeLiveUntilMap(orderedNodes) {
|
|
const nodeNameToOrder = new Map(orderedNodes.map((node, order)=>[
|
|
node.name,
|
|
order
|
|
]));
|
|
const INF_LIFE = Number.MAX_SAFE_INTEGER;
|
|
// Make control flow nodes (and consequently their direct parents)
|
|
// live forever since they're tricky to track correctly.
|
|
const selfLifespans = orderedNodes.map((node, nodeOrder)=>isControlFlow(node) ? INF_LIFE : nodeOrder);
|
|
const getSelfLifeSpan = (node)=>{
|
|
const selfLife = selfLifespans[nodeNameToOrder.get(node.name)];
|
|
if (selfLife == null) // If nodeToOrder does not contain the node, it is unused or
|
|
// unreachable in graph.
|
|
return -1;
|
|
return selfLife;
|
|
};
|
|
// `liveUntil[i]` points to the last node in the `orderedNodes` array that
|
|
// may depend on tensors from node `i`. It indicates that all the
|
|
// intermediate tensors from `orderedNodes[i]` should be disposed after
|
|
// `orderedNodes[liveUntil[i]]` is executed.
|
|
// A node lives long enough to pass on its tensors to its children.
|
|
// It lives until at least `max(node's position, children's positions)`.
|
|
const liveUntilOrders = orderedNodes.map((node, nodeOrder)=>{
|
|
return node.children.map(getSelfLifeSpan).reduce((a, b)=>Math.max(a, b), selfLifespans[nodeOrder]);
|
|
});
|
|
// liveUntilMap:
|
|
// - Key: Name of a node `x`
|
|
// - Values: All nodes whose intermediate tensors should be disposed
|
|
// after `x` is executed.
|
|
const liveUntilMap = new Map();
|
|
for(let nodeOrder = 0; nodeOrder < orderedNodes.length; ++nodeOrder){
|
|
const liveUntilOrder = liveUntilOrders[nodeOrder];
|
|
if (liveUntilOrder === INF_LIFE) continue;
|
|
const node = orderedNodes[nodeOrder];
|
|
const liveUntilNode = orderedNodes[liveUntilOrder];
|
|
if (!liveUntilMap.has(liveUntilNode.name)) liveUntilMap.set(liveUntilNode.name, []);
|
|
liveUntilMap.get(liveUntilNode.name).push(node);
|
|
}
|
|
return liveUntilMap;
|
|
}
|
|
const CONTROL_FLOW_OPS = new Set([
|
|
"Switch",
|
|
"Merge",
|
|
"Enter",
|
|
"Exit",
|
|
"NextIteration",
|
|
"StatelessIf",
|
|
"StatelessWhile",
|
|
"if",
|
|
"While"
|
|
]);
|
|
const DYNAMIC_SHAPE_OPS = new Set([
|
|
"NonMaxSuppressionV2",
|
|
"NonMaxSuppressionV3",
|
|
"NonMaxSuppressionV5",
|
|
"Where"
|
|
]);
|
|
const HASH_TABLE_OPS = new Set([
|
|
"HashTable",
|
|
"HashTableV2",
|
|
"LookupTableImport",
|
|
"LookupTableImportV2",
|
|
"LookupTableFind",
|
|
"LookupTableFindV2",
|
|
"LookupTableSize",
|
|
"LookupTableSizeV2"
|
|
]);
|
|
function isControlFlow(node) {
|
|
return CONTROL_FLOW_OPS.has(node.op);
|
|
}
|
|
function isDynamicShape(node) {
|
|
return DYNAMIC_SHAPE_OPS.has(node.op);
|
|
}
|
|
function isHashTable(node) {
|
|
return HASH_TABLE_OPS.has(node.op);
|
|
}
|
|
|
|
},{"../operations/executors/utils":"lA8AN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9Yk8c":[function(require,module,exports) {
|
|
/**
|
|
* Contains global resources of a model.
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ResourceManager", ()=>ResourceManager);
|
|
class ResourceManager {
|
|
constructor(hashTableNameToHandle = {}, hashTableMap = {}){
|
|
this.hashTableNameToHandle = hashTableNameToHandle;
|
|
this.hashTableMap = hashTableMap;
|
|
}
|
|
/**
|
|
* Register a `HashTable` in the resource manager.
|
|
*
|
|
* The `HashTable` can be retrieved by `resourceManager.getHashTableById`,
|
|
* where id is the table handle tensor's id.
|
|
*
|
|
* @param name Op node name that creates the `HashTable`.
|
|
* @param hashTable The `HashTable` to be added to resource manager.
|
|
*/ addHashTable(name, hashTable) {
|
|
this.hashTableNameToHandle[name] = hashTable.handle;
|
|
this.hashTableMap[hashTable.id] = hashTable;
|
|
}
|
|
/**
|
|
* Get the table handle by node name.
|
|
* @param name Op node name that creates the `HashTable`. This name is also
|
|
* used in the inputs list of lookup and import `HashTable` ops.
|
|
*/ getHashTableHandleByName(name) {
|
|
return this.hashTableNameToHandle[name];
|
|
}
|
|
/**
|
|
* Get the actual `HashTable` by its handle tensor's id.
|
|
* @param id The id of the handle tensor.
|
|
*/ getHashTableById(id) {
|
|
return this.hashTableMap[id];
|
|
}
|
|
/**
|
|
* Dispose `ResourceManager`, including its hashTables and tensors in them.
|
|
*/ dispose() {
|
|
for(const key in this.hashTableMap){
|
|
this.hashTableMap[key].clearAndClose();
|
|
delete this.hashTableMap[key];
|
|
}
|
|
for(const name in this.hashTableNameToHandle){
|
|
this.hashTableNameToHandle[name].dispose();
|
|
delete this.hashTableNameToHandle[name];
|
|
}
|
|
}
|
|
}
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"by8XT":[function(require,module,exports) {
|
|
/** @license See the LICENSE file. */ // This code is auto-generated, do not modify this file!
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "version", ()=>version);
|
|
const version = "4.21.0";
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"j6iw2":[function(require,module,exports) {
|
|
var global = arguments[3];
|
|
(function() {
|
|
"use strict";
|
|
var x;
|
|
function aa(a) {
|
|
var b = 0;
|
|
return function() {
|
|
return b < a.length ? {
|
|
done: !1,
|
|
value: a[b++]
|
|
} : {
|
|
done: !0
|
|
};
|
|
};
|
|
}
|
|
var ba = "function" == typeof Object.defineProperties ? Object.defineProperty : function(a, b, c) {
|
|
if (a == Array.prototype || a == Object.prototype) return a;
|
|
a[b] = c.value;
|
|
return a;
|
|
};
|
|
function ca(a) {
|
|
a = [
|
|
"object" == typeof globalThis && globalThis,
|
|
a,
|
|
"object" == typeof window && window,
|
|
"object" == typeof self && self,
|
|
"object" == typeof global && global
|
|
];
|
|
for(var b = 0; b < a.length; ++b){
|
|
var c = a[b];
|
|
if (c && c.Math == Math) return c;
|
|
}
|
|
throw Error("Cannot find global object");
|
|
}
|
|
var y = ca(this);
|
|
function z(a, b) {
|
|
if (b) a: {
|
|
var c = y;
|
|
a = a.split(".");
|
|
for(var d = 0; d < a.length - 1; d++){
|
|
var e = a[d];
|
|
if (!(e in c)) break a;
|
|
c = c[e];
|
|
}
|
|
a = a[a.length - 1];
|
|
d = c[a];
|
|
b = b(d);
|
|
b != d && null != b && ba(c, a, {
|
|
configurable: !0,
|
|
writable: !0,
|
|
value: b
|
|
});
|
|
}
|
|
}
|
|
z("Symbol", function(a) {
|
|
function b(g) {
|
|
if (this instanceof b) throw new TypeError("Symbol is not a constructor");
|
|
return new c(d + (g || "") + "_" + e++, g);
|
|
}
|
|
function c(g, f) {
|
|
this.h = g;
|
|
ba(this, "description", {
|
|
configurable: !0,
|
|
writable: !0,
|
|
value: f
|
|
});
|
|
}
|
|
if (a) return a;
|
|
c.prototype.toString = function() {
|
|
return this.h;
|
|
};
|
|
var d = "jscomp_symbol_" + (1E9 * Math.random() >>> 0) + "_", e = 0;
|
|
return b;
|
|
});
|
|
z("Symbol.iterator", function(a) {
|
|
if (a) return a;
|
|
a = Symbol("Symbol.iterator");
|
|
for(var b = "Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "), c = 0; c < b.length; c++){
|
|
var d = y[b[c]];
|
|
"function" === typeof d && "function" != typeof d.prototype[a] && ba(d.prototype, a, {
|
|
configurable: !0,
|
|
writable: !0,
|
|
value: function() {
|
|
return da(aa(this));
|
|
}
|
|
});
|
|
}
|
|
return a;
|
|
});
|
|
function da(a) {
|
|
a = {
|
|
next: a
|
|
};
|
|
a[Symbol.iterator] = function() {
|
|
return this;
|
|
};
|
|
return a;
|
|
}
|
|
function A(a) {
|
|
var b = "undefined" != typeof Symbol && Symbol.iterator && a[Symbol.iterator];
|
|
return b ? b.call(a) : {
|
|
next: aa(a)
|
|
};
|
|
}
|
|
function ea(a) {
|
|
if (!(a instanceof Array)) {
|
|
a = A(a);
|
|
for(var b, c = []; !(b = a.next()).done;)c.push(b.value);
|
|
a = c;
|
|
}
|
|
return a;
|
|
}
|
|
var fa = "function" == typeof Object.assign ? Object.assign : function(a, b) {
|
|
for(var c = 1; c < arguments.length; c++){
|
|
var d = arguments[c];
|
|
if (d) for(var e in d)Object.prototype.hasOwnProperty.call(d, e) && (a[e] = d[e]);
|
|
}
|
|
return a;
|
|
};
|
|
z("Object.assign", function(a) {
|
|
return a || fa;
|
|
});
|
|
var ha = "function" == typeof Object.create ? Object.create : function(a) {
|
|
function b() {}
|
|
b.prototype = a;
|
|
return new b;
|
|
}, ia;
|
|
if ("function" == typeof Object.setPrototypeOf) ia = Object.setPrototypeOf;
|
|
else {
|
|
var ja;
|
|
a: {
|
|
var ka = {
|
|
a: !0
|
|
}, la = {};
|
|
try {
|
|
la.__proto__ = ka;
|
|
ja = la.a;
|
|
break a;
|
|
} catch (a) {}
|
|
ja = !1;
|
|
}
|
|
ia = ja ? function(a, b) {
|
|
a.__proto__ = b;
|
|
if (a.__proto__ !== b) throw new TypeError(a + " is not extensible");
|
|
return a;
|
|
} : null;
|
|
}
|
|
var ma = ia;
|
|
function na(a, b) {
|
|
a.prototype = ha(b.prototype);
|
|
a.prototype.constructor = a;
|
|
if (ma) ma(a, b);
|
|
else for(var c in b)if ("prototype" != c) {
|
|
if (Object.defineProperties) {
|
|
var d = Object.getOwnPropertyDescriptor(b, c);
|
|
d && Object.defineProperty(a, c, d);
|
|
} else a[c] = b[c];
|
|
}
|
|
a.za = b.prototype;
|
|
}
|
|
function oa() {
|
|
this.m = !1;
|
|
this.j = null;
|
|
this.i = void 0;
|
|
this.h = 1;
|
|
this.v = this.s = 0;
|
|
this.l = null;
|
|
}
|
|
function pa(a) {
|
|
if (a.m) throw new TypeError("Generator is already running");
|
|
a.m = !0;
|
|
}
|
|
oa.prototype.u = function(a) {
|
|
this.i = a;
|
|
};
|
|
function qa(a, b) {
|
|
a.l = {
|
|
ma: b,
|
|
na: !0
|
|
};
|
|
a.h = a.s || a.v;
|
|
}
|
|
oa.prototype.return = function(a) {
|
|
this.l = {
|
|
return: a
|
|
};
|
|
this.h = this.v;
|
|
};
|
|
function D(a, b, c) {
|
|
a.h = c;
|
|
return {
|
|
value: b
|
|
};
|
|
}
|
|
function ra(a) {
|
|
this.h = new oa;
|
|
this.i = a;
|
|
}
|
|
function sa(a, b) {
|
|
pa(a.h);
|
|
var c = a.h.j;
|
|
if (c) return ta(a, "return" in c ? c["return"] : function(d) {
|
|
return {
|
|
value: d,
|
|
done: !0
|
|
};
|
|
}, b, a.h.return);
|
|
a.h.return(b);
|
|
return ua(a);
|
|
}
|
|
function ta(a, b, c, d) {
|
|
try {
|
|
var e = b.call(a.h.j, c);
|
|
if (!(e instanceof Object)) throw new TypeError("Iterator result " + e + " is not an object");
|
|
if (!e.done) return a.h.m = !1, e;
|
|
var g = e.value;
|
|
} catch (f) {
|
|
return a.h.j = null, qa(a.h, f), ua(a);
|
|
}
|
|
a.h.j = null;
|
|
d.call(a.h, g);
|
|
return ua(a);
|
|
}
|
|
function ua(a) {
|
|
for(; a.h.h;)try {
|
|
var b = a.i(a.h);
|
|
if (b) return a.h.m = !1, {
|
|
value: b.value,
|
|
done: !1
|
|
};
|
|
} catch (c) {
|
|
a.h.i = void 0, qa(a.h, c);
|
|
}
|
|
a.h.m = !1;
|
|
if (a.h.l) {
|
|
b = a.h.l;
|
|
a.h.l = null;
|
|
if (b.na) throw b.ma;
|
|
return {
|
|
value: b.return,
|
|
done: !0
|
|
};
|
|
}
|
|
return {
|
|
value: void 0,
|
|
done: !0
|
|
};
|
|
}
|
|
function va(a) {
|
|
this.next = function(b) {
|
|
pa(a.h);
|
|
a.h.j ? b = ta(a, a.h.j.next, b, a.h.u) : (a.h.u(b), b = ua(a));
|
|
return b;
|
|
};
|
|
this.throw = function(b) {
|
|
pa(a.h);
|
|
a.h.j ? b = ta(a, a.h.j["throw"], b, a.h.u) : (qa(a.h, b), b = ua(a));
|
|
return b;
|
|
};
|
|
this.return = function(b) {
|
|
return sa(a, b);
|
|
};
|
|
this[Symbol.iterator] = function() {
|
|
return this;
|
|
};
|
|
}
|
|
function wa(a) {
|
|
function b(d) {
|
|
return a.next(d);
|
|
}
|
|
function c(d) {
|
|
return a.throw(d);
|
|
}
|
|
return new Promise(function(d, e) {
|
|
function g(f) {
|
|
f.done ? d(f.value) : Promise.resolve(f.value).then(b, c).then(g, e);
|
|
}
|
|
g(a.next());
|
|
});
|
|
}
|
|
function E(a) {
|
|
return wa(new va(new ra(a)));
|
|
}
|
|
z("Promise", function(a) {
|
|
function b(f) {
|
|
this.i = 0;
|
|
this.j = void 0;
|
|
this.h = [];
|
|
this.u = !1;
|
|
var h = this.l();
|
|
try {
|
|
f(h.resolve, h.reject);
|
|
} catch (k) {
|
|
h.reject(k);
|
|
}
|
|
}
|
|
function c() {
|
|
this.h = null;
|
|
}
|
|
function d(f) {
|
|
return f instanceof b ? f : new b(function(h) {
|
|
h(f);
|
|
});
|
|
}
|
|
if (a) return a;
|
|
c.prototype.i = function(f) {
|
|
if (null == this.h) {
|
|
this.h = [];
|
|
var h = this;
|
|
this.j(function() {
|
|
h.m();
|
|
});
|
|
}
|
|
this.h.push(f);
|
|
};
|
|
var e = y.setTimeout;
|
|
c.prototype.j = function(f) {
|
|
e(f, 0);
|
|
};
|
|
c.prototype.m = function() {
|
|
for(; this.h && this.h.length;){
|
|
var f = this.h;
|
|
this.h = [];
|
|
for(var h = 0; h < f.length; ++h){
|
|
var k = f[h];
|
|
f[h] = null;
|
|
try {
|
|
k();
|
|
} catch (l) {
|
|
this.l(l);
|
|
}
|
|
}
|
|
}
|
|
this.h = null;
|
|
};
|
|
c.prototype.l = function(f) {
|
|
this.j(function() {
|
|
throw f;
|
|
});
|
|
};
|
|
b.prototype.l = function() {
|
|
function f(l) {
|
|
return function(m) {
|
|
k || (k = !0, l.call(h, m));
|
|
};
|
|
}
|
|
var h = this, k = !1;
|
|
return {
|
|
resolve: f(this.I),
|
|
reject: f(this.m)
|
|
};
|
|
};
|
|
b.prototype.I = function(f) {
|
|
if (f === this) this.m(new TypeError("A Promise cannot resolve to itself"));
|
|
else if (f instanceof b) this.L(f);
|
|
else {
|
|
a: switch(typeof f){
|
|
case "object":
|
|
var h = null != f;
|
|
break a;
|
|
case "function":
|
|
h = !0;
|
|
break a;
|
|
default:
|
|
h = !1;
|
|
}
|
|
h ? this.F(f) : this.s(f);
|
|
}
|
|
};
|
|
b.prototype.F = function(f) {
|
|
var h = void 0;
|
|
try {
|
|
h = f.then;
|
|
} catch (k) {
|
|
this.m(k);
|
|
return;
|
|
}
|
|
"function" == typeof h ? this.M(h, f) : this.s(f);
|
|
};
|
|
b.prototype.m = function(f) {
|
|
this.v(2, f);
|
|
};
|
|
b.prototype.s = function(f) {
|
|
this.v(1, f);
|
|
};
|
|
b.prototype.v = function(f, h) {
|
|
if (0 != this.i) throw Error("Cannot settle(" + f + ", " + h + "): Promise already settled in state" + this.i);
|
|
this.i = f;
|
|
this.j = h;
|
|
2 === this.i && this.K();
|
|
this.H();
|
|
};
|
|
b.prototype.K = function() {
|
|
var f = this;
|
|
e(function() {
|
|
if (f.D()) {
|
|
var h = y.console;
|
|
"undefined" !== typeof h && h.error(f.j);
|
|
}
|
|
}, 1);
|
|
};
|
|
b.prototype.D = function() {
|
|
if (this.u) return !1;
|
|
var f = y.CustomEvent, h = y.Event, k = y.dispatchEvent;
|
|
if ("undefined" === typeof k) return !0;
|
|
"function" === typeof f ? f = new f("unhandledrejection", {
|
|
cancelable: !0
|
|
}) : "function" === typeof h ? f = new h("unhandledrejection", {
|
|
cancelable: !0
|
|
}) : (f = y.document.createEvent("CustomEvent"), f.initCustomEvent("unhandledrejection", !1, !0, f));
|
|
f.promise = this;
|
|
f.reason = this.j;
|
|
return k(f);
|
|
};
|
|
b.prototype.H = function() {
|
|
if (null != this.h) {
|
|
for(var f = 0; f < this.h.length; ++f)g.i(this.h[f]);
|
|
this.h = null;
|
|
}
|
|
};
|
|
var g = new c;
|
|
b.prototype.L = function(f) {
|
|
var h = this.l();
|
|
f.T(h.resolve, h.reject);
|
|
};
|
|
b.prototype.M = function(f, h) {
|
|
var k = this.l();
|
|
try {
|
|
f.call(h, k.resolve, k.reject);
|
|
} catch (l) {
|
|
k.reject(l);
|
|
}
|
|
};
|
|
b.prototype.then = function(f, h) {
|
|
function k(p, n) {
|
|
return "function" == typeof p ? function(q) {
|
|
try {
|
|
l(p(q));
|
|
} catch (t) {
|
|
m(t);
|
|
}
|
|
} : n;
|
|
}
|
|
var l, m, r = new b(function(p, n) {
|
|
l = p;
|
|
m = n;
|
|
});
|
|
this.T(k(f, l), k(h, m));
|
|
return r;
|
|
};
|
|
b.prototype.catch = function(f) {
|
|
return this.then(void 0, f);
|
|
};
|
|
b.prototype.T = function(f, h) {
|
|
function k() {
|
|
switch(l.i){
|
|
case 1:
|
|
f(l.j);
|
|
break;
|
|
case 2:
|
|
h(l.j);
|
|
break;
|
|
default:
|
|
throw Error("Unexpected state: " + l.i);
|
|
}
|
|
}
|
|
var l = this;
|
|
null == this.h ? g.i(k) : this.h.push(k);
|
|
this.u = !0;
|
|
};
|
|
b.resolve = d;
|
|
b.reject = function(f) {
|
|
return new b(function(h, k) {
|
|
k(f);
|
|
});
|
|
};
|
|
b.race = function(f) {
|
|
return new b(function(h, k) {
|
|
for(var l = A(f), m = l.next(); !m.done; m = l.next())d(m.value).T(h, k);
|
|
});
|
|
};
|
|
b.all = function(f) {
|
|
var h = A(f), k = h.next();
|
|
return k.done ? d([]) : new b(function(l, m) {
|
|
function r(q) {
|
|
return function(t) {
|
|
p[q] = t;
|
|
n--;
|
|
0 == n && l(p);
|
|
};
|
|
}
|
|
var p = [], n = 0;
|
|
do p.push(void 0), n++, d(k.value).T(r(p.length - 1), m), k = h.next();
|
|
while (!k.done);
|
|
});
|
|
};
|
|
return b;
|
|
});
|
|
function xa(a, b) {
|
|
a instanceof String && (a += "");
|
|
var c = 0, d = !1, e = {
|
|
next: function() {
|
|
if (!d && c < a.length) {
|
|
var g = c++;
|
|
return {
|
|
value: b(g, a[g]),
|
|
done: !1
|
|
};
|
|
}
|
|
d = !0;
|
|
return {
|
|
done: !0,
|
|
value: void 0
|
|
};
|
|
}
|
|
};
|
|
e[Symbol.iterator] = function() {
|
|
return e;
|
|
};
|
|
return e;
|
|
}
|
|
z("Array.prototype.keys", function(a) {
|
|
return a ? a : function() {
|
|
return xa(this, function(b) {
|
|
return b;
|
|
});
|
|
};
|
|
});
|
|
z("Array.prototype.fill", function(a) {
|
|
return a ? a : function(b, c, d) {
|
|
var e = this.length || 0;
|
|
0 > c && (c = Math.max(0, e + c));
|
|
if (null == d || d > e) d = e;
|
|
d = Number(d);
|
|
0 > d && (d = Math.max(0, e + d));
|
|
for(c = Number(c || 0); c < d; c++)this[c] = b;
|
|
return this;
|
|
};
|
|
});
|
|
function F(a) {
|
|
return a ? a : Array.prototype.fill;
|
|
}
|
|
z("Int8Array.prototype.fill", F);
|
|
z("Uint8Array.prototype.fill", F);
|
|
z("Uint8ClampedArray.prototype.fill", F);
|
|
z("Int16Array.prototype.fill", F);
|
|
z("Uint16Array.prototype.fill", F);
|
|
z("Int32Array.prototype.fill", F);
|
|
z("Uint32Array.prototype.fill", F);
|
|
z("Float32Array.prototype.fill", F);
|
|
z("Float64Array.prototype.fill", F);
|
|
z("Object.is", function(a) {
|
|
return a ? a : function(b, c) {
|
|
return b === c ? 0 !== b || 1 / b === 1 / c : b !== b && c !== c;
|
|
};
|
|
});
|
|
z("Array.prototype.includes", function(a) {
|
|
return a ? a : function(b, c) {
|
|
var d = this;
|
|
d instanceof String && (d = String(d));
|
|
var e = d.length;
|
|
c = c || 0;
|
|
for(0 > c && (c = Math.max(c + e, 0)); c < e; c++){
|
|
var g = d[c];
|
|
if (g === b || Object.is(g, b)) return !0;
|
|
}
|
|
return !1;
|
|
};
|
|
});
|
|
z("String.prototype.includes", function(a) {
|
|
return a ? a : function(b, c) {
|
|
if (null == this) throw new TypeError("The 'this' value for String.prototype.includes must not be null or undefined");
|
|
if (b instanceof RegExp) throw new TypeError("First argument to String.prototype.includes must not be a regular expression");
|
|
return -1 !== this.indexOf(b, c || 0);
|
|
};
|
|
});
|
|
var ya = this || self;
|
|
function Aa(a, b) {
|
|
a = a.split(".");
|
|
var c = ya;
|
|
a[0] in c || "undefined" == typeof c.execScript || c.execScript("var " + a[0]);
|
|
for(var d; a.length && (d = a.shift());)a.length || void 0 === b ? c[d] && c[d] !== Object.prototype[d] ? c = c[d] : c = c[d] = {} : c[d] = b;
|
|
}
|
|
function Ba(a) {
|
|
var b;
|
|
a: {
|
|
if (b = ya.navigator) {
|
|
if (b = b.userAgent) break a;
|
|
}
|
|
b = "";
|
|
}
|
|
return -1 != b.indexOf(a);
|
|
}
|
|
var Ca = Array.prototype.map ? function(a, b) {
|
|
return Array.prototype.map.call(a, b, void 0);
|
|
} : function(a, b) {
|
|
for(var c = a.length, d = Array(c), e = "string" === typeof a ? a.split("") : a, g = 0; g < c; g++)g in e && (d[g] = b.call(void 0, e[g], g, a));
|
|
return d;
|
|
};
|
|
var Da = {}, Ea = null;
|
|
function Fa(a) {
|
|
var b = a.length, c = 3 * b / 4;
|
|
c % 3 ? c = Math.floor(c) : -1 != "=.".indexOf(a[b - 1]) && (c = -1 != "=.".indexOf(a[b - 2]) ? c - 2 : c - 1);
|
|
var d = new Uint8Array(c), e = 0;
|
|
Ga(a, function(g) {
|
|
d[e++] = g;
|
|
});
|
|
return e !== c ? d.subarray(0, e) : d;
|
|
}
|
|
function Ga(a, b) {
|
|
function c(k) {
|
|
for(; d < a.length;){
|
|
var l = a.charAt(d++), m = Ea[l];
|
|
if (null != m) return m;
|
|
if (!/^[\s\xa0]*$/.test(l)) throw Error("Unknown base64 encoding at char: " + l);
|
|
}
|
|
return k;
|
|
}
|
|
Ha();
|
|
for(var d = 0;;){
|
|
var e = c(-1), g = c(0), f = c(64), h = c(64);
|
|
if (64 === h && -1 === e) break;
|
|
b(e << 2 | g >> 4);
|
|
64 != f && (b(g << 4 & 240 | f >> 2), 64 != h && b(f << 6 & 192 | h));
|
|
}
|
|
}
|
|
function Ha() {
|
|
if (!Ea) {
|
|
Ea = {};
|
|
for(var a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""), b = [
|
|
"+/=",
|
|
"+/",
|
|
"-_=",
|
|
"-_.",
|
|
"-_"
|
|
], c = 0; 5 > c; c++){
|
|
var d = a.concat(b[c].split(""));
|
|
Da[c] = d;
|
|
for(var e = 0; e < d.length; e++){
|
|
var g = d[e];
|
|
void 0 === Ea[g] && (Ea[g] = e);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
var Ia = "undefined" !== typeof Uint8Array, Ja = !(Ba("Trident") || Ba("MSIE")) && "function" === typeof ya.btoa;
|
|
function Ka(a) {
|
|
if (!Ja) {
|
|
var b;
|
|
void 0 === b && (b = 0);
|
|
Ha();
|
|
b = Da[b];
|
|
for(var c = Array(Math.floor(a.length / 3)), d = b[64] || "", e = 0, g = 0; e < a.length - 2; e += 3){
|
|
var f = a[e], h = a[e + 1], k = a[e + 2], l = b[f >> 2];
|
|
f = b[(f & 3) << 4 | h >> 4];
|
|
h = b[(h & 15) << 2 | k >> 6];
|
|
k = b[k & 63];
|
|
c[g++] = l + f + h + k;
|
|
}
|
|
l = 0;
|
|
k = d;
|
|
switch(a.length - e){
|
|
case 2:
|
|
l = a[e + 1], k = b[(l & 15) << 2] || d;
|
|
case 1:
|
|
a = a[e], c[g] = b[a >> 2] + b[(a & 3) << 4 | l >> 4] + k + d;
|
|
}
|
|
return c.join("");
|
|
}
|
|
for(b = ""; 10240 < a.length;)b += String.fromCharCode.apply(null, a.subarray(0, 10240)), a = a.subarray(10240);
|
|
b += String.fromCharCode.apply(null, a);
|
|
return btoa(b);
|
|
}
|
|
var La = RegExp("[-_.]", "g");
|
|
function Ma(a) {
|
|
switch(a){
|
|
case "-":
|
|
return "+";
|
|
case "_":
|
|
return "/";
|
|
case ".":
|
|
return "=";
|
|
default:
|
|
return "";
|
|
}
|
|
}
|
|
function Na(a) {
|
|
if (!Ja) return Fa(a);
|
|
La.test(a) && (a = a.replace(La, Ma));
|
|
a = atob(a);
|
|
for(var b = new Uint8Array(a.length), c = 0; c < a.length; c++)b[c] = a.charCodeAt(c);
|
|
return b;
|
|
}
|
|
var Oa;
|
|
function Pa() {
|
|
return Oa || (Oa = new Uint8Array(0));
|
|
}
|
|
var Qa = {};
|
|
var Ra = "function" === typeof Uint8Array.prototype.slice, G = 0, H = 0;
|
|
function Sa(a) {
|
|
var b = 0 > a;
|
|
a = Math.abs(a);
|
|
var c = a >>> 0;
|
|
a = Math.floor((a - c) / 4294967296);
|
|
b && (c = A(Ta(c, a)), b = c.next().value, a = c.next().value, c = b);
|
|
G = c >>> 0;
|
|
H = a >>> 0;
|
|
}
|
|
var Ua = "function" === typeof BigInt;
|
|
function Ta(a, b) {
|
|
b = ~b;
|
|
a ? a = ~a + 1 : b += 1;
|
|
return [
|
|
a,
|
|
b
|
|
];
|
|
}
|
|
function Va(a, b) {
|
|
this.i = a >>> 0;
|
|
this.h = b >>> 0;
|
|
}
|
|
function Wa(a) {
|
|
if (!a) return Xa || (Xa = new Va(0, 0));
|
|
if (!/^-?\d+$/.test(a)) return null;
|
|
if (16 > a.length) Sa(Number(a));
|
|
else if (Ua) a = BigInt(a), G = Number(a & BigInt(4294967295)) >>> 0, H = Number(a >> BigInt(32) & BigInt(4294967295));
|
|
else {
|
|
var b = +("-" === a[0]);
|
|
H = G = 0;
|
|
for(var c = a.length, d = b, e = (c - b) % 6 + b; e <= c; d = e, e += 6)d = Number(a.slice(d, e)), H *= 1E6, G = 1E6 * G + d, 4294967296 <= G && (H += G / 4294967296 | 0, G %= 4294967296);
|
|
b && (b = A(Ta(G, H)), a = b.next().value, b = b.next().value, G = a, H = b);
|
|
}
|
|
return new Va(G, H);
|
|
}
|
|
var Xa;
|
|
function Ya(a, b) {
|
|
return Error("Invalid wire type: " + a + " (at position " + b + ")");
|
|
}
|
|
function Za() {
|
|
return Error("Failed to read varint, encoding is invalid.");
|
|
}
|
|
function $a(a, b) {
|
|
return Error("Tried to read past the end of the data " + b + " > " + a);
|
|
}
|
|
function K() {
|
|
throw Error("Invalid UTF8");
|
|
}
|
|
function ab(a, b) {
|
|
b = String.fromCharCode.apply(null, b);
|
|
return null == a ? b : a + b;
|
|
}
|
|
var bb = void 0, cb, db = "undefined" !== typeof TextDecoder, eb, fb = "undefined" !== typeof TextEncoder;
|
|
var gb;
|
|
function hb(a) {
|
|
if (a !== Qa) throw Error("illegal external caller");
|
|
}
|
|
function ib(a, b) {
|
|
hb(b);
|
|
this.V = a;
|
|
if (null != a && 0 === a.length) throw Error("ByteString should be constructed with non-empty values");
|
|
}
|
|
function jb() {
|
|
return gb || (gb = new ib(null, Qa));
|
|
}
|
|
function kb(a) {
|
|
hb(Qa);
|
|
var b = a.V;
|
|
b = null == b || Ia && null != b && b instanceof Uint8Array ? b : "string" === typeof b ? Na(b) : null;
|
|
return null == b ? b : a.V = b;
|
|
}
|
|
function lb(a) {
|
|
if ("string" === typeof a) return {
|
|
buffer: Na(a),
|
|
C: !1
|
|
};
|
|
if (Array.isArray(a)) return {
|
|
buffer: new Uint8Array(a),
|
|
C: !1
|
|
};
|
|
if (a.constructor === Uint8Array) return {
|
|
buffer: a,
|
|
C: !1
|
|
};
|
|
if (a.constructor === ArrayBuffer) return {
|
|
buffer: new Uint8Array(a),
|
|
C: !1
|
|
};
|
|
if (a.constructor === ib) return {
|
|
buffer: kb(a) || Pa(),
|
|
C: !0
|
|
};
|
|
if (a instanceof Uint8Array) return {
|
|
buffer: new Uint8Array(a.buffer, a.byteOffset, a.byteLength),
|
|
C: !1
|
|
};
|
|
throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers");
|
|
}
|
|
function mb(a, b) {
|
|
this.i = null;
|
|
this.m = !1;
|
|
this.h = this.j = this.l = 0;
|
|
nb(this, a, b);
|
|
}
|
|
function nb(a, b, c) {
|
|
c = void 0 === c ? {} : c;
|
|
a.S = void 0 === c.S ? !1 : c.S;
|
|
b && (b = lb(b), a.i = b.buffer, a.m = b.C, a.l = 0, a.j = a.i.length, a.h = a.l);
|
|
}
|
|
mb.prototype.reset = function() {
|
|
this.h = this.l;
|
|
};
|
|
function L(a, b) {
|
|
a.h = b;
|
|
if (b > a.j) throw $a(a.j, b);
|
|
}
|
|
function ob(a) {
|
|
var b = a.i, c = a.h, d = b[c++], e = d & 127;
|
|
if (d & 128 && (d = b[c++], e |= (d & 127) << 7, d & 128 && (d = b[c++], e |= (d & 127) << 14, d & 128 && (d = b[c++], e |= (d & 127) << 21, d & 128 && (d = b[c++], e |= d << 28, d & 128 && b[c++] & 128 && b[c++] & 128 && b[c++] & 128 && b[c++] & 128 && b[c++] & 128))))) throw Za();
|
|
L(a, c);
|
|
return e;
|
|
}
|
|
function pb(a, b) {
|
|
if (0 > b) throw Error("Tried to read a negative byte length: " + b);
|
|
var c = a.h, d = c + b;
|
|
if (d > a.j) throw $a(b, a.j - c);
|
|
a.h = d;
|
|
return c;
|
|
}
|
|
var qb = [];
|
|
function rb() {
|
|
this.h = [];
|
|
}
|
|
rb.prototype.length = function() {
|
|
return this.h.length;
|
|
};
|
|
rb.prototype.end = function() {
|
|
var a = this.h;
|
|
this.h = [];
|
|
return a;
|
|
};
|
|
function sb(a, b, c) {
|
|
for(; 0 < c || 127 < b;)a.h.push(b & 127 | 128), b = (b >>> 7 | c << 25) >>> 0, c >>>= 7;
|
|
a.h.push(b);
|
|
}
|
|
function M(a, b) {
|
|
for(; 127 < b;)a.h.push(b & 127 | 128), b >>>= 7;
|
|
a.h.push(b);
|
|
}
|
|
function tb(a, b) {
|
|
if (qb.length) {
|
|
var c = qb.pop();
|
|
nb(c, a, b);
|
|
a = c;
|
|
} else a = new mb(a, b);
|
|
this.h = a;
|
|
this.j = this.h.h;
|
|
this.i = this.l = -1;
|
|
this.setOptions(b);
|
|
}
|
|
tb.prototype.setOptions = function(a) {
|
|
a = void 0 === a ? {} : a;
|
|
this.ca = void 0 === a.ca ? !1 : a.ca;
|
|
};
|
|
tb.prototype.reset = function() {
|
|
this.h.reset();
|
|
this.j = this.h.h;
|
|
this.i = this.l = -1;
|
|
};
|
|
function ub(a) {
|
|
var b = a.h;
|
|
if (b.h == b.j) return !1;
|
|
a.j = a.h.h;
|
|
var c = ob(a.h) >>> 0;
|
|
b = c >>> 3;
|
|
c &= 7;
|
|
if (!(0 <= c && 5 >= c)) throw Ya(c, a.j);
|
|
if (1 > b) throw Error("Invalid field number: " + b + " (at position " + a.j + ")");
|
|
a.l = b;
|
|
a.i = c;
|
|
return !0;
|
|
}
|
|
function vb(a) {
|
|
switch(a.i){
|
|
case 0:
|
|
if (0 != a.i) vb(a);
|
|
else a: {
|
|
a = a.h;
|
|
for(var b = a.h, c = b + 10, d = a.i; b < c;)if (0 === (d[b++] & 128)) {
|
|
L(a, b);
|
|
break a;
|
|
}
|
|
throw Za();
|
|
}
|
|
break;
|
|
case 1:
|
|
a = a.h;
|
|
L(a, a.h + 8);
|
|
break;
|
|
case 2:
|
|
2 != a.i ? vb(a) : (b = ob(a.h) >>> 0, a = a.h, L(a, a.h + b));
|
|
break;
|
|
case 5:
|
|
a = a.h;
|
|
L(a, a.h + 4);
|
|
break;
|
|
case 3:
|
|
b = a.l;
|
|
do {
|
|
if (!ub(a)) throw Error("Unmatched start-group tag: stream EOF");
|
|
if (4 == a.i) {
|
|
if (a.l != b) throw Error("Unmatched end-group tag");
|
|
break;
|
|
}
|
|
vb(a);
|
|
}while (1);
|
|
break;
|
|
default:
|
|
throw Ya(a.i, a.j);
|
|
}
|
|
}
|
|
var wb = [];
|
|
function xb() {
|
|
this.j = [];
|
|
this.i = 0;
|
|
this.h = new rb;
|
|
}
|
|
function N(a, b) {
|
|
0 !== b.length && (a.j.push(b), a.i += b.length);
|
|
}
|
|
function yb(a, b) {
|
|
if (b = b.R) {
|
|
N(a, a.h.end());
|
|
for(var c = 0; c < b.length; c++)N(a, kb(b[c]) || Pa());
|
|
}
|
|
}
|
|
var O = "function" === typeof Symbol && "symbol" === typeof Symbol() ? Symbol() : void 0;
|
|
function P(a, b) {
|
|
if (O) return a[O] |= b;
|
|
if (void 0 !== a.A) return a.A |= b;
|
|
Object.defineProperties(a, {
|
|
A: {
|
|
value: b,
|
|
configurable: !0,
|
|
writable: !0,
|
|
enumerable: !1
|
|
}
|
|
});
|
|
return b;
|
|
}
|
|
function zb(a, b) {
|
|
O ? a[O] && (a[O] &= ~b) : void 0 !== a.A && (a.A &= ~b);
|
|
}
|
|
function Q(a) {
|
|
var b;
|
|
O ? b = a[O] : b = a.A;
|
|
return null == b ? 0 : b;
|
|
}
|
|
function R(a, b) {
|
|
O ? a[O] = b : void 0 !== a.A ? a.A = b : Object.defineProperties(a, {
|
|
A: {
|
|
value: b,
|
|
configurable: !0,
|
|
writable: !0,
|
|
enumerable: !1
|
|
}
|
|
});
|
|
}
|
|
function Ab(a) {
|
|
P(a, 1);
|
|
return a;
|
|
}
|
|
function Bb(a, b) {
|
|
R(b, (a | 0) & -51);
|
|
}
|
|
function Cb(a, b) {
|
|
R(b, (a | 18) & -41);
|
|
}
|
|
var Db = {};
|
|
function Eb(a) {
|
|
return null !== a && "object" === typeof a && !Array.isArray(a) && a.constructor === Object;
|
|
}
|
|
var Fb, Gb = [];
|
|
R(Gb, 23);
|
|
Fb = Object.freeze(Gb);
|
|
function Hb(a) {
|
|
if (Q(a.o) & 2) throw Error("Cannot mutate an immutable Message");
|
|
}
|
|
function Ib(a) {
|
|
var b = a.length;
|
|
(b = b ? a[b - 1] : void 0) && Eb(b) ? b.g = 1 : (b = {}, a.push((b.g = 1, b)));
|
|
}
|
|
function Jb(a) {
|
|
var b = a.i + a.G;
|
|
return a.B || (a.B = a.o[b] = {});
|
|
}
|
|
function S(a, b) {
|
|
return -1 === b ? null : b >= a.i ? a.B ? a.B[b] : void 0 : a.o[b + a.G];
|
|
}
|
|
function U(a, b, c, d) {
|
|
Hb(a);
|
|
Kb(a, b, c, d);
|
|
}
|
|
function Kb(a, b, c, d) {
|
|
a.j && (a.j = void 0);
|
|
b >= a.i || d ? Jb(a)[b] = c : (a.o[b + a.G] = c, (a = a.B) && b in a && delete a[b]);
|
|
}
|
|
function Lb(a, b, c, d) {
|
|
var e = S(a, b);
|
|
Array.isArray(e) || (e = Fb);
|
|
var g = Q(e);
|
|
g & 1 || Ab(e);
|
|
if (d) g & 2 || P(e, 2), c & 1 || Object.freeze(e);
|
|
else {
|
|
d = !(c & 2);
|
|
var f = g & 2;
|
|
c & 1 || !f ? d && g & 16 && !f && zb(e, 16) : (e = Ab(Array.prototype.slice.call(e)), Kb(a, b, e));
|
|
}
|
|
return e;
|
|
}
|
|
function Mb(a, b) {
|
|
var c = S(a, b);
|
|
var d = null == c ? c : "number" === typeof c || "NaN" === c || "Infinity" === c || "-Infinity" === c ? Number(c) : void 0;
|
|
null != d && d !== c && Kb(a, b, d);
|
|
return d;
|
|
}
|
|
function Nb(a, b, c, d, e) {
|
|
a.h || (a.h = {});
|
|
var g = a.h[c], f = Lb(a, c, 3, e);
|
|
if (!g) {
|
|
var h = f;
|
|
g = [];
|
|
var k = !!(Q(a.o) & 16);
|
|
f = !!(Q(h) & 2);
|
|
var l = h;
|
|
!e && f && (h = Array.prototype.slice.call(h));
|
|
for(var m = f, r = 0; r < h.length; r++){
|
|
var p = h[r];
|
|
var n = b, q = !1;
|
|
q = void 0 === q ? !1 : q;
|
|
p = Array.isArray(p) ? new n(p) : q ? new n : void 0;
|
|
if (void 0 !== p) {
|
|
n = p.o;
|
|
var t = q = Q(n);
|
|
f && (t |= 2);
|
|
k && (t |= 16);
|
|
t != q && R(n, t);
|
|
n = t;
|
|
m = m || !!(2 & n);
|
|
g.push(p);
|
|
}
|
|
}
|
|
a.h[c] = g;
|
|
k = Q(h);
|
|
b = k | 33;
|
|
b = m ? b & -9 : b | 8;
|
|
k != b && (m = h, Object.isFrozen(m) && (m = Array.prototype.slice.call(m)), R(m, b), h = m);
|
|
l !== h && Kb(a, c, h);
|
|
(e || d && f) && P(g, 2);
|
|
d && Object.freeze(g);
|
|
return g;
|
|
}
|
|
e || (e = Object.isFrozen(g), d && !e ? Object.freeze(g) : !d && e && (g = Array.prototype.slice.call(g), a.h[c] = g));
|
|
return g;
|
|
}
|
|
function Ob(a, b, c) {
|
|
var d = !!(Q(a.o) & 2);
|
|
b = Nb(a, b, c, d, d);
|
|
a = Lb(a, c, 3, d);
|
|
if (!(d || Q(a) & 8)) {
|
|
for(d = 0; d < b.length; d++){
|
|
c = b[d];
|
|
if (Q(c.o) & 2) {
|
|
var e = Pb(c, !1);
|
|
e.j = c;
|
|
} else e = c;
|
|
c !== e && (b[d] = e, a[d] = e.o);
|
|
}
|
|
P(a, 8);
|
|
}
|
|
return b;
|
|
}
|
|
function V(a, b, c) {
|
|
if (null != c && "number" !== typeof c) throw Error("Value of float/double field must be a number|null|undefined, found " + typeof c + ": " + c);
|
|
U(a, b, c);
|
|
}
|
|
function Qb(a, b, c, d, e) {
|
|
Hb(a);
|
|
var g = Nb(a, c, b, !1, !1);
|
|
c = null != d ? d : new c;
|
|
a = Lb(a, b, 2, !1);
|
|
void 0 != e ? (g.splice(e, 0, c), a.splice(e, 0, c.o)) : (g.push(c), a.push(c.o));
|
|
c.C() && zb(a, 8);
|
|
return c;
|
|
}
|
|
function Rb(a, b) {
|
|
return null == a ? b : a;
|
|
}
|
|
function W(a, b, c) {
|
|
c = void 0 === c ? 0 : c;
|
|
return Rb(Mb(a, b), c);
|
|
}
|
|
var Sb;
|
|
function Tb(a) {
|
|
switch(typeof a){
|
|
case "number":
|
|
return isFinite(a) ? a : String(a);
|
|
case "object":
|
|
if (a) {
|
|
if (Array.isArray(a)) {
|
|
if (0 !== (Q(a) & 128)) return a = Array.prototype.slice.call(a), Ib(a), a;
|
|
} else {
|
|
if (Ia && null != a && a instanceof Uint8Array) return Ka(a);
|
|
if (a instanceof ib) {
|
|
var b = a.V;
|
|
return null == b ? "" : "string" === typeof b ? b : a.V = Ka(b);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return a;
|
|
}
|
|
function Ub(a, b, c, d) {
|
|
if (null != a) {
|
|
if (Array.isArray(a)) a = Vb(a, b, c, void 0 !== d);
|
|
else if (Eb(a)) {
|
|
var e = {}, g;
|
|
for(g in a)e[g] = Ub(a[g], b, c, d);
|
|
a = e;
|
|
} else a = b(a, d);
|
|
return a;
|
|
}
|
|
}
|
|
function Vb(a, b, c, d) {
|
|
var e = Q(a);
|
|
d = d ? !!(e & 16) : void 0;
|
|
a = Array.prototype.slice.call(a);
|
|
for(var g = 0; g < a.length; g++)a[g] = Ub(a[g], b, c, d);
|
|
c(e, a);
|
|
return a;
|
|
}
|
|
function Wb(a) {
|
|
return a.ja === Db ? a.toJSON() : Tb(a);
|
|
}
|
|
function Xb(a, b) {
|
|
a & 128 && Ib(b);
|
|
}
|
|
function Yb(a, b, c) {
|
|
c = void 0 === c ? Cb : c;
|
|
if (null != a) {
|
|
if (Ia && a instanceof Uint8Array) return a.length ? new ib(new Uint8Array(a), Qa) : jb();
|
|
if (Array.isArray(a)) {
|
|
var d = Q(a);
|
|
if (d & 2) return a;
|
|
if (b && !(d & 32) && (d & 16 || 0 === d)) return R(a, d | 2), a;
|
|
a = Vb(a, Yb, d & 4 ? Cb : c, !0);
|
|
b = Q(a);
|
|
b & 4 && b & 2 && Object.freeze(a);
|
|
return a;
|
|
}
|
|
return a.ja === Db ? Zb(a) : a;
|
|
}
|
|
}
|
|
function $b(a, b, c, d, e, g, f) {
|
|
if (a = a.h && a.h[c]) {
|
|
d = Q(a);
|
|
d & 2 ? d = a : (g = Ca(a, Zb), Cb(d, g), Object.freeze(g), d = g);
|
|
Hb(b);
|
|
f = null == d ? Fb : Ab([]);
|
|
if (null != d) {
|
|
g = !!d.length;
|
|
for(a = 0; a < d.length; a++){
|
|
var h = d[a];
|
|
g = g && !(Q(h.o) & 2);
|
|
f[a] = h.o;
|
|
}
|
|
g = (g ? 8 : 0) | 1;
|
|
a = Q(f);
|
|
(a & g) !== g && (Object.isFrozen(f) && (f = Array.prototype.slice.call(f)), R(f, a | g));
|
|
b.h || (b.h = {});
|
|
b.h[c] = d;
|
|
} else b.h && (b.h[c] = void 0);
|
|
Kb(b, c, f, e);
|
|
} else U(b, c, Yb(d, g, f), e);
|
|
}
|
|
function Zb(a) {
|
|
if (Q(a.o) & 2) return a;
|
|
a = Pb(a, !0);
|
|
P(a.o, 2);
|
|
return a;
|
|
}
|
|
function Pb(a, b) {
|
|
var c = a.o, d = [];
|
|
P(d, 16);
|
|
var e = a.constructor.h;
|
|
e && d.push(e);
|
|
e = a.B;
|
|
if (e) {
|
|
d.length = c.length;
|
|
d.fill(void 0, d.length, c.length);
|
|
var g = {};
|
|
d[d.length - 1] = g;
|
|
}
|
|
0 !== (Q(c) & 128) && Ib(d);
|
|
b = b || a.C() ? Cb : Bb;
|
|
g = a.constructor;
|
|
Sb = d;
|
|
d = new g(d);
|
|
Sb = void 0;
|
|
a.R && (d.R = a.R.slice());
|
|
g = !!(Q(c) & 16);
|
|
for(var f = e ? c.length - 1 : c.length, h = 0; h < f; h++)$b(a, d, h - a.G, c[h], !1, g, b);
|
|
if (e) for(var k in e)$b(a, d, +k, e[k], !0, g, b);
|
|
return d;
|
|
}
|
|
function X(a, b, c) {
|
|
null == a && (a = Sb);
|
|
Sb = void 0;
|
|
var d = this.constructor.i || 0, e = 0 < d, g = this.constructor.h, f = !1;
|
|
if (null == a) {
|
|
a = g ? [
|
|
g
|
|
] : [];
|
|
var h = 48;
|
|
var k = !0;
|
|
e && (d = 0, h |= 128);
|
|
R(a, h);
|
|
} else {
|
|
if (!Array.isArray(a)) throw Error();
|
|
if (g && g !== a[0]) throw Error();
|
|
var l = h = P(a, 0);
|
|
if (k = 0 !== (16 & l)) (f = 0 !== (32 & l)) || (l |= 32);
|
|
if (e) {
|
|
if (128 & l) d = 0;
|
|
else if (0 < a.length) {
|
|
var m = a[a.length - 1];
|
|
if (Eb(m) && "g" in m) {
|
|
d = 0;
|
|
l |= 128;
|
|
delete m.g;
|
|
var r = !0, p;
|
|
for(p in m){
|
|
r = !1;
|
|
break;
|
|
}
|
|
r && a.pop();
|
|
}
|
|
}
|
|
} else if (128 & l) throw Error();
|
|
h !== l && R(a, l);
|
|
}
|
|
this.G = (g ? 0 : -1) - d;
|
|
this.h = void 0;
|
|
this.o = a;
|
|
a: {
|
|
g = this.o.length;
|
|
d = g - 1;
|
|
if (g && (g = this.o[d], Eb(g))) {
|
|
this.B = g;
|
|
this.i = d - this.G;
|
|
break a;
|
|
}
|
|
void 0 !== b && -1 < b ? (this.i = Math.max(b, d + 1 - this.G), this.B = void 0) : this.i = Number.MAX_VALUE;
|
|
}
|
|
if (!e && this.B && "g" in this.B) throw Error('Unexpected "g" flag in sparse object of message that is not a group type.');
|
|
if (c) {
|
|
b = k && !f && !0;
|
|
e = this.i;
|
|
var n;
|
|
for(k = 0; k < c.length; k++)f = c[k], f < e ? (f += this.G, (d = a[f]) ? ac(d, b) : a[f] = Fb) : (n || (n = Jb(this)), (d = n[f]) ? ac(d, b) : n[f] = Fb);
|
|
}
|
|
}
|
|
X.prototype.toJSON = function() {
|
|
return Vb(this.o, Wb, Xb);
|
|
};
|
|
X.prototype.C = function() {
|
|
return !!(Q(this.o) & 2);
|
|
};
|
|
function ac(a, b) {
|
|
if (Array.isArray(a)) {
|
|
var c = Q(a), d = 1;
|
|
!b || c & 2 || (d |= 16);
|
|
(c & d) !== d && R(a, c | d);
|
|
}
|
|
}
|
|
X.prototype.ja = Db;
|
|
X.prototype.toString = function() {
|
|
return this.o.toString();
|
|
};
|
|
function bc(a, b, c) {
|
|
if (c) {
|
|
var d = {}, e;
|
|
for(e in c){
|
|
var g = c[e], f = g.ra;
|
|
f || (d.J = g.xa || g.oa.W, g.ia ? (d.aa = cc(g.ia), f = function(h) {
|
|
return function(k, l, m) {
|
|
return h.J(k, l, m, h.aa);
|
|
};
|
|
}(d)) : g.ka ? (d.Z = dc(g.da.P, g.ka), f = function(h) {
|
|
return function(k, l, m) {
|
|
return h.J(k, l, m, h.Z);
|
|
};
|
|
}(d)) : f = d.J, g.ra = f);
|
|
f(b, a, g.da);
|
|
d = {
|
|
J: d.J,
|
|
aa: d.aa,
|
|
Z: d.Z
|
|
};
|
|
}
|
|
}
|
|
yb(b, a);
|
|
}
|
|
var ec = Symbol();
|
|
function fc(a, b, c) {
|
|
return a[ec] || (a[ec] = function(d, e) {
|
|
return b(d, e, c);
|
|
});
|
|
}
|
|
function gc(a) {
|
|
var b = a[ec];
|
|
if (!b) {
|
|
var c = hc(a);
|
|
b = function(d, e) {
|
|
return ic(d, e, c);
|
|
};
|
|
a[ec] = b;
|
|
}
|
|
return b;
|
|
}
|
|
function jc(a) {
|
|
var b = a.ia;
|
|
if (b) return gc(b);
|
|
if (b = a.wa) return fc(a.da.P, b, a.ka);
|
|
}
|
|
function kc(a) {
|
|
var b = jc(a), c = a.da, d = a.oa.U;
|
|
return b ? function(e, g) {
|
|
return d(e, g, c, b);
|
|
} : function(e, g) {
|
|
return d(e, g, c);
|
|
};
|
|
}
|
|
function lc(a, b) {
|
|
var c = a[b];
|
|
"function" == typeof c && 0 === c.length && (c = c(), a[b] = c);
|
|
return Array.isArray(c) && (mc in c || nc in c || 0 < c.length && "function" == typeof c[0]) ? c : void 0;
|
|
}
|
|
function oc(a, b, c, d, e, g) {
|
|
b.P = a[0];
|
|
var f = 1;
|
|
if (a.length > f && "number" !== typeof a[f]) {
|
|
var h = a[f++];
|
|
c(b, h);
|
|
}
|
|
for(; f < a.length;){
|
|
c = a[f++];
|
|
for(var k = f + 1; k < a.length && "number" !== typeof a[k];)k++;
|
|
h = a[f++];
|
|
k -= f;
|
|
switch(k){
|
|
case 0:
|
|
d(b, c, h);
|
|
break;
|
|
case 1:
|
|
(k = lc(a, f)) ? (f++, e(b, c, h, k)) : d(b, c, h, a[f++]);
|
|
break;
|
|
case 2:
|
|
k = f++;
|
|
k = lc(a, k);
|
|
e(b, c, h, k, a[f++]);
|
|
break;
|
|
case 3:
|
|
g(b, c, h, a[f++], a[f++], a[f++]);
|
|
break;
|
|
case 4:
|
|
g(b, c, h, a[f++], a[f++], a[f++], a[f++]);
|
|
break;
|
|
default:
|
|
throw Error("unexpected number of binary field arguments: " + k);
|
|
}
|
|
}
|
|
return b;
|
|
}
|
|
var pc = Symbol();
|
|
function cc(a) {
|
|
var b = a[pc];
|
|
if (!b) {
|
|
var c = qc(a);
|
|
b = function(d, e) {
|
|
return rc(d, e, c);
|
|
};
|
|
a[pc] = b;
|
|
}
|
|
return b;
|
|
}
|
|
function dc(a, b) {
|
|
var c = a[pc];
|
|
c || (c = function(d, e) {
|
|
return bc(d, e, b);
|
|
}, a[pc] = c);
|
|
return c;
|
|
}
|
|
var nc = Symbol();
|
|
function sc(a, b) {
|
|
a.push(b);
|
|
}
|
|
function tc(a, b, c) {
|
|
a.push(b, c.W);
|
|
}
|
|
function uc(a, b, c, d) {
|
|
var e = cc(d), g = qc(d).P, f = c.W;
|
|
a.push(b, function(h, k, l) {
|
|
return f(h, k, l, g, e);
|
|
});
|
|
}
|
|
function vc(a, b, c, d, e, g) {
|
|
var f = dc(d, g), h = c.W;
|
|
a.push(b, function(k, l, m) {
|
|
return h(k, l, m, d, f);
|
|
});
|
|
}
|
|
function qc(a) {
|
|
var b = a[nc];
|
|
if (b) return b;
|
|
b = oc(a, a[nc] = [], sc, tc, uc, vc);
|
|
mc in a && nc in a && (a.length = 0);
|
|
return b;
|
|
}
|
|
var mc = Symbol();
|
|
function wc(a, b) {
|
|
a[0] = b;
|
|
}
|
|
function xc(a, b, c, d) {
|
|
var e = c.U;
|
|
a[b] = d ? function(g, f, h) {
|
|
return e(g, f, h, d);
|
|
} : e;
|
|
}
|
|
function yc(a, b, c, d, e) {
|
|
var g = c.U, f = gc(d), h = hc(d).P;
|
|
a[b] = function(k, l, m) {
|
|
return g(k, l, m, h, f, e);
|
|
};
|
|
}
|
|
function zc(a, b, c, d, e, g, f) {
|
|
var h = c.U, k = fc(d, e, g);
|
|
a[b] = function(l, m, r) {
|
|
return h(l, m, r, d, k, f);
|
|
};
|
|
}
|
|
function hc(a) {
|
|
var b = a[mc];
|
|
if (b) return b;
|
|
b = oc(a, a[mc] = {}, wc, xc, yc, zc);
|
|
mc in a && nc in a && (a.length = 0);
|
|
return b;
|
|
}
|
|
function ic(a, b, c) {
|
|
for(; ub(b) && 4 != b.i;){
|
|
var d = b.l, e = c[d];
|
|
if (!e) {
|
|
var g = c[0];
|
|
g && (g = g[d]) && (e = c[d] = kc(g));
|
|
}
|
|
if (!e || !e(b, a, d)) {
|
|
e = b;
|
|
d = a;
|
|
g = e.j;
|
|
vb(e);
|
|
var f = e;
|
|
if (!f.ca) {
|
|
e = f.h.h - g;
|
|
f.h.h = g;
|
|
f = f.h;
|
|
if (0 == e) e = jb();
|
|
else {
|
|
g = pb(f, e);
|
|
if (f.S && f.m) e = f.i.subarray(g, g + e);
|
|
else {
|
|
f = f.i;
|
|
var h = g;
|
|
e = g + e;
|
|
e = h === e ? Pa() : Ra ? f.slice(h, e) : new Uint8Array(f.subarray(h, e));
|
|
}
|
|
e = 0 == e.length ? jb() : new ib(e, Qa);
|
|
}
|
|
(g = d.R) ? g.push(e) : d.R = [
|
|
e
|
|
];
|
|
}
|
|
}
|
|
}
|
|
return a;
|
|
}
|
|
function rc(a, b, c) {
|
|
for(var d = c.length, e = 1 == d % 2, g = e ? 1 : 0; g < d; g += 2)(0, c[g + 1])(b, a, c[g]);
|
|
bc(a, b, e ? c[0] : void 0);
|
|
}
|
|
function Ac(a, b) {
|
|
return {
|
|
U: a,
|
|
W: b
|
|
};
|
|
}
|
|
var Y = Ac(function(a, b, c) {
|
|
if (5 !== a.i) return !1;
|
|
a = a.h;
|
|
var d = a.i, e = a.h, g = d[e];
|
|
var f = d[e + 1];
|
|
var h = d[e + 2];
|
|
d = d[e + 3];
|
|
L(a, a.h + 4);
|
|
f = (g << 0 | f << 8 | h << 16 | d << 24) >>> 0;
|
|
a = 2 * (f >> 31) + 1;
|
|
g = f >>> 23 & 255;
|
|
f &= 8388607;
|
|
U(b, c, 255 == g ? f ? NaN : Infinity * a : 0 == g ? a * Math.pow(2, -149) * f : a * Math.pow(2, g - 150) * (f + Math.pow(2, 23)));
|
|
return !0;
|
|
}, function(a, b, c) {
|
|
b = Mb(b, c);
|
|
if (null != b) {
|
|
M(a.h, 8 * c + 5);
|
|
a = a.h;
|
|
var d = +b;
|
|
0 === d ? 0 < 1 / d ? G = H = 0 : (H = 0, G = 2147483648) : isNaN(d) ? (H = 0, G = 2147483647) : (d = (c = 0 > d ? -2147483648 : 0) ? -d : d, 3.4028234663852886E38 < d ? (H = 0, G = (c | 2139095040) >>> 0) : 1.1754943508222875E-38 > d ? (d = Math.round(d / Math.pow(2, -149)), H = 0, G = (c | d) >>> 0) : (b = Math.floor(Math.log(d) / Math.LN2), d *= Math.pow(2, -b), d = Math.round(8388608 * d), 16777216 <= d && ++b, H = 0, G = (c | b + 127 << 23 | d & 8388607) >>> 0));
|
|
c = G;
|
|
a.h.push(c >>> 0 & 255);
|
|
a.h.push(c >>> 8 & 255);
|
|
a.h.push(c >>> 16 & 255);
|
|
a.h.push(c >>> 24 & 255);
|
|
}
|
|
}), Bc = Ac(function(a, b, c) {
|
|
if (0 !== a.i) return !1;
|
|
var d = a.h, e = 0, g = a = 0, f = d.i, h = d.h;
|
|
do {
|
|
var k = f[h++];
|
|
e |= (k & 127) << g;
|
|
g += 7;
|
|
}while (32 > g && k & 128);
|
|
32 < g && (a |= (k & 127) >> 4);
|
|
for(g = 3; 32 > g && k & 128; g += 7)k = f[h++], a |= (k & 127) << g;
|
|
L(d, h);
|
|
if (128 > k) {
|
|
d = e >>> 0;
|
|
k = a >>> 0;
|
|
if (a = k & 2147483648) d = ~d + 1 >>> 0, k = ~k >>> 0, 0 == d && (k = k + 1 >>> 0);
|
|
d = 4294967296 * k + (d >>> 0);
|
|
} else throw Za();
|
|
U(b, c, a ? -d : d);
|
|
return !0;
|
|
}, function(a, b, c) {
|
|
b = S(b, c);
|
|
null != b && ("string" === typeof b && Wa(b), null != b && (M(a.h, 8 * c), "number" === typeof b ? (a = a.h, Sa(b), sb(a, G, H)) : (c = Wa(b), sb(a.h, c.i, c.h))));
|
|
}), Cc = Ac(function(a, b, c) {
|
|
if (0 !== a.i) return !1;
|
|
U(b, c, ob(a.h));
|
|
return !0;
|
|
}, function(a, b, c) {
|
|
b = S(b, c);
|
|
if (null != b && null != b) {
|
|
if (M(a.h, 8 * c), a = a.h, c = b, 0 <= c) M(a, c);
|
|
else {
|
|
for(b = 0; 9 > b; b++)a.h.push(c & 127 | 128), c >>= 7;
|
|
a.h.push(1);
|
|
}
|
|
}
|
|
}), Dc = Ac(function(a, b, c) {
|
|
if (2 !== a.i) return !1;
|
|
var d = ob(a.h) >>> 0;
|
|
a = a.h;
|
|
var e = pb(a, d);
|
|
a = a.i;
|
|
if (db) {
|
|
var g = a, f;
|
|
(f = cb) || (f = cb = new TextDecoder("utf-8", {
|
|
fatal: !0
|
|
}));
|
|
a = e + d;
|
|
g = 0 === e && a === g.length ? g : g.subarray(e, a);
|
|
try {
|
|
var h = f.decode(g);
|
|
} catch (r) {
|
|
if (void 0 === bb) {
|
|
try {
|
|
f.decode(new Uint8Array([
|
|
128
|
|
]));
|
|
} catch (p) {}
|
|
try {
|
|
f.decode(new Uint8Array([
|
|
97
|
|
])), bb = !0;
|
|
} catch (p) {
|
|
bb = !1;
|
|
}
|
|
}
|
|
!bb && (cb = void 0);
|
|
throw r;
|
|
}
|
|
} else {
|
|
h = e;
|
|
d = h + d;
|
|
e = [];
|
|
for(var k = null, l, m; h < d;)l = a[h++], 128 > l ? e.push(l) : 224 > l ? h >= d ? K() : (m = a[h++], 194 > l || 128 !== (m & 192) ? (h--, K()) : e.push((l & 31) << 6 | m & 63)) : 240 > l ? h >= d - 1 ? K() : (m = a[h++], 128 !== (m & 192) || 224 === l && 160 > m || 237 === l && 160 <= m || 128 !== ((g = a[h++]) & 192) ? (h--, K()) : e.push((l & 15) << 12 | (m & 63) << 6 | g & 63)) : 244 >= l ? h >= d - 2 ? K() : (m = a[h++], 128 !== (m & 192) || 0 !== (l << 28) + (m - 144) >> 30 || 128 !== ((g = a[h++]) & 192) || 128 !== ((f = a[h++]) & 192) ? (h--, K()) : (l = (l & 7) << 18 | (m & 63) << 12 | (g & 63) << 6 | f & 63, l -= 65536, e.push((l >> 10 & 1023) + 55296, (l & 1023) + 56320))) : K(), 8192 <= e.length && (k = ab(k, e), e.length = 0);
|
|
h = ab(k, e);
|
|
}
|
|
U(b, c, h);
|
|
return !0;
|
|
}, function(a, b, c) {
|
|
b = S(b, c);
|
|
if (null != b) {
|
|
var d = !1;
|
|
d = void 0 === d ? !1 : d;
|
|
if (fb) {
|
|
if (d && /(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(b)) throw Error("Found an unpaired surrogate");
|
|
b = (eb || (eb = new TextEncoder)).encode(b);
|
|
} else {
|
|
for(var e = 0, g = new Uint8Array(3 * b.length), f = 0; f < b.length; f++){
|
|
var h = b.charCodeAt(f);
|
|
if (128 > h) g[e++] = h;
|
|
else {
|
|
if (2048 > h) g[e++] = h >> 6 | 192;
|
|
else {
|
|
if (55296 <= h && 57343 >= h) {
|
|
if (56319 >= h && f < b.length) {
|
|
var k = b.charCodeAt(++f);
|
|
if (56320 <= k && 57343 >= k) {
|
|
h = 1024 * (h - 55296) + k - 56320 + 65536;
|
|
g[e++] = h >> 18 | 240;
|
|
g[e++] = h >> 12 & 63 | 128;
|
|
g[e++] = h >> 6 & 63 | 128;
|
|
g[e++] = h & 63 | 128;
|
|
continue;
|
|
} else f--;
|
|
}
|
|
if (d) throw Error("Found an unpaired surrogate");
|
|
h = 65533;
|
|
}
|
|
g[e++] = h >> 12 | 224;
|
|
g[e++] = h >> 6 & 63 | 128;
|
|
}
|
|
g[e++] = h & 63 | 128;
|
|
}
|
|
}
|
|
b = e === g.length ? g : g.subarray(0, e);
|
|
}
|
|
M(a.h, 8 * c + 2);
|
|
M(a.h, b.length);
|
|
N(a, a.h.end());
|
|
N(a, b);
|
|
}
|
|
}), Ec = Ac(function(a, b, c, d, e) {
|
|
if (2 !== a.i) return !1;
|
|
b = Qb(b, c, d);
|
|
c = a.h.j;
|
|
d = ob(a.h) >>> 0;
|
|
var g = a.h.h + d, f = g - c;
|
|
0 >= f && (a.h.j = g, e(b, a, void 0, void 0, void 0), f = g - a.h.h);
|
|
if (f) throw Error("Message parsing ended unexpectedly. Expected to read " + (d + " bytes, instead read " + (d - f) + " bytes, either the data ended unexpectedly or the message misreported its own length"));
|
|
a.h.h = g;
|
|
a.h.j = c;
|
|
return !0;
|
|
}, function(a, b, c, d, e) {
|
|
b = Ob(b, d, c);
|
|
if (null != b) for(d = 0; d < b.length; d++){
|
|
var g = a;
|
|
M(g.h, 8 * c + 2);
|
|
var f = g.h.end();
|
|
N(g, f);
|
|
f.push(g.i);
|
|
g = f;
|
|
e(b[d], a);
|
|
f = a;
|
|
var h = g.pop();
|
|
for(h = f.i + f.h.length() - h; 127 < h;)g.push(h & 127 | 128), h >>>= 7, f.i++;
|
|
g.push(h);
|
|
f.i++;
|
|
}
|
|
});
|
|
function Fc(a) {
|
|
return function(b, c) {
|
|
a: {
|
|
if (wb.length) {
|
|
var d = wb.pop();
|
|
d.setOptions(c);
|
|
nb(d.h, b, c);
|
|
b = d;
|
|
} else b = new tb(b, c);
|
|
try {
|
|
var e = hc(a);
|
|
var g = ic(new e.P, b, e);
|
|
break a;
|
|
} finally{
|
|
e = b.h, e.i = null, e.m = !1, e.l = 0, e.j = 0, e.h = 0, e.S = !1, b.l = -1, b.i = -1, 100 > wb.length && wb.push(b);
|
|
}
|
|
g = void 0;
|
|
}
|
|
return g;
|
|
};
|
|
}
|
|
function Gc(a) {
|
|
return function() {
|
|
var b = new xb;
|
|
rc(this, b, qc(a));
|
|
N(b, b.h.end());
|
|
for(var c = new Uint8Array(b.i), d = b.j, e = d.length, g = 0, f = 0; f < e; f++){
|
|
var h = d[f];
|
|
c.set(h, g);
|
|
g += h.length;
|
|
}
|
|
b.j = [
|
|
c
|
|
];
|
|
return c;
|
|
};
|
|
}
|
|
function Z(a) {
|
|
X.call(this, a);
|
|
}
|
|
na(Z, X);
|
|
var Hc = [
|
|
Z,
|
|
1,
|
|
Cc,
|
|
2,
|
|
Y,
|
|
3,
|
|
Dc,
|
|
4,
|
|
Dc
|
|
];
|
|
Z.prototype.l = Gc(Hc);
|
|
function Ic(a) {
|
|
X.call(this, a, -1, Jc);
|
|
}
|
|
na(Ic, X);
|
|
Ic.prototype.addClassification = function(a, b) {
|
|
Qb(this, 1, Z, a, b);
|
|
return this;
|
|
};
|
|
var Jc = [
|
|
1
|
|
], Kc = Fc([
|
|
Ic,
|
|
1,
|
|
Ec,
|
|
Hc
|
|
]);
|
|
function Lc(a) {
|
|
X.call(this, a);
|
|
}
|
|
na(Lc, X);
|
|
var Mc = [
|
|
Lc,
|
|
1,
|
|
Y,
|
|
2,
|
|
Y,
|
|
3,
|
|
Y,
|
|
4,
|
|
Y,
|
|
5,
|
|
Y
|
|
];
|
|
Lc.prototype.l = Gc(Mc);
|
|
function Nc(a) {
|
|
X.call(this, a, -1, Oc);
|
|
}
|
|
na(Nc, X);
|
|
var Oc = [
|
|
1
|
|
], Pc = Fc([
|
|
Nc,
|
|
1,
|
|
Ec,
|
|
Mc
|
|
]);
|
|
function Qc(a) {
|
|
X.call(this, a);
|
|
}
|
|
na(Qc, X);
|
|
var Rc = [
|
|
Qc,
|
|
1,
|
|
Y,
|
|
2,
|
|
Y,
|
|
3,
|
|
Y,
|
|
4,
|
|
Y,
|
|
5,
|
|
Y,
|
|
6,
|
|
Bc
|
|
], Sc = Fc(Rc);
|
|
Qc.prototype.l = Gc(Rc);
|
|
function Tc(a, b, c) {
|
|
c = a.createShader(0 === c ? a.VERTEX_SHADER : a.FRAGMENT_SHADER);
|
|
a.shaderSource(c, b);
|
|
a.compileShader(c);
|
|
if (!a.getShaderParameter(c, a.COMPILE_STATUS)) throw Error("Could not compile WebGL shader.\n\n" + a.getShaderInfoLog(c));
|
|
return c;
|
|
}
|
|
function Uc(a) {
|
|
return Ob(a, Z, 1).map(function(b) {
|
|
var c = S(b, 1);
|
|
return {
|
|
index: null == c ? 0 : c,
|
|
qa: W(b, 2),
|
|
label: null != S(b, 3) ? Rb(S(b, 3), "") : void 0,
|
|
displayName: null != S(b, 4) ? Rb(S(b, 4), "") : void 0
|
|
};
|
|
});
|
|
}
|
|
function Vc(a) {
|
|
return {
|
|
x: W(a, 1),
|
|
y: W(a, 2),
|
|
z: W(a, 3),
|
|
visibility: null != Mb(a, 4) ? W(a, 4) : void 0
|
|
};
|
|
}
|
|
function Wc(a, b) {
|
|
this.i = a;
|
|
this.h = b;
|
|
this.m = 0;
|
|
}
|
|
function Xc(a, b, c) {
|
|
Yc(a, b);
|
|
if ("function" === typeof a.h.canvas.transferToImageBitmap) return Promise.resolve(a.h.canvas.transferToImageBitmap());
|
|
if (c) return Promise.resolve(a.h.canvas);
|
|
if ("function" === typeof createImageBitmap) return createImageBitmap(a.h.canvas);
|
|
void 0 === a.j && (a.j = document.createElement("canvas"));
|
|
return new Promise(function(d) {
|
|
a.j.height = a.h.canvas.height;
|
|
a.j.width = a.h.canvas.width;
|
|
a.j.getContext("2d", {}).drawImage(a.h.canvas, 0, 0, a.h.canvas.width, a.h.canvas.height);
|
|
d(a.j);
|
|
});
|
|
}
|
|
function Yc(a, b) {
|
|
var c = a.h;
|
|
if (void 0 === a.s) {
|
|
var d = Tc(c, "\n attribute vec2 aVertex;\n attribute vec2 aTex;\n varying vec2 vTex;\n void main(void) {\n gl_Position = vec4(aVertex, 0.0, 1.0);\n vTex = aTex;\n }", 0), e = Tc(c, "\n precision mediump float;\n varying vec2 vTex;\n uniform sampler2D sampler0;\n void main(){\n gl_FragColor = texture2D(sampler0, vTex);\n }", 1), g = c.createProgram();
|
|
c.attachShader(g, d);
|
|
c.attachShader(g, e);
|
|
c.linkProgram(g);
|
|
if (!c.getProgramParameter(g, c.LINK_STATUS)) throw Error("Could not compile WebGL program.\n\n" + c.getProgramInfoLog(g));
|
|
d = a.s = g;
|
|
c.useProgram(d);
|
|
e = c.getUniformLocation(d, "sampler0");
|
|
a.l = {
|
|
O: c.getAttribLocation(d, "aVertex"),
|
|
N: c.getAttribLocation(d, "aTex"),
|
|
ya: e
|
|
};
|
|
a.v = c.createBuffer();
|
|
c.bindBuffer(c.ARRAY_BUFFER, a.v);
|
|
c.enableVertexAttribArray(a.l.O);
|
|
c.vertexAttribPointer(a.l.O, 2, c.FLOAT, !1, 0, 0);
|
|
c.bufferData(c.ARRAY_BUFFER, new Float32Array([
|
|
-1,
|
|
-1,
|
|
-1,
|
|
1,
|
|
1,
|
|
1,
|
|
1,
|
|
-1
|
|
]), c.STATIC_DRAW);
|
|
c.bindBuffer(c.ARRAY_BUFFER, null);
|
|
a.u = c.createBuffer();
|
|
c.bindBuffer(c.ARRAY_BUFFER, a.u);
|
|
c.enableVertexAttribArray(a.l.N);
|
|
c.vertexAttribPointer(a.l.N, 2, c.FLOAT, !1, 0, 0);
|
|
c.bufferData(c.ARRAY_BUFFER, new Float32Array([
|
|
0,
|
|
1,
|
|
0,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1
|
|
]), c.STATIC_DRAW);
|
|
c.bindBuffer(c.ARRAY_BUFFER, null);
|
|
c.uniform1i(e, 0);
|
|
}
|
|
d = a.l;
|
|
c.useProgram(a.s);
|
|
c.canvas.width = b.width;
|
|
c.canvas.height = b.height;
|
|
c.viewport(0, 0, b.width, b.height);
|
|
c.activeTexture(c.TEXTURE0);
|
|
a.i.bindTexture2d(b.glName);
|
|
c.enableVertexAttribArray(d.O);
|
|
c.bindBuffer(c.ARRAY_BUFFER, a.v);
|
|
c.vertexAttribPointer(d.O, 2, c.FLOAT, !1, 0, 0);
|
|
c.enableVertexAttribArray(d.N);
|
|
c.bindBuffer(c.ARRAY_BUFFER, a.u);
|
|
c.vertexAttribPointer(d.N, 2, c.FLOAT, !1, 0, 0);
|
|
c.bindFramebuffer(c.DRAW_FRAMEBUFFER ? c.DRAW_FRAMEBUFFER : c.FRAMEBUFFER, null);
|
|
c.clearColor(0, 0, 0, 0);
|
|
c.clear(c.COLOR_BUFFER_BIT);
|
|
c.colorMask(!0, !0, !0, !0);
|
|
c.drawArrays(c.TRIANGLE_FAN, 0, 4);
|
|
c.disableVertexAttribArray(d.O);
|
|
c.disableVertexAttribArray(d.N);
|
|
c.bindBuffer(c.ARRAY_BUFFER, null);
|
|
a.i.bindTexture2d(0);
|
|
}
|
|
function Zc(a) {
|
|
this.h = a;
|
|
}
|
|
var $c = new Uint8Array([
|
|
0,
|
|
97,
|
|
115,
|
|
109,
|
|
1,
|
|
0,
|
|
0,
|
|
0,
|
|
1,
|
|
4,
|
|
1,
|
|
96,
|
|
0,
|
|
0,
|
|
3,
|
|
2,
|
|
1,
|
|
0,
|
|
10,
|
|
9,
|
|
1,
|
|
7,
|
|
0,
|
|
65,
|
|
0,
|
|
253,
|
|
15,
|
|
26,
|
|
11
|
|
]);
|
|
function ad(a, b) {
|
|
return b + a;
|
|
}
|
|
function bd(a, b) {
|
|
window[a] = b;
|
|
}
|
|
function cd(a) {
|
|
var b = document.createElement("script");
|
|
b.setAttribute("src", a);
|
|
b.setAttribute("crossorigin", "anonymous");
|
|
return new Promise(function(c) {
|
|
b.addEventListener("load", function() {
|
|
c();
|
|
}, !1);
|
|
b.addEventListener("error", function() {
|
|
c();
|
|
}, !1);
|
|
document.body.appendChild(b);
|
|
});
|
|
}
|
|
function dd() {
|
|
return E(function(a) {
|
|
switch(a.h){
|
|
case 1:
|
|
return a.s = 2, D(a, WebAssembly.instantiate($c), 4);
|
|
case 4:
|
|
a.h = 3;
|
|
a.s = 0;
|
|
break;
|
|
case 2:
|
|
return a.s = 0, a.l = null, a.return(!1);
|
|
case 3:
|
|
return a.return(!0);
|
|
}
|
|
});
|
|
}
|
|
function ed(a) {
|
|
this.h = a;
|
|
this.listeners = {};
|
|
this.l = {};
|
|
this.L = {};
|
|
this.s = {};
|
|
this.v = {};
|
|
this.M = this.u = this.ga = !0;
|
|
this.I = Promise.resolve();
|
|
this.fa = "";
|
|
this.D = {};
|
|
this.locateFile = a && a.locateFile || ad;
|
|
if ("object" === typeof window) var b = window.location.pathname.toString().substring(0, window.location.pathname.toString().lastIndexOf("/")) + "/";
|
|
else if ("undefined" !== typeof location) b = location.pathname.toString().substring(0, location.pathname.toString().lastIndexOf("/")) + "/";
|
|
else throw Error("solutions can only be loaded on a web page or in a web worker");
|
|
this.ha = b;
|
|
if (a.options) {
|
|
b = A(Object.keys(a.options));
|
|
for(var c = b.next(); !c.done; c = b.next()){
|
|
c = c.value;
|
|
var d = a.options[c].default;
|
|
void 0 !== d && (this.l[c] = "function" === typeof d ? d() : d);
|
|
}
|
|
}
|
|
}
|
|
x = ed.prototype;
|
|
x.close = function() {
|
|
this.j && this.j.delete();
|
|
return Promise.resolve();
|
|
};
|
|
function fd(a) {
|
|
var b, c, d, e, g, f, h, k, l, m, r;
|
|
return E(function(p) {
|
|
switch(p.h){
|
|
case 1:
|
|
if (!a.ga) return p.return();
|
|
b = void 0 === a.h.files ? [] : "function" === typeof a.h.files ? a.h.files(a.l) : a.h.files;
|
|
return D(p, dd(), 2);
|
|
case 2:
|
|
c = p.i;
|
|
if ("object" === typeof window) return bd("createMediapipeSolutionsWasm", {
|
|
locateFile: a.locateFile
|
|
}), bd("createMediapipeSolutionsPackedAssets", {
|
|
locateFile: a.locateFile
|
|
}), f = b.filter(function(n) {
|
|
return void 0 !== n.data;
|
|
}), h = b.filter(function(n) {
|
|
return void 0 === n.data;
|
|
}), k = Promise.all(f.map(function(n) {
|
|
var q = gd(a, n.url);
|
|
if (void 0 !== n.path) {
|
|
var t = n.path;
|
|
q = q.then(function(w) {
|
|
a.overrideFile(t, w);
|
|
return Promise.resolve(w);
|
|
});
|
|
}
|
|
return q;
|
|
})), l = Promise.all(h.map(function(n) {
|
|
return void 0 === n.simd || n.simd && c || !n.simd && !c ? cd(a.locateFile(n.url, a.ha)) : Promise.resolve();
|
|
})).then(function() {
|
|
var n, q, t;
|
|
return E(function(w) {
|
|
if (1 == w.h) return n = window.createMediapipeSolutionsWasm, q = window.createMediapipeSolutionsPackedAssets, t = a, D(w, n(q), 2);
|
|
t.i = w.i;
|
|
w.h = 0;
|
|
});
|
|
}), m = function() {
|
|
return E(function(n) {
|
|
a.h.graph && a.h.graph.url ? n = D(n, gd(a, a.h.graph.url), 0) : (n.h = 0, n = void 0);
|
|
return n;
|
|
});
|
|
}(), D(p, Promise.all([
|
|
l,
|
|
k,
|
|
m
|
|
]), 7);
|
|
if ("function" !== typeof importScripts) throw Error("solutions can only be loaded on a web page or in a web worker");
|
|
d = b.filter(function(n) {
|
|
return void 0 === n.simd || n.simd && c || !n.simd && !c;
|
|
}).map(function(n) {
|
|
return a.locateFile(n.url, a.ha);
|
|
});
|
|
importScripts.apply(null, ea(d));
|
|
e = a;
|
|
return D(p, createMediapipeSolutionsWasm(Module), 6);
|
|
case 6:
|
|
e.i = p.i;
|
|
a.m = new OffscreenCanvas(1, 1);
|
|
a.i.canvas = a.m;
|
|
g = a.i.GL.createContext(a.m, {
|
|
antialias: !1,
|
|
alpha: !1,
|
|
va: "undefined" !== typeof WebGL2RenderingContext ? 2 : 1
|
|
});
|
|
a.i.GL.makeContextCurrent(g);
|
|
p.h = 4;
|
|
break;
|
|
case 7:
|
|
a.m = document.createElement("canvas");
|
|
r = a.m.getContext("webgl2", {});
|
|
if (!r && (r = a.m.getContext("webgl", {}), !r)) return alert("Failed to create WebGL canvas context when passing video frame."), p.return();
|
|
a.K = r;
|
|
a.i.canvas = a.m;
|
|
a.i.createContext(a.m, !0, !0, {});
|
|
case 4:
|
|
a.j = new a.i.SolutionWasm, a.ga = !1, p.h = 0;
|
|
}
|
|
});
|
|
}
|
|
function hd(a) {
|
|
var b, c, d, e, g, f, h, k;
|
|
return E(function(l) {
|
|
if (1 == l.h) {
|
|
if (a.h.graph && a.h.graph.url && a.fa === a.h.graph.url) return l.return();
|
|
a.u = !0;
|
|
if (!a.h.graph || !a.h.graph.url) {
|
|
l.h = 2;
|
|
return;
|
|
}
|
|
a.fa = a.h.graph.url;
|
|
return D(l, gd(a, a.h.graph.url), 3);
|
|
}
|
|
2 != l.h && (b = l.i, a.j.loadGraph(b));
|
|
c = A(Object.keys(a.D));
|
|
for(d = c.next(); !d.done; d = c.next())e = d.value, a.j.overrideFile(e, a.D[e]);
|
|
a.D = {};
|
|
if (a.h.listeners) for(g = A(a.h.listeners), f = g.next(); !f.done; f = g.next())h = f.value, id(a, h);
|
|
k = a.l;
|
|
a.l = {};
|
|
a.setOptions(k);
|
|
l.h = 0;
|
|
});
|
|
}
|
|
x.reset = function() {
|
|
var a = this;
|
|
return E(function(b) {
|
|
a.j && (a.j.reset(), a.s = {}, a.v = {});
|
|
b.h = 0;
|
|
});
|
|
};
|
|
x.setOptions = function(a, b) {
|
|
var c = this;
|
|
if (b = b || this.h.options) {
|
|
for(var d = [], e = [], g = {}, f = A(Object.keys(a)), h = f.next(); !h.done; g = {
|
|
X: g.X,
|
|
Y: g.Y
|
|
}, h = f.next())if (h = h.value, !(h in this.l && this.l[h] === a[h])) {
|
|
this.l[h] = a[h];
|
|
var k = b[h];
|
|
void 0 !== k && (k.onChange && (g.X = k.onChange, g.Y = a[h], d.push(function(l) {
|
|
return function() {
|
|
var m;
|
|
return E(function(r) {
|
|
if (1 == r.h) return D(r, l.X(l.Y), 2);
|
|
m = r.i;
|
|
!0 === m && (c.u = !0);
|
|
r.h = 0;
|
|
});
|
|
};
|
|
}(g))), k.graphOptionXref && (h = Object.assign({}, {
|
|
calculatorName: "",
|
|
calculatorIndex: 0
|
|
}, k.graphOptionXref, {
|
|
valueNumber: 1 === k.type ? a[h] : 0,
|
|
valueBoolean: 0 === k.type ? a[h] : !1,
|
|
valueString: 2 === k.type ? a[h] : ""
|
|
}), e.push(h)));
|
|
}
|
|
if (0 !== d.length || 0 !== e.length) this.u = !0, this.H = (void 0 === this.H ? [] : this.H).concat(e), this.F = (void 0 === this.F ? [] : this.F).concat(d);
|
|
}
|
|
};
|
|
function jd(a) {
|
|
var b, c, d, e, g, f, h;
|
|
return E(function(k) {
|
|
switch(k.h){
|
|
case 1:
|
|
if (!a.u) return k.return();
|
|
if (!a.F) {
|
|
k.h = 2;
|
|
break;
|
|
}
|
|
b = A(a.F);
|
|
c = b.next();
|
|
case 3:
|
|
if (c.done) {
|
|
k.h = 5;
|
|
break;
|
|
}
|
|
d = c.value;
|
|
return D(k, d(), 4);
|
|
case 4:
|
|
c = b.next();
|
|
k.h = 3;
|
|
break;
|
|
case 5:
|
|
a.F = void 0;
|
|
case 2:
|
|
if (a.H) {
|
|
e = new a.i.GraphOptionChangeRequestList;
|
|
g = A(a.H);
|
|
for(f = g.next(); !f.done; f = g.next())h = f.value, e.push_back(h);
|
|
a.j.changeOptions(e);
|
|
e.delete();
|
|
a.H = void 0;
|
|
}
|
|
a.u = !1;
|
|
k.h = 0;
|
|
}
|
|
});
|
|
}
|
|
x.initialize = function() {
|
|
var a = this;
|
|
return E(function(b) {
|
|
return 1 == b.h ? D(b, fd(a), 2) : 3 != b.h ? D(b, hd(a), 3) : D(b, jd(a), 0);
|
|
});
|
|
};
|
|
function gd(a, b) {
|
|
var c, d;
|
|
return E(function(e) {
|
|
if (b in a.L) return e.return(a.L[b]);
|
|
c = a.locateFile(b, "");
|
|
d = fetch(c).then(function(g) {
|
|
return g.arrayBuffer();
|
|
});
|
|
a.L[b] = d;
|
|
return e.return(d);
|
|
});
|
|
}
|
|
x.overrideFile = function(a, b) {
|
|
this.j ? this.j.overrideFile(a, b) : this.D[a] = b;
|
|
};
|
|
x.clearOverriddenFiles = function() {
|
|
this.D = {};
|
|
this.j && this.j.clearOverriddenFiles();
|
|
};
|
|
x.send = function(a, b) {
|
|
var c = this, d, e, g, f, h, k, l, m, r;
|
|
return E(function(p) {
|
|
switch(p.h){
|
|
case 1:
|
|
if (!c.h.inputs) return p.return();
|
|
d = 1E3 * (void 0 === b || null === b ? performance.now() : b);
|
|
return D(p, c.I, 2);
|
|
case 2:
|
|
return D(p, c.initialize(), 3);
|
|
case 3:
|
|
e = new c.i.PacketDataList;
|
|
g = A(Object.keys(a));
|
|
for(f = g.next(); !f.done; f = g.next())if (h = f.value, k = c.h.inputs[h]) {
|
|
a: {
|
|
var n = a[h];
|
|
switch(k.type){
|
|
case "video":
|
|
var q = c.s[k.stream];
|
|
q || (q = new Wc(c.i, c.K), c.s[k.stream] = q);
|
|
0 === q.m && (q.m = q.i.createTexture());
|
|
if ("undefined" !== typeof HTMLVideoElement && n instanceof HTMLVideoElement) {
|
|
var t = n.videoWidth;
|
|
var w = n.videoHeight;
|
|
} else "undefined" !== typeof HTMLImageElement && n instanceof HTMLImageElement ? (t = n.naturalWidth, w = n.naturalHeight) : (t = n.width, w = n.height);
|
|
w = {
|
|
glName: q.m,
|
|
width: t,
|
|
height: w
|
|
};
|
|
t = q.h;
|
|
t.canvas.width = w.width;
|
|
t.canvas.height = w.height;
|
|
t.activeTexture(t.TEXTURE0);
|
|
q.i.bindTexture2d(q.m);
|
|
t.texImage2D(t.TEXTURE_2D, 0, t.RGBA, t.RGBA, t.UNSIGNED_BYTE, n);
|
|
q.i.bindTexture2d(0);
|
|
q = w;
|
|
break a;
|
|
case "detections":
|
|
q = c.s[k.stream];
|
|
q || (q = new Zc(c.i), c.s[k.stream] = q);
|
|
q.data || (q.data = new q.h.DetectionListData);
|
|
q.data.reset(n.length);
|
|
for(w = 0; w < n.length; ++w){
|
|
t = n[w];
|
|
var v = q.data, B = v.setBoundingBox, J = w;
|
|
var I = t.la;
|
|
var u = new Qc;
|
|
V(u, 1, I.sa);
|
|
V(u, 2, I.ta);
|
|
V(u, 3, I.height);
|
|
V(u, 4, I.width);
|
|
V(u, 5, I.rotation);
|
|
U(u, 6, I.pa);
|
|
I = u.l();
|
|
B.call(v, J, I);
|
|
if (t.ea) for(v = 0; v < t.ea.length; ++v){
|
|
u = t.ea[v];
|
|
B = q.data;
|
|
J = B.addNormalizedLandmark;
|
|
I = w;
|
|
u = Object.assign({}, u, {
|
|
visibility: u.visibility ? u.visibility : 0
|
|
});
|
|
var C = new Lc;
|
|
V(C, 1, u.x);
|
|
V(C, 2, u.y);
|
|
V(C, 3, u.z);
|
|
u.visibility && V(C, 4, u.visibility);
|
|
u = C.l();
|
|
J.call(B, I, u);
|
|
}
|
|
if (t.ba) for(v = 0; v < t.ba.length; ++v)B = q.data, J = B.addClassification, I = w, u = t.ba[v], C = new Z, V(C, 2, u.qa), u.index && U(C, 1, u.index), u.label && U(C, 3, u.label), u.displayName && U(C, 4, u.displayName), u = C.l(), J.call(B, I, u);
|
|
}
|
|
q = q.data;
|
|
break a;
|
|
default:
|
|
q = {};
|
|
}
|
|
}
|
|
l = q;
|
|
m = k.stream;
|
|
switch(k.type){
|
|
case "video":
|
|
e.pushTexture2d(Object.assign({}, l, {
|
|
stream: m,
|
|
timestamp: d
|
|
}));
|
|
break;
|
|
case "detections":
|
|
r = l;
|
|
r.stream = m;
|
|
r.timestamp = d;
|
|
e.pushDetectionList(r);
|
|
break;
|
|
default:
|
|
throw Error("Unknown input config type: '" + k.type + "'");
|
|
}
|
|
}
|
|
c.j.send(e);
|
|
return D(p, c.I, 4);
|
|
case 4:
|
|
e.delete(), p.h = 0;
|
|
}
|
|
});
|
|
};
|
|
function kd(a, b, c) {
|
|
var d, e, g, f, h, k, l, m, r, p, n, q, t, w;
|
|
return E(function(v) {
|
|
switch(v.h){
|
|
case 1:
|
|
if (!c) return v.return(b);
|
|
d = {};
|
|
e = 0;
|
|
g = A(Object.keys(c));
|
|
for(f = g.next(); !f.done; f = g.next())h = f.value, k = c[h], "string" !== typeof k && "texture" === k.type && void 0 !== b[k.stream] && ++e;
|
|
1 < e && (a.M = !1);
|
|
l = A(Object.keys(c));
|
|
f = l.next();
|
|
case 2:
|
|
if (f.done) {
|
|
v.h = 4;
|
|
break;
|
|
}
|
|
m = f.value;
|
|
r = c[m];
|
|
if ("string" === typeof r) return t = d, w = m, D(v, ld(a, m, b[r]), 14);
|
|
p = b[r.stream];
|
|
if ("detection_list" === r.type) {
|
|
if (p) {
|
|
var B = p.getRectList();
|
|
for(var J = p.getLandmarksList(), I = p.getClassificationsList(), u = [], C = 0; C < B.size(); ++C){
|
|
var T = Sc(B.get(C)), od = W(T, 1), pd = W(T, 2), qd = W(T, 3), rd = W(T, 4), sd = W(T, 5, 0), za = void 0;
|
|
za = void 0 === za ? 0 : za;
|
|
T = {
|
|
la: {
|
|
sa: od,
|
|
ta: pd,
|
|
height: qd,
|
|
width: rd,
|
|
rotation: sd,
|
|
pa: Rb(S(T, 6), za)
|
|
},
|
|
ea: Ob(Pc(J.get(C)), Lc, 1).map(Vc),
|
|
ba: Uc(Kc(I.get(C)))
|
|
};
|
|
u.push(T);
|
|
}
|
|
B = u;
|
|
} else B = [];
|
|
d[m] = B;
|
|
v.h = 7;
|
|
break;
|
|
}
|
|
if ("proto_list" === r.type) {
|
|
if (p) {
|
|
B = Array(p.size());
|
|
for(J = 0; J < p.size(); J++)B[J] = p.get(J);
|
|
p.delete();
|
|
} else B = [];
|
|
d[m] = B;
|
|
v.h = 7;
|
|
break;
|
|
}
|
|
if (void 0 === p) {
|
|
v.h = 3;
|
|
break;
|
|
}
|
|
if ("float_list" === r.type) {
|
|
d[m] = p;
|
|
v.h = 7;
|
|
break;
|
|
}
|
|
if ("proto" === r.type) {
|
|
d[m] = p;
|
|
v.h = 7;
|
|
break;
|
|
}
|
|
if ("texture" !== r.type) throw Error("Unknown output config type: '" + r.type + "'");
|
|
n = a.v[m];
|
|
n || (n = new Wc(a.i, a.K), a.v[m] = n);
|
|
return D(v, Xc(n, p, a.M), 13);
|
|
case 13:
|
|
q = v.i, d[m] = q;
|
|
case 7:
|
|
r.transform && d[m] && (d[m] = r.transform(d[m]));
|
|
v.h = 3;
|
|
break;
|
|
case 14:
|
|
t[w] = v.i;
|
|
case 3:
|
|
f = l.next();
|
|
v.h = 2;
|
|
break;
|
|
case 4:
|
|
return v.return(d);
|
|
}
|
|
});
|
|
}
|
|
function ld(a, b, c) {
|
|
var d;
|
|
return E(function(e) {
|
|
return "number" === typeof c || c instanceof Uint8Array || c instanceof a.i.Uint8BlobList ? e.return(c) : c instanceof a.i.Texture2dDataOut ? (d = a.v[b], d || (d = new Wc(a.i, a.K), a.v[b] = d), e.return(Xc(d, c, a.M))) : e.return(void 0);
|
|
});
|
|
}
|
|
function id(a, b) {
|
|
for(var c = b.name || "$", d = [].concat(ea(b.wants)), e = new a.i.StringList, g = A(b.wants), f = g.next(); !f.done; f = g.next())e.push_back(f.value);
|
|
g = a.i.PacketListener.implement({
|
|
onResults: function(h) {
|
|
for(var k = {}, l = 0; l < b.wants.length; ++l)k[d[l]] = h.get(l);
|
|
var m = a.listeners[c];
|
|
m && (a.I = kd(a, k, b.outs).then(function(r) {
|
|
r = m(r);
|
|
for(var p = 0; p < b.wants.length; ++p){
|
|
var n = k[d[p]];
|
|
"object" === typeof n && n.hasOwnProperty && n.hasOwnProperty("delete") && n.delete();
|
|
}
|
|
r && (a.I = r);
|
|
}));
|
|
}
|
|
});
|
|
a.j.attachMultiListener(e, g);
|
|
e.delete();
|
|
}
|
|
x.onResults = function(a, b) {
|
|
this.listeners[b || "$"] = a;
|
|
};
|
|
Aa("Solution", ed);
|
|
Aa("OptionType", {
|
|
BOOL: 0,
|
|
NUMBER: 1,
|
|
ua: 2,
|
|
0: "BOOL",
|
|
1: "NUMBER",
|
|
2: "STRING"
|
|
});
|
|
function md(a) {
|
|
void 0 === a && (a = 0);
|
|
switch(a){
|
|
case 1:
|
|
return "selfie_segmentation_landscape.tflite";
|
|
default:
|
|
return "selfie_segmentation.tflite";
|
|
}
|
|
}
|
|
function nd(a) {
|
|
var b = this;
|
|
a = a || {};
|
|
this.h = new ed({
|
|
locateFile: a.locateFile,
|
|
files: function(c) {
|
|
return [
|
|
{
|
|
simd: !0,
|
|
url: "selfie_segmentation_solution_simd_wasm_bin.js"
|
|
},
|
|
{
|
|
simd: !1,
|
|
url: "selfie_segmentation_solution_wasm_bin.js"
|
|
},
|
|
{
|
|
data: !0,
|
|
url: md(c.modelSelection)
|
|
}
|
|
];
|
|
},
|
|
graph: {
|
|
url: "selfie_segmentation.binarypb"
|
|
},
|
|
listeners: [
|
|
{
|
|
wants: [
|
|
"segmentation_mask",
|
|
"image_transformed"
|
|
],
|
|
outs: {
|
|
image: {
|
|
type: "texture",
|
|
stream: "image_transformed"
|
|
},
|
|
segmentationMask: {
|
|
type: "texture",
|
|
stream: "segmentation_mask"
|
|
}
|
|
}
|
|
}
|
|
],
|
|
inputs: {
|
|
image: {
|
|
type: "video",
|
|
stream: "input_frames_gpu"
|
|
}
|
|
},
|
|
options: {
|
|
useCpuInference: {
|
|
type: 0,
|
|
graphOptionXref: {
|
|
calculatorType: "InferenceCalculator",
|
|
fieldName: "use_cpu_inference"
|
|
},
|
|
default: "object" !== typeof window || void 0 === window.navigator ? !1 : "iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend" in document
|
|
},
|
|
selfieMode: {
|
|
type: 0,
|
|
graphOptionXref: {
|
|
calculatorType: "GlScalerCalculator",
|
|
calculatorIndex: 1,
|
|
fieldName: "flip_horizontal"
|
|
}
|
|
},
|
|
modelSelection: {
|
|
type: 1,
|
|
graphOptionXref: {
|
|
calculatorType: "ConstantSidePacketCalculator",
|
|
calculatorName: "ConstantSidePacketCalculatorModelSelection",
|
|
fieldName: "int_value"
|
|
},
|
|
onChange: function(c) {
|
|
var d, e, g;
|
|
return E(function(f) {
|
|
if (1 == f.h) return d = md(c), e = "third_party/mediapipe/modules/selfie_segmentation/" + d, D(f, gd(b.h, d), 2);
|
|
g = f.i;
|
|
b.h.overrideFile(e, g);
|
|
return f.return(!0);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
x = nd.prototype;
|
|
x.close = function() {
|
|
this.h.close();
|
|
return Promise.resolve();
|
|
};
|
|
x.onResults = function(a) {
|
|
this.h.onResults(a);
|
|
};
|
|
x.initialize = function() {
|
|
var a = this;
|
|
return E(function(b) {
|
|
return D(b, a.h.initialize(), 0);
|
|
});
|
|
};
|
|
x.reset = function() {
|
|
this.h.reset();
|
|
};
|
|
x.send = function(a) {
|
|
var b = this;
|
|
return E(function(c) {
|
|
return D(c, b.h.send(a), 0);
|
|
});
|
|
};
|
|
x.setOptions = function(a) {
|
|
this.h.setOptions(a);
|
|
};
|
|
Aa("SelfieSegmentation", nd);
|
|
Aa("VERSION", "0.1.1675465747");
|
|
}).call(this);
|
|
|
|
},{}],"bzQr6":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // All exports from this package should be in base.
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
var _base = require("./base");
|
|
parcelHelpers.exportAll(_base, exports);
|
|
var _registerAllKernels = require("./register_all_kernels");
|
|
|
|
},{"./base":"eS7ei","./register_all_kernels":"89NZo","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eS7ei":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ /*
|
|
* base.ts contains all the exports from tfjs-backend-cpu
|
|
* without auto-kernel registration
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MathBackendCPU", ()=>(0, _backendCpu.MathBackendCPU));
|
|
parcelHelpers.export(exports, "version_cpu", ()=>(0, _version.version));
|
|
parcelHelpers.export(exports, "shared", ()=>_shared);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _backendCpu = require("./backend_cpu");
|
|
var _shared = require("./shared");
|
|
var _version = require("./version");
|
|
// Side effects for default initialization of MathBackendCPU
|
|
(0, _tfjsCore.registerBackend)("cpu", ()=>new (0, _backendCpu.MathBackendCPU)(), 1 /* priority */ );
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./backend_cpu":"argpD","./shared":"YbUp7","./version":"fow87","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"argpD":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "MathBackendCPU", ()=>MathBackendCPU);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("./cpu_util");
|
|
const whereImpl = (0, _tfjsCore.kernel_impls).whereImpl;
|
|
class MathBackendCPU extends (0, _tfjsCore.KernelBackend) {
|
|
nextDataId() {
|
|
return MathBackendCPU.nextDataId++;
|
|
}
|
|
constructor(){
|
|
super();
|
|
this.blockSize = 48;
|
|
this.firstUse = true;
|
|
this.data = new (0, _tfjsCore.DataStorage)(this, (0, _tfjsCore.engine)());
|
|
}
|
|
write(values, shape, dtype) {
|
|
if (this.firstUse) {
|
|
this.firstUse = false;
|
|
if ((0, _tfjsCore.env)().get("IS_NODE")) (0, _tfjsCore.backend_util).warn("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================");
|
|
}
|
|
const dataId = {
|
|
id: this.nextDataId()
|
|
};
|
|
this.data.set(dataId, {
|
|
values,
|
|
dtype,
|
|
refCount: 1
|
|
});
|
|
return dataId;
|
|
}
|
|
/**
|
|
* Create a data bucket in cpu backend.
|
|
* @param shape Shape of the `TensorInfo`.
|
|
* @param dtype DType of the `TensorInfo`.
|
|
* @param values The value of the `TensorInfo` stored as a flattened array.
|
|
*/ makeTensorInfo(shape, dtype, values) {
|
|
let outId;
|
|
if (dtype === "string" && values != null && values.length > 0 && (0, _tfjsCore.util).isString(values[0])) {
|
|
const encodedValues = values.map((d)=>(0, _tfjsCore.util).encodeString(d));
|
|
outId = this.write(encodedValues, shape, dtype);
|
|
} else outId = this.write(values, shape, dtype);
|
|
return {
|
|
dataId: outId,
|
|
shape,
|
|
dtype
|
|
};
|
|
}
|
|
/** Return refCount of a `TensorData`. */ refCount(dataId) {
|
|
if (this.data.has(dataId)) {
|
|
const tensorData = this.data.get(dataId);
|
|
return tensorData.refCount;
|
|
}
|
|
return 0;
|
|
}
|
|
/** Increase refCount of a `TensorData`. */ incRef(dataId) {
|
|
const tensorData = this.data.get(dataId);
|
|
tensorData.refCount++;
|
|
}
|
|
/** Decrease refCount of a `TensorData`. */ decRef(dataId) {
|
|
if (this.data.has(dataId)) {
|
|
const tensorData = this.data.get(dataId);
|
|
tensorData.refCount--;
|
|
}
|
|
}
|
|
move(dataId, values, shape, dtype, refCount) {
|
|
this.data.set(dataId, {
|
|
values,
|
|
dtype,
|
|
refCount
|
|
});
|
|
}
|
|
numDataIds() {
|
|
return this.data.numDataIds();
|
|
}
|
|
async read(dataId) {
|
|
return this.readSync(dataId);
|
|
}
|
|
readSync(dataId) {
|
|
const { dtype, complexTensorInfos } = this.data.get(dataId);
|
|
if (dtype === "complex64") {
|
|
const realValues = this.readSync(complexTensorInfos.real.dataId);
|
|
const imagValues = this.readSync(complexTensorInfos.imag.dataId);
|
|
return (0, _tfjsCore.backend_util).mergeRealAndImagArrays(realValues, imagValues);
|
|
}
|
|
return (0, _tfjsCore.util).convertBackendValuesAndArrayBuffer(this.data.get(dataId).values, dtype);
|
|
}
|
|
bufferSync(t) {
|
|
const data = this.readSync(t.dataId);
|
|
if (t.dtype === "string") try {
|
|
// Decode the bytes into string.
|
|
const strings = data.map((d)=>(0, _tfjsCore.util).decodeString(d));
|
|
return (0, _tfjsCore.buffer)(t.shape, t.dtype, strings);
|
|
} catch (_a) {
|
|
throw new Error("Failed to decode encoded string bytes into utf-8");
|
|
}
|
|
return (0, _tfjsCore.buffer)(t.shape, t.dtype, data);
|
|
}
|
|
makeOutput(values, shape, dtype) {
|
|
return (0, _tfjsCore.engine)().makeTensorFromTensorInfo(this.makeTensorInfo(shape, dtype, values), this);
|
|
}
|
|
/**
|
|
* Dispose the memory if the dataId has 0 refCount. Return true if the memory
|
|
* is released or memory is not managed in this backend, false if memory is
|
|
* not cleared.
|
|
* @param dataId
|
|
* @oaram force Optional, remove the data regardless of refCount
|
|
*/ disposeData(dataId, force = false) {
|
|
if (this.data.has(dataId)) {
|
|
this.data.get(dataId).refCount--;
|
|
if (!force && this.data.get(dataId).refCount > 0) return false;
|
|
const { complexTensorInfos } = this.data.get(dataId);
|
|
if (complexTensorInfos != null) {
|
|
this.disposeData(complexTensorInfos.real.dataId, true);
|
|
this.disposeData(complexTensorInfos.imag.dataId, true);
|
|
}
|
|
this.data.delete(dataId);
|
|
}
|
|
return true;
|
|
}
|
|
disposeIntermediateTensorInfo(tensorInfo) {
|
|
this.disposeData(tensorInfo.dataId);
|
|
}
|
|
async time(f) {
|
|
const start = (0, _tfjsCore.util).now();
|
|
f();
|
|
const kernelMs = (0, _tfjsCore.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."
|
|
]
|
|
};
|
|
}
|
|
where(condition) {
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
condition
|
|
], "where");
|
|
const condVals = this.readSync(condition.dataId);
|
|
return whereImpl(condition.shape, condVals);
|
|
}
|
|
dispose() {}
|
|
floatPrecision() {
|
|
return 32;
|
|
}
|
|
/** Returns the smallest representable number. */ epsilon() {
|
|
return super.epsilon();
|
|
}
|
|
}
|
|
MathBackendCPU.nextDataId = 0;
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fow87":[function(require,module,exports) {
|
|
/** @license See the LICENSE file. */ // This code is auto-generated, do not modify this file!
|
|
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "version", ()=>version);
|
|
const version = "4.21.0";
|
|
|
|
},{"@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"89NZo":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ // 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.
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fusedMatMul = require("./kernels/_FusedMatMul");
|
|
var _abs = require("./kernels/Abs");
|
|
var _acos = require("./kernels/Acos");
|
|
var _acosh = require("./kernels/Acosh");
|
|
var _add = require("./kernels/Add");
|
|
var _addN = require("./kernels/AddN");
|
|
var _all = require("./kernels/All");
|
|
var _any = require("./kernels/Any");
|
|
var _argMax = require("./kernels/ArgMax");
|
|
var _argMin = require("./kernels/ArgMin");
|
|
var _asin = require("./kernels/Asin");
|
|
var _asinh = require("./kernels/Asinh");
|
|
var _atan = require("./kernels/Atan");
|
|
var _atan2 = require("./kernels/Atan2");
|
|
var _atanh = require("./kernels/Atanh");
|
|
var _avgPool = require("./kernels/AvgPool");
|
|
var _avgPool3D = require("./kernels/AvgPool3D");
|
|
var _avgPool3DGrad = require("./kernels/AvgPool3DGrad");
|
|
var _avgPoolGrad = require("./kernels/AvgPoolGrad");
|
|
var _batchMatMul = require("./kernels/BatchMatMul");
|
|
var _batchNorm = require("./kernels/BatchNorm");
|
|
var _batchToSpaceND = require("./kernels/BatchToSpaceND");
|
|
var _bincount = require("./kernels/Bincount");
|
|
var _bitwiseAnd = require("./kernels/BitwiseAnd");
|
|
var _broadcastArgs = require("./kernels/BroadcastArgs");
|
|
var _cast = require("./kernels/Cast");
|
|
var _ceil = require("./kernels/Ceil");
|
|
var _clipByValue = require("./kernels/ClipByValue");
|
|
var _complex = require("./kernels/Complex");
|
|
var _complexAbs = require("./kernels/ComplexAbs");
|
|
var _concat = require("./kernels/Concat");
|
|
var _conv2D = require("./kernels/Conv2D");
|
|
var _conv2DBackpropFilter = require("./kernels/Conv2DBackpropFilter");
|
|
var _conv2DBackpropInput = require("./kernels/Conv2DBackpropInput");
|
|
var _conv3D = require("./kernels/Conv3D");
|
|
var _conv3DBackpropFilterV2 = require("./kernels/Conv3DBackpropFilterV2");
|
|
var _conv3DBackpropInputV2 = require("./kernels/Conv3DBackpropInputV2");
|
|
var _cos = require("./kernels/Cos");
|
|
var _cosh = require("./kernels/Cosh");
|
|
var _cropAndResize = require("./kernels/CropAndResize");
|
|
var _cumprod = require("./kernels/Cumprod");
|
|
var _cumsum = require("./kernels/Cumsum");
|
|
var _denseBincount = require("./kernels/DenseBincount");
|
|
var _depthToSpace = require("./kernels/DepthToSpace");
|
|
var _depthwiseConv2DNative = require("./kernels/DepthwiseConv2dNative");
|
|
var _depthwiseConv2DNativeBackpropFilter = require("./kernels/DepthwiseConv2dNativeBackpropFilter");
|
|
var _depthwiseConv2DNativeBackpropInput = require("./kernels/DepthwiseConv2dNativeBackpropInput");
|
|
var _diag = require("./kernels/Diag");
|
|
var _dilation2D = require("./kernels/Dilation2D");
|
|
var _dilation2DBackpropFilter = require("./kernels/Dilation2DBackpropFilter");
|
|
var _dilation2DBackpropInput = require("./kernels/Dilation2DBackpropInput");
|
|
var _draw = require("./kernels/Draw");
|
|
var _einsum = require("./kernels/Einsum");
|
|
var _elu = require("./kernels/Elu");
|
|
var _eluGrad = require("./kernels/EluGrad");
|
|
var _equal = require("./kernels/Equal");
|
|
var _erf = require("./kernels/Erf");
|
|
var _exp = require("./kernels/Exp");
|
|
var _expandDims = require("./kernels/ExpandDims");
|
|
var _expm1 = require("./kernels/Expm1");
|
|
var _fft = require("./kernels/FFT");
|
|
var _fill = require("./kernels/Fill");
|
|
var _flipLeftRight = require("./kernels/FlipLeftRight");
|
|
var _floor = require("./kernels/Floor");
|
|
var _floorDiv = require("./kernels/FloorDiv");
|
|
var _fusedConv2D = require("./kernels/FusedConv2D");
|
|
var _fusedDepthwiseConv2D = require("./kernels/FusedDepthwiseConv2D");
|
|
var _gatherNd = require("./kernels/GatherNd");
|
|
var _gatherV2 = require("./kernels/GatherV2");
|
|
var _greater = require("./kernels/Greater");
|
|
var _greaterEqual = require("./kernels/GreaterEqual");
|
|
var _identity = require("./kernels/Identity");
|
|
var _ifft = require("./kernels/IFFT");
|
|
var _imag = require("./kernels/Imag");
|
|
var _isFinite = require("./kernels/IsFinite");
|
|
var _isInf = require("./kernels/IsInf");
|
|
var _isNaN = require("./kernels/IsNaN");
|
|
var _leakyRelu = require("./kernels/LeakyRelu");
|
|
var _less = require("./kernels/Less");
|
|
var _lessEqual = require("./kernels/LessEqual");
|
|
var _linSpace = require("./kernels/LinSpace");
|
|
var _log = require("./kernels/Log");
|
|
var _log1P = require("./kernels/Log1p");
|
|
var _logicalAnd = require("./kernels/LogicalAnd");
|
|
var _logicalNot = require("./kernels/LogicalNot");
|
|
var _logicalOr = require("./kernels/LogicalOr");
|
|
var _lrn = require("./kernels/LRN");
|
|
var _lrngrad = require("./kernels/LRNGrad");
|
|
var _max = require("./kernels/Max");
|
|
var _maximum = require("./kernels/Maximum");
|
|
var _maxPool = require("./kernels/MaxPool");
|
|
var _maxPool3D = require("./kernels/MaxPool3D");
|
|
var _maxPool3DGrad = require("./kernels/MaxPool3DGrad");
|
|
var _maxPoolGrad = require("./kernels/MaxPoolGrad");
|
|
var _maxPoolWithArgmax = require("./kernels/MaxPoolWithArgmax");
|
|
var _mean = require("./kernels/Mean");
|
|
var _min = require("./kernels/Min");
|
|
var _minimum = require("./kernels/Minimum");
|
|
var _mirrorPad = require("./kernels/MirrorPad");
|
|
var _mod = require("./kernels/Mod");
|
|
var _multinomial = require("./kernels/Multinomial");
|
|
var _multiply = require("./kernels/Multiply");
|
|
var _neg = require("./kernels/Neg");
|
|
var _nonMaxSuppressionV3 = require("./kernels/NonMaxSuppressionV3");
|
|
var _nonMaxSuppressionV4 = require("./kernels/NonMaxSuppressionV4");
|
|
var _nonMaxSuppressionV5 = require("./kernels/NonMaxSuppressionV5");
|
|
var _notEqual = require("./kernels/NotEqual");
|
|
var _oneHot = require("./kernels/OneHot");
|
|
var _onesLike = require("./kernels/OnesLike");
|
|
var _pack = require("./kernels/Pack");
|
|
var _padV2 = require("./kernels/PadV2");
|
|
var _pow = require("./kernels/Pow");
|
|
var _prelu = require("./kernels/Prelu");
|
|
var _prod = require("./kernels/Prod");
|
|
var _raggedGather = require("./kernels/RaggedGather");
|
|
var _raggedRange = require("./kernels/RaggedRange");
|
|
var _raggedTensorToTensor = require("./kernels/RaggedTensorToTensor");
|
|
var _range = require("./kernels/Range");
|
|
var _real = require("./kernels/Real");
|
|
var _realDiv = require("./kernels/RealDiv");
|
|
var _reciprocal = require("./kernels/Reciprocal");
|
|
var _relu = require("./kernels/Relu");
|
|
var _relu6 = require("./kernels/Relu6");
|
|
var _reshape = require("./kernels/Reshape");
|
|
var _resizeBilinear = require("./kernels/ResizeBilinear");
|
|
var _resizeBilinearGrad = require("./kernels/ResizeBilinearGrad");
|
|
var _resizeNearestNeighbor = require("./kernels/ResizeNearestNeighbor");
|
|
var _resizeNearestNeighborGrad = require("./kernels/ResizeNearestNeighborGrad");
|
|
var _reverse = require("./kernels/Reverse");
|
|
var _rotateWithOffset = require("./kernels/RotateWithOffset");
|
|
var _round = require("./kernels/Round");
|
|
var _rsqrt = require("./kernels/Rsqrt");
|
|
var _scatterNd = require("./kernels/ScatterNd");
|
|
var _searchSorted = require("./kernels/SearchSorted");
|
|
var _select = require("./kernels/Select");
|
|
var _selu = require("./kernels/Selu");
|
|
var _sigmoid = require("./kernels/Sigmoid");
|
|
var _sign = require("./kernels/Sign");
|
|
var _sin = require("./kernels/Sin");
|
|
var _sinh = require("./kernels/Sinh");
|
|
var _slice = require("./kernels/Slice");
|
|
var _softmax = require("./kernels/Softmax");
|
|
var _softplus = require("./kernels/Softplus");
|
|
var _spaceToBatchND = require("./kernels/SpaceToBatchND");
|
|
var _sparseFillEmptyRows = require("./kernels/SparseFillEmptyRows");
|
|
var _sparseReshape = require("./kernels/SparseReshape");
|
|
var _sparseSegmentMean = require("./kernels/SparseSegmentMean");
|
|
var _sparseSegmentSum = require("./kernels/SparseSegmentSum");
|
|
var _sparseToDense = require("./kernels/SparseToDense");
|
|
var _splitV = require("./kernels/SplitV");
|
|
var _sqrt = require("./kernels/Sqrt");
|
|
var _square = require("./kernels/Square");
|
|
var _squaredDifference = require("./kernels/SquaredDifference");
|
|
var _staticRegexReplace = require("./kernels/StaticRegexReplace");
|
|
var _step = require("./kernels/Step");
|
|
var _stridedSlice = require("./kernels/StridedSlice");
|
|
var _stringNGrams = require("./kernels/StringNGrams");
|
|
var _stringSplit = require("./kernels/StringSplit");
|
|
var _stringToHashBucketFast = require("./kernels/StringToHashBucketFast");
|
|
var _sub = require("./kernels/Sub");
|
|
var _sum = require("./kernels/Sum");
|
|
var _tan = require("./kernels/Tan");
|
|
var _tanh = require("./kernels/Tanh");
|
|
var _tensorScatterUpdate = require("./kernels/TensorScatterUpdate");
|
|
var _tile = require("./kernels/Tile");
|
|
var _topK = require("./kernels/TopK");
|
|
var _transform = require("./kernels/Transform");
|
|
var _transpose = require("./kernels/Transpose");
|
|
var _unique = require("./kernels/Unique");
|
|
var _unpack = require("./kernels/Unpack");
|
|
var _unsortedSegmentSum = require("./kernels/UnsortedSegmentSum");
|
|
var _zerosLike = require("./kernels/ZerosLike");
|
|
// List all kernel configs here
|
|
const kernelConfigs = [
|
|
(0, _fusedMatMul._fusedMatMulConfig),
|
|
(0, _abs.absConfig),
|
|
(0, _acos.acosConfig),
|
|
(0, _acosh.acoshConfig),
|
|
(0, _add.addConfig),
|
|
(0, _addN.addNConfig),
|
|
(0, _all.allConfig),
|
|
(0, _any.anyConfig),
|
|
(0, _argMax.argMaxConfig),
|
|
(0, _argMin.argMinConfig),
|
|
(0, _asin.asinConfig),
|
|
(0, _asinh.asinhConfig),
|
|
(0, _atan.atanConfig),
|
|
(0, _atan2.atan2Config),
|
|
(0, _atanh.atanhConfig),
|
|
(0, _avgPool.avgPoolConfig),
|
|
(0, _avgPool3D.avgPool3DConfig),
|
|
(0, _avgPool3DGrad.avgPool3DGradConfig),
|
|
(0, _avgPoolGrad.avgPoolGradConfig),
|
|
(0, _batchMatMul.batchMatMulConfig),
|
|
(0, _batchNorm.batchNormConfig),
|
|
(0, _batchToSpaceND.batchToSpaceNDConfig),
|
|
(0, _bincount.bincountConfig),
|
|
(0, _bitwiseAnd.bitwiseAndConfig),
|
|
(0, _broadcastArgs.broadcastArgsConfig),
|
|
(0, _cast.castConfig),
|
|
(0, _ceil.ceilConfig),
|
|
(0, _clipByValue.clipByValueConfig),
|
|
(0, _complex.complexConfig),
|
|
(0, _complexAbs.complexAbsConfig),
|
|
(0, _concat.concatConfig),
|
|
(0, _conv2D.conv2DConfig),
|
|
(0, _conv2DBackpropFilter.conv2DBackpropFilterConfig),
|
|
(0, _conv2DBackpropInput.conv2DBackpropInputConfig),
|
|
(0, _conv3D.conv3DConfig),
|
|
(0, _conv3DBackpropFilterV2.conv3DBackpropFilterV2Config),
|
|
(0, _conv3DBackpropInputV2.conv3DBackpropInputV2Config),
|
|
(0, _cos.cosConfig),
|
|
(0, _cosh.coshConfig),
|
|
(0, _cropAndResize.cropAndResizeConfig),
|
|
(0, _cumprod.cumprodConfig),
|
|
(0, _cumsum.cumsumConfig),
|
|
(0, _denseBincount.denseBincountConfig),
|
|
(0, _depthToSpace.depthToSpaceConfig),
|
|
(0, _depthwiseConv2DNative.depthwiseConv2dNativeConfig),
|
|
(0, _depthwiseConv2DNativeBackpropFilter.depthwiseConv2dNativeBackpropFilterConfig),
|
|
(0, _depthwiseConv2DNativeBackpropInput.depthwiseConv2dNativeBackpropInputConfig),
|
|
(0, _diag.diagConfig),
|
|
(0, _dilation2D.dilation2DConfig),
|
|
(0, _dilation2DBackpropFilter.dilation2DBackpropFilterConfig),
|
|
(0, _dilation2DBackpropInput.dilation2DBackpropInputConfig),
|
|
(0, _draw.drawConfig),
|
|
(0, _einsum.einsumConfig),
|
|
(0, _elu.eluConfig),
|
|
(0, _eluGrad.eluGradConfig),
|
|
(0, _equal.equalConfig),
|
|
(0, _erf.erfConfig),
|
|
(0, _exp.expConfig),
|
|
(0, _expandDims.expandDimsConfig),
|
|
(0, _expm1.expm1Config),
|
|
(0, _fft.fftConfig),
|
|
(0, _fill.fillConfig),
|
|
(0, _flipLeftRight.flipLeftRightConfig),
|
|
(0, _floor.floorConfig),
|
|
(0, _floorDiv.floorDivConfig),
|
|
(0, _fusedConv2D.fusedConv2DConfig),
|
|
(0, _fusedDepthwiseConv2D.fusedDepthwiseConv2DConfig),
|
|
(0, _gatherNd.gatherNdConfig),
|
|
(0, _gatherV2.gatherV2Config),
|
|
(0, _greater.greaterConfig),
|
|
(0, _greaterEqual.greaterEqualConfig),
|
|
(0, _identity.identityConfig),
|
|
(0, _ifft.ifftConfig),
|
|
(0, _imag.imagConfig),
|
|
(0, _isFinite.isFiniteConfig),
|
|
(0, _isInf.isInfConfig),
|
|
(0, _isNaN.isNaNConfig),
|
|
(0, _leakyRelu.leakyReluConfig),
|
|
(0, _less.lessConfig),
|
|
(0, _lessEqual.lessEqualConfig),
|
|
(0, _linSpace.linSpaceConfig),
|
|
(0, _log.logConfig),
|
|
(0, _log1P.log1pConfig),
|
|
(0, _logicalAnd.logicalAndConfig),
|
|
(0, _logicalNot.logicalNotConfig),
|
|
(0, _logicalOr.logicalOrConfig),
|
|
(0, _lrn.LRNConfig),
|
|
(0, _lrngrad.LRNGradConfig),
|
|
(0, _max.maxConfig),
|
|
(0, _maximum.maximumConfig),
|
|
(0, _maxPool.maxPoolConfig),
|
|
(0, _maxPool3D.maxPool3DConfig),
|
|
(0, _maxPool3DGrad.maxPool3DGradConfig),
|
|
(0, _maxPoolGrad.maxPoolGradConfig),
|
|
(0, _maxPoolWithArgmax.maxPoolWithArgmaxConfig),
|
|
(0, _mean.meanConfig),
|
|
(0, _min.minConfig),
|
|
(0, _minimum.minimumConfig),
|
|
(0, _mirrorPad.mirrorPadConfig),
|
|
(0, _mod.modConfig),
|
|
(0, _multinomial.multinomialConfig),
|
|
(0, _multiply.multiplyConfig),
|
|
(0, _neg.negConfig),
|
|
(0, _nonMaxSuppressionV3.nonMaxSuppressionV3Config),
|
|
(0, _nonMaxSuppressionV4.nonMaxSuppressionV4Config),
|
|
(0, _nonMaxSuppressionV5.nonMaxSuppressionV5Config),
|
|
(0, _notEqual.notEqualConfig),
|
|
(0, _oneHot.oneHotConfig),
|
|
(0, _onesLike.onesLikeConfig),
|
|
(0, _pack.packConfig),
|
|
(0, _padV2.padV2Config),
|
|
(0, _pow.powConfig),
|
|
(0, _prelu.preluConfig),
|
|
(0, _prod.prodConfig),
|
|
(0, _raggedGather.raggedGatherConfig),
|
|
(0, _raggedRange.raggedRangeConfig),
|
|
(0, _raggedTensorToTensor.raggedTensorToTensorConfig),
|
|
(0, _range.rangeConfig),
|
|
(0, _real.realConfig),
|
|
(0, _realDiv.realDivConfig),
|
|
(0, _reciprocal.reciprocalConfig),
|
|
(0, _relu.reluConfig),
|
|
(0, _relu6.relu6Config),
|
|
(0, _reshape.reshapeConfig),
|
|
(0, _resizeBilinear.resizeBilinearConfig),
|
|
(0, _resizeBilinearGrad.resizeBilinearGradConfig),
|
|
(0, _resizeNearestNeighbor.resizeNearestNeighborConfig),
|
|
(0, _resizeNearestNeighborGrad.resizeNearestNeighborGradConfig),
|
|
(0, _reverse.reverseConfig),
|
|
(0, _rotateWithOffset.rotateWithOffsetConfig),
|
|
(0, _round.roundConfig),
|
|
(0, _rsqrt.rsqrtConfig),
|
|
(0, _scatterNd.scatterNdConfig),
|
|
(0, _searchSorted.searchSortedConfig),
|
|
(0, _select.selectConfig),
|
|
(0, _selu.seluConfig),
|
|
(0, _sigmoid.sigmoidConfig),
|
|
(0, _sign.signConfig),
|
|
(0, _sin.sinConfig),
|
|
(0, _sinh.sinhConfig),
|
|
(0, _slice.sliceConfig),
|
|
(0, _softmax.softmaxConfig),
|
|
(0, _softplus.softplusConfig),
|
|
(0, _spaceToBatchND.spaceToBatchNDConfig),
|
|
(0, _sparseFillEmptyRows.sparseFillEmptyRowsConfig),
|
|
(0, _sparseReshape.sparseReshapeConfig),
|
|
(0, _sparseSegmentMean.sparseSegmentMeanConfig),
|
|
(0, _sparseSegmentSum.sparseSegmentSumConfig),
|
|
(0, _sparseToDense.sparseToDenseConfig),
|
|
(0, _splitV.splitVConfig),
|
|
(0, _sqrt.sqrtConfig),
|
|
(0, _square.squareConfig),
|
|
(0, _squaredDifference.squaredDifferenceConfig),
|
|
(0, _staticRegexReplace.staticRegexReplaceConfig),
|
|
(0, _step.stepConfig),
|
|
(0, _stridedSlice.stridedSliceConfig),
|
|
(0, _stringNGrams.stringNGramsConfig),
|
|
(0, _stringSplit.stringSplitConfig),
|
|
(0, _stringToHashBucketFast.stringToHashBucketFastConfig),
|
|
(0, _sub.subConfig),
|
|
(0, _sum.sumConfig),
|
|
(0, _tan.tanConfig),
|
|
(0, _tanh.tanhConfig),
|
|
(0, _tensorScatterUpdate.tensorScatterUpdateConfig),
|
|
(0, _tile.tileConfig),
|
|
(0, _topK.topKConfig),
|
|
(0, _transform.transformConfig),
|
|
(0, _transpose.transposeConfig),
|
|
(0, _unique.uniqueConfig),
|
|
(0, _unpack.unpackConfig),
|
|
(0, _unsortedSegmentSum.unsortedSegmentSumConfig),
|
|
(0, _zerosLike.zerosLikeConfig)
|
|
];
|
|
for (const kernelConfig of kernelConfigs)(0, _tfjsCore.registerKernel)(kernelConfig);
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./kernels/_FusedMatMul":"2uXSk","./kernels/Abs":"2vVaE","./kernels/Acos":"2M2i0","./kernels/Acosh":"bYe62","./kernels/Add":"dippY","./kernels/AddN":"dmcG0","./kernels/All":"6pIZf","./kernels/Any":"5AV1Z","./kernels/ArgMax":"6P1xW","./kernels/ArgMin":"1cyKX","./kernels/Asin":"kRHNu","./kernels/Asinh":"bYcdN","./kernels/Atan":"a4d7R","./kernels/Atan2":"gUrSR","./kernels/Atanh":"dsEHm","./kernels/AvgPool":"8IIie","./kernels/AvgPool3D":"eu5qc","./kernels/AvgPool3DGrad":"iGPNS","./kernels/AvgPoolGrad":"kCJ3l","./kernels/BatchMatMul":"i8QFX","./kernels/BatchNorm":"a3KQN","./kernels/BatchToSpaceND":"7Jug2","./kernels/Bincount":"hE7iz","./kernels/BitwiseAnd":"lFHUr","./kernels/BroadcastArgs":"4GYx6","./kernels/Cast":"fAtIw","./kernels/Ceil":"dPS5d","./kernels/ClipByValue":"ck0lb","./kernels/Complex":"3DPmh","./kernels/ComplexAbs":"kThBM","./kernels/Concat":"iYEAT","./kernels/Conv2D":"4bj3X","./kernels/Conv2DBackpropFilter":"jHKF1","./kernels/Conv2DBackpropInput":"fBpei","./kernels/Conv3D":"iJ4dh","./kernels/Conv3DBackpropFilterV2":"g7cYG","./kernels/Conv3DBackpropInputV2":"l6kPr","./kernels/Cos":"hkcOn","./kernels/Cosh":"eg9u0","./kernels/CropAndResize":"8K1SK","./kernels/Cumprod":"bN0pp","./kernels/Cumsum":"8YA18","./kernels/DenseBincount":"cpFc0","./kernels/DepthToSpace":"l4MfW","./kernels/DepthwiseConv2dNative":"2iRpa","./kernels/DepthwiseConv2dNativeBackpropFilter":"j6FA2","./kernels/DepthwiseConv2dNativeBackpropInput":"4Kyp1","./kernels/Diag":"c5zdj","./kernels/Dilation2D":"8CglA","./kernels/Dilation2DBackpropFilter":"5GOEE","./kernels/Dilation2DBackpropInput":"fnjGq","./kernels/Draw":"9ZCFV","./kernels/Einsum":"lXbVv","./kernels/Elu":"7XTZG","./kernels/EluGrad":"cZudI","./kernels/Equal":"jK2O7","./kernels/Erf":"g7iiK","./kernels/Exp":"6eexr","./kernels/ExpandDims":"4z77l","./kernels/Expm1":"pXtet","./kernels/FFT":"7gqPz","./kernels/Fill":"4BMgR","./kernels/FlipLeftRight":"8d8ZF","./kernels/Floor":"ftFzk","./kernels/FloorDiv":"kMZnS","./kernels/FusedConv2D":"1OWT7","./kernels/FusedDepthwiseConv2D":"5SkmJ","./kernels/GatherNd":"6Owm3","./kernels/GatherV2":"dUokB","./kernels/Greater":"94zPb","./kernels/GreaterEqual":"a9aqR","./kernels/Identity":"btREJ","./kernels/IFFT":"hHvJu","./kernels/Imag":"af3Tx","./kernels/IsFinite":"a8CWT","./kernels/IsInf":"342Gs","./kernels/IsNaN":"gKXUy","./kernels/LeakyRelu":"hDqHI","./kernels/Less":"anwWy","./kernels/LessEqual":"nFlBF","./kernels/LinSpace":"3aMpD","./kernels/Log":"dNlq0","./kernels/Log1p":"bNfse","./kernels/LogicalAnd":"9q52j","./kernels/LogicalNot":"929wA","./kernels/LogicalOr":"4bpjj","./kernels/LRN":"1ZDWc","./kernels/LRNGrad":"01nUa","./kernels/Max":"ceCEC","./kernels/Maximum":"73P1X","./kernels/MaxPool":"2HK6O","./kernels/MaxPool3D":"guFsS","./kernels/MaxPool3DGrad":"bsOhi","./kernels/MaxPoolGrad":"esvnZ","./kernels/MaxPoolWithArgmax":"aBn34","./kernels/Mean":"hu1l4","./kernels/Min":"h3WES","./kernels/Minimum":"2gO4x","./kernels/MirrorPad":"1HbpJ","./kernels/Mod":"iD4b6","./kernels/Multinomial":"dy4Sw","./kernels/Multiply":"FrRi2","./kernels/Neg":"4sfM4","./kernels/NonMaxSuppressionV3":"cU4dv","./kernels/NonMaxSuppressionV4":"chYiL","./kernels/NonMaxSuppressionV5":"bVnt1","./kernels/NotEqual":"i62sj","./kernels/OneHot":"9Evwj","./kernels/OnesLike":"kWIOw","./kernels/Pack":"3NDYm","./kernels/PadV2":"dssNb","./kernels/Pow":"jx4g8","./kernels/Prelu":"c057T","./kernels/Prod":"8NwGT","./kernels/RaggedGather":"4jEHO","./kernels/RaggedRange":"kFVpX","./kernels/RaggedTensorToTensor":"bJlTR","./kernels/Range":"1Dov9","./kernels/Real":"eZ7aJ","./kernels/RealDiv":"9Ly75","./kernels/Reciprocal":"3BhEV","./kernels/Relu":"iWdDO","./kernels/Relu6":"C9OA6","./kernels/Reshape":"9350i","./kernels/ResizeBilinear":"kU0RB","./kernels/ResizeBilinearGrad":"76Mq3","./kernels/ResizeNearestNeighbor":"5c1lG","./kernels/ResizeNearestNeighborGrad":"4hhu6","./kernels/Reverse":"ff3xk","./kernels/RotateWithOffset":"d9nWG","./kernels/Round":"gnp2v","./kernels/Rsqrt":"gcVCI","./kernels/ScatterNd":"bb9Cv","./kernels/SearchSorted":"f7WfM","./kernels/Select":"lDXuK","./kernels/Selu":"cJWbo","./kernels/Sigmoid":"1a9v3","./kernels/Sign":"erXNP","./kernels/Sin":"c9it7","./kernels/Sinh":"9tr3d","./kernels/Slice":"9L9GN","./kernels/Softmax":"1UnfO","./kernels/Softplus":"bojBS","./kernels/SpaceToBatchND":"cO9CD","./kernels/SparseFillEmptyRows":"cLZdR","./kernels/SparseReshape":"bVjgS","./kernels/SparseSegmentMean":"7zRqG","./kernels/SparseSegmentSum":"dMeLQ","./kernels/SparseToDense":"kfHsN","./kernels/SplitV":"j2Sbu","./kernels/Sqrt":"cnnoj","./kernels/Square":"jjLIw","./kernels/SquaredDifference":"77Ql7","./kernels/StaticRegexReplace":"9G2f2","./kernels/Step":"2cqHx","./kernels/StridedSlice":"l76iO","./kernels/StringNGrams":"7Beq9","./kernels/StringSplit":"6TsmC","./kernels/StringToHashBucketFast":"irRRx","./kernels/Sub":"4DByI","./kernels/Sum":"6gbbV","./kernels/Tan":"aMIl2","./kernels/Tanh":"fdqiG","./kernels/TensorScatterUpdate":"jFIwa","./kernels/Tile":"cYsKW","./kernels/TopK":"9RDRk","./kernels/Transform":"hKZ0R","./kernels/Transpose":"61ywv","./kernels/Unique":"9nca3","./kernels/Unpack":"iIwqM","./kernels/UnsortedSegmentSum":"eWcTc","./kernels/ZerosLike":"hfVJr"}],"2uXSk":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "_fusedMatMul", ()=>_fusedMatMul);
|
|
parcelHelpers.export(exports, "_fusedMatMulConfig", ()=>_fusedMatMulConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fusedUtils = require("../utils/fused_utils");
|
|
var _add = require("./Add");
|
|
var _batchMatMul = require("./BatchMatMul");
|
|
function _fusedMatMul(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { a, b, bias, preluActivationWeights } = inputs;
|
|
const { transposeA, transposeB, activation, leakyreluAlpha } = attrs;
|
|
let current;
|
|
let addRes;
|
|
let activationRes;
|
|
const intermediates = [];
|
|
const matMulRes = (0, _batchMatMul.batchMatMul)({
|
|
inputs: {
|
|
a,
|
|
b
|
|
},
|
|
attrs: {
|
|
transposeA,
|
|
transposeB
|
|
},
|
|
backend
|
|
});
|
|
current = matMulRes;
|
|
if (bias) {
|
|
addRes = (0, _add.add)({
|
|
inputs: {
|
|
a: current,
|
|
b: bias
|
|
},
|
|
backend
|
|
});
|
|
intermediates.push(current);
|
|
current = addRes;
|
|
}
|
|
if (activation) {
|
|
activationRes = (0, _fusedUtils.applyActivation)(backend, current, activation, preluActivationWeights, leakyreluAlpha);
|
|
intermediates.push(current);
|
|
current = activationRes;
|
|
}
|
|
for (const i of intermediates)backend.disposeIntermediateTensorInfo(i);
|
|
return current;
|
|
}
|
|
const _fusedMatMulConfig = {
|
|
kernelName: (0, _tfjsCore._FusedMatMul),
|
|
backendName: "cpu",
|
|
kernelFunc: _fusedMatMul
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/fused_utils":"6DUEF","./Add":"dippY","./BatchMatMul":"i8QFX","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6DUEF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "applyActivation", ()=>applyActivation);
|
|
var _elu = require("../kernels/Elu");
|
|
var _identity = require("../kernels/Identity");
|
|
var _leakyRelu = require("../kernels/LeakyRelu");
|
|
var _prelu = require("../kernels/Prelu");
|
|
var _relu = require("../kernels/Relu");
|
|
var _relu6 = require("../kernels/Relu6");
|
|
var _sigmoid = require("../kernels/Sigmoid");
|
|
function applyActivation(backend, x, activation, preluActivationWeights, leakyreluAlpha) {
|
|
if (activation === "linear") return (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
else if (activation === "relu") return (0, _relu.relu)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
else if (activation === "elu") return (0, _elu.elu)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
else if (activation === "relu6") return (0, _relu6.relu6)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
else if (activation === "prelu") return (0, _prelu.prelu)({
|
|
inputs: {
|
|
x,
|
|
alpha: preluActivationWeights
|
|
},
|
|
backend
|
|
});
|
|
else if (activation === "leakyrelu") return (0, _leakyRelu.leakyRelu)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
alpha: leakyreluAlpha
|
|
}
|
|
});
|
|
else if (activation === "sigmoid") return (0, _sigmoid.sigmoid)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
throw new Error(`Activation ${activation} has not been implemented for the CPU backend.`);
|
|
}
|
|
|
|
},{"../kernels/Elu":"7XTZG","../kernels/Identity":"btREJ","../kernels/LeakyRelu":"hDqHI","../kernels/Prelu":"c057T","../kernels/Relu":"iWdDO","../kernels/Relu6":"C9OA6","../kernels/Sigmoid":"1a9v3","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7XTZG":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "elu", ()=>elu);
|
|
parcelHelpers.export(exports, "eluConfig", ()=>eluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const elu = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Elu), (xi)=>xi >= 0 ? xi : Math.exp(xi) - 1);
|
|
const eluConfig = {
|
|
kernelName: (0, _tfjsCore.Elu),
|
|
backendName: "cpu",
|
|
kernelFunc: elu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hDqHI":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "leakyRelu", ()=>leakyRelu);
|
|
parcelHelpers.export(exports, "leakyReluConfig", ()=>leakyReluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function leakyRelu(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { alpha } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x
|
|
], "leakyRelu");
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const outVals = (0, _tfjsCore.util).getTypedArrayFromDType("float32", xSize);
|
|
for(let i = 0; i < xVals.length; i++)outVals[i] = xVals[i] < 0 ? alpha * xVals[i] : xVals[i];
|
|
return backend.makeTensorInfo(x.shape, "float32", outVals);
|
|
}
|
|
const leakyReluConfig = {
|
|
kernelName: (0, _tfjsCore.LeakyRelu),
|
|
backendName: "cpu",
|
|
kernelFunc: leakyRelu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c057T":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "prelu", ()=>prelu);
|
|
parcelHelpers.export(exports, "preluConfig", ()=>preluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
const preluImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((xValue, aValue)=>xValue < 0 ? aValue * xValue : xValue);
|
|
function prelu(args) {
|
|
const { inputs, backend } = args;
|
|
const { x, alpha } = inputs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
alpha
|
|
], "prelu");
|
|
const aVals = backend.data.get(x.dataId).values;
|
|
const bVals = backend.data.get(alpha.dataId).values;
|
|
const [resultData, resultShape] = preluImpl(x.shape, alpha.shape, aVals, bVals, "float32");
|
|
return backend.makeTensorInfo(resultShape, "float32", resultData);
|
|
}
|
|
const preluConfig = {
|
|
kernelName: (0, _tfjsCore.Prelu),
|
|
backendName: "cpu",
|
|
kernelFunc: prelu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../utils/binary_impl":"7WPlP","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iWdDO":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "relu", ()=>relu);
|
|
parcelHelpers.export(exports, "reluConfig", ()=>reluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const relu = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Relu), (xi)=>Math.max(0, xi));
|
|
const reluConfig = {
|
|
kernelName: (0, _tfjsCore.Relu),
|
|
backendName: "cpu",
|
|
kernelFunc: relu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"C9OA6":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "relu6", ()=>relu6);
|
|
parcelHelpers.export(exports, "relu6Config", ()=>relu6Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const relu6 = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Relu6), (xi)=>Math.min(Math.max(0, xi), 6));
|
|
const relu6Config = {
|
|
kernelName: (0, _tfjsCore.Relu6),
|
|
backendName: "cpu",
|
|
kernelFunc: relu6
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"i8QFX":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchMatMul", ()=>batchMatMul);
|
|
parcelHelpers.export(exports, "batchMatMulConfig", ()=>batchMatMulConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _reshape = require("./Reshape");
|
|
function batchMatMul(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { a, b } = inputs;
|
|
const { transposeA, transposeB } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
a,
|
|
b
|
|
], "matMul");
|
|
const aRank = a.shape.length;
|
|
const bRank = b.shape.length;
|
|
const innerShapeA = transposeA ? a.shape[aRank - 2] : a.shape[aRank - 1];
|
|
const innerShapeB = transposeB ? b.shape[bRank - 1] : b.shape[bRank - 2];
|
|
const outerShapeA = transposeA ? a.shape[aRank - 1] : a.shape[aRank - 2];
|
|
const outerShapeB = transposeB ? b.shape[bRank - 2] : b.shape[bRank - 1];
|
|
const outerDimsA = a.shape.slice(0, -2);
|
|
const outerDimsB = b.shape.slice(0, -2);
|
|
const batchDimA = (0, _tfjsCore.util).sizeFromShape(outerDimsA);
|
|
const batchDimB = (0, _tfjsCore.util).sizeFromShape(outerDimsB);
|
|
const outShapeOuterDims = (0, _tfjsCore.broadcast_util).assertAndGetBroadcastShape(a.shape.slice(0, -2), b.shape.slice(0, -2));
|
|
const outShape = outShapeOuterDims.concat([
|
|
outerShapeA,
|
|
outerShapeB
|
|
]);
|
|
(0, _tfjsCore.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 a3dShape = transposeA ? [
|
|
batchDimA,
|
|
innerShapeA,
|
|
outerShapeA
|
|
] : [
|
|
batchDimA,
|
|
outerShapeA,
|
|
innerShapeA
|
|
];
|
|
const b3dShape = transposeB ? [
|
|
batchDimB,
|
|
outerShapeB,
|
|
innerShapeB
|
|
] : [
|
|
batchDimB,
|
|
innerShapeB,
|
|
outerShapeB
|
|
];
|
|
// The rest of the implementation is designed to operate on rank-3 tensors
|
|
const a3d = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: a
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: a3dShape
|
|
}
|
|
});
|
|
const b3d = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: b
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: b3dShape
|
|
}
|
|
});
|
|
const sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];
|
|
const leftDim = transposeA ? a3d.shape[2] : a3d.shape[1];
|
|
const rightDim = transposeB ? b3d.shape[1] : b3d.shape[2];
|
|
const batchDim = Math.max(batchDimA, batchDimB);
|
|
const a3dValues = backend.data.get(a3d.dataId).values;
|
|
const b3dValues = backend.data.get(b3d.dataId).values;
|
|
const a3dStrides = (0, _tfjsCore.util).computeStrides(a3d.shape);
|
|
const b3dStrides = (0, _tfjsCore.util).computeStrides(b3d.shape);
|
|
const [aBatch, aOuterStep, aInnerStep] = transposeA ? [
|
|
a3dStrides[0],
|
|
1,
|
|
a3dStrides[1]
|
|
] : [
|
|
a3dStrides[0],
|
|
a3dStrides[1],
|
|
1
|
|
];
|
|
const [bInnerStep, bOuterStep, bBatch] = transposeB ? [
|
|
1,
|
|
b3dStrides[1],
|
|
b3dStrides[0]
|
|
] : [
|
|
b3dStrides[1],
|
|
1,
|
|
b3dStrides[0]
|
|
];
|
|
const size = leftDim * rightDim;
|
|
const result = (0, _tfjsCore.buffer)([
|
|
batchDim,
|
|
leftDim,
|
|
rightDim
|
|
], a3d.dtype);
|
|
const resVals = result.values;
|
|
const blockSize = backend.blockSize;
|
|
for(let bi = 0; bi < batchDim; bi++){
|
|
const batchIndexA = bi % batchDimA;
|
|
const batchIndexB = bi % batchDimB;
|
|
for(let i0 = 0; i0 < leftDim; i0 += blockSize){
|
|
// for when blockSize doesn't evenly divide the input
|
|
const iBlock = Math.min(i0 + blockSize, leftDim);
|
|
for(let j0 = 0; j0 < rightDim; j0 += blockSize){
|
|
const jBlock = Math.min(j0 + blockSize, rightDim);
|
|
for(let k0 = 0; k0 < sharedDim; k0 += blockSize){
|
|
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++){
|
|
const aVal = // tslint:disable-next-line: max-line-length
|
|
a3dValues[batchIndexA * aBatch + i * aOuterStep + k * aInnerStep];
|
|
const bVal = // tslint:disable-next-line: max-line-length
|
|
b3dValues[k * bInnerStep + j * bOuterStep + batchIndexB * bBatch];
|
|
sum += aVal * bVal;
|
|
}
|
|
resVals[bi * size + (i * rightDim + j)] += sum;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
backend.disposeIntermediateTensorInfo(a3d);
|
|
backend.disposeIntermediateTensorInfo(b3d);
|
|
// set correct shape on output.
|
|
return backend.makeTensorInfo(outShape, result.dtype, result.values);
|
|
}
|
|
const batchMatMulConfig = {
|
|
kernelName: (0, _tfjsCore.BatchMatMul),
|
|
backendName: "cpu",
|
|
kernelFunc: batchMatMul
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Reshape":"9350i","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9350i":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reshape", ()=>reshape);
|
|
parcelHelpers.export(exports, "reshapeConfig", ()=>reshapeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function reshape(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { shape } = attrs;
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const $shape = (0, _tfjsCore.util).inferFromImplicitShape(shape, xSize);
|
|
const $xSize = (0, _tfjsCore.util).sizeFromShape($shape);
|
|
(0, _tfjsCore.util).assert(xSize === $xSize, ()=>`The new shape (${$shape}) has ${$xSize} elements and the old ` + `shape (${x.shape}) has ${xSize} elements. The new shape and old ` + `shape must have the same number of elements.`);
|
|
backend.incRef(x.dataId);
|
|
const xData = backend.data.get(x.dataId);
|
|
if (xData.complexTensorInfos != null) {
|
|
const real = xData.complexTensorInfos.real;
|
|
const imag = xData.complexTensorInfos.imag;
|
|
real.shape = $shape;
|
|
imag.shape = $shape;
|
|
}
|
|
return {
|
|
dataId: x.dataId,
|
|
shape: $shape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
const reshapeConfig = {
|
|
kernelName: (0, _tfjsCore.Reshape),
|
|
backendName: "cpu",
|
|
kernelFunc: reshape
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2M2i0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "acos", ()=>acos);
|
|
parcelHelpers.export(exports, "acosConfig", ()=>acosConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const acos = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Acos), (xi)=>Math.acos(xi));
|
|
const acosConfig = {
|
|
kernelName: (0, _tfjsCore.Acos),
|
|
backendName: "cpu",
|
|
kernelFunc: acos
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bYe62":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "acosh", ()=>acosh);
|
|
parcelHelpers.export(exports, "acoshConfig", ()=>acoshConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const acosh = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Acosh), (xi)=>Math.acosh(xi));
|
|
const acoshConfig = {
|
|
kernelName: (0, _tfjsCore.Acosh),
|
|
backendName: "cpu",
|
|
kernelFunc: acosh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dmcG0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "addN", ()=>addN);
|
|
parcelHelpers.export(exports, "addNConfig", ()=>addNConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function addN(args) {
|
|
const { inputs, backend } = args;
|
|
const tensors = inputs;
|
|
(0, _cpuUtil.assertNotComplex)(inputs, "addN");
|
|
const vals = tensors.map((t)=>backend.data.get(t.dataId).values);
|
|
const outBuf = (0, _tfjsCore.buffer)(tensors[0].shape, tensors[0].dtype);
|
|
const outVals = outBuf.values;
|
|
for(let i = 0; i < tensors.length; i++){
|
|
const currVals = vals[i];
|
|
for(let j = 0; j < outVals.length; j++)outVals[j] += currVals[j];
|
|
}
|
|
return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const addNConfig = {
|
|
kernelName: (0, _tfjsCore.AddN),
|
|
backendName: "cpu",
|
|
kernelFunc: addN
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6pIZf":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "all", ()=>all);
|
|
parcelHelpers.export(exports, "allConfig", ()=>allConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function all(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "all");
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, x.shape.length);
|
|
let $x = x;
|
|
if (permutedAxes != null) {
|
|
$x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, x.shape.length);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("all", axes, $x.shape.length);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes($x.shape, axes);
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const vals = (0, _tfjsCore.util).makeZerosTypedArray((0, _tfjsCore.util).sizeFromShape(outShape), $x.dtype);
|
|
const aVals = backend.data.get($x.dataId).values;
|
|
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;
|
|
}
|
|
if (permutedAxes != null) backend.disposeIntermediateTensorInfo($x);
|
|
const result = backend.makeTensorInfo(outShape, $x.dtype, vals);
|
|
if (keepDims) {
|
|
const expandedShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(outShape, origAxes);
|
|
const reshapedResult = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: expandedShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
return reshapedResult;
|
|
}
|
|
return result;
|
|
}
|
|
const allConfig = {
|
|
kernelName: (0, _tfjsCore.All),
|
|
backendName: "cpu",
|
|
kernelFunc: all
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Reshape":"9350i","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5AV1Z":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "any", ()=>any);
|
|
parcelHelpers.export(exports, "anyConfig", ()=>anyConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function any(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "any");
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, x.shape.length);
|
|
let $x = x;
|
|
if (permutedAxes != null) {
|
|
$x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, x.shape.length);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("any", axes, $x.shape.length);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes($x.shape, axes);
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const vals = (0, _tfjsCore.util).makeZerosTypedArray((0, _tfjsCore.util).sizeFromShape(outShape), $x.dtype);
|
|
const aVals = backend.data.get($x.dataId).values;
|
|
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;
|
|
}
|
|
if (permutedAxes != null) backend.disposeIntermediateTensorInfo($x);
|
|
const result = backend.makeTensorInfo(outShape, $x.dtype, vals);
|
|
if (keepDims) {
|
|
const expandedShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(outShape, origAxes);
|
|
const reshapedResult = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: expandedShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
return reshapedResult;
|
|
}
|
|
return result;
|
|
}
|
|
const anyConfig = {
|
|
kernelName: (0, _tfjsCore.Any),
|
|
backendName: "cpu",
|
|
kernelFunc: any
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Reshape":"9350i","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6P1xW":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "argMax", ()=>argMax);
|
|
parcelHelpers.export(exports, "argMaxConfig", ()=>argMaxConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _transpose = require("./Transpose");
|
|
function argMax(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "argMax");
|
|
let axes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, x.shape.length);
|
|
let $x = x;
|
|
const intermediateTensorInfos = [];
|
|
if (permutedAxes != null) {
|
|
$x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
intermediateTensorInfos.push($x);
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, $x.shape.length);
|
|
}
|
|
axes = [
|
|
axes[0]
|
|
];
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("argMax", axes, $x.shape.length);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes($x.shape, axes);
|
|
const outSize = (0, _tfjsCore.util).sizeFromShape(outShape);
|
|
const vals = (0, _tfjsCore.util).makeZerosTypedArray(outSize, "int32");
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const aVals = backend.data.get($x.dataId).values;
|
|
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;
|
|
}
|
|
intermediateTensorInfos.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return backend.makeTensorInfo(outShape, "int32", vals);
|
|
}
|
|
const argMaxConfig = {
|
|
kernelName: (0, _tfjsCore.ArgMax),
|
|
backendName: "cpu",
|
|
kernelFunc: argMax
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1cyKX":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "argMin", ()=>argMin);
|
|
parcelHelpers.export(exports, "argMinConfig", ()=>argMinConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _transpose = require("./Transpose");
|
|
function argMin(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "argMin");
|
|
let axes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, x.shape.length);
|
|
let $x = x;
|
|
const intermediateTensorInfos = [];
|
|
if (permutedAxes != null) {
|
|
$x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
intermediateTensorInfos.push($x);
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, $x.shape.length);
|
|
}
|
|
axes = [
|
|
axes[0]
|
|
];
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("argMin", axes, $x.shape.length);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes($x.shape, axes);
|
|
const outSize = (0, _tfjsCore.util).sizeFromShape(outShape);
|
|
const vals = (0, _tfjsCore.util).makeZerosTypedArray(outSize, "int32");
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const aVals = backend.data.get($x.dataId).values;
|
|
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;
|
|
}
|
|
intermediateTensorInfos.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return backend.makeTensorInfo(outShape, "int32", vals);
|
|
}
|
|
const argMinConfig = {
|
|
kernelName: (0, _tfjsCore.ArgMin),
|
|
backendName: "cpu",
|
|
kernelFunc: argMin
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kRHNu":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "asin", ()=>asin);
|
|
parcelHelpers.export(exports, "asinConfig", ()=>asinConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const asin = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Asin), (xi)=>Math.asin(xi));
|
|
const asinConfig = {
|
|
kernelName: (0, _tfjsCore.Asin),
|
|
backendName: "cpu",
|
|
kernelFunc: asin
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bYcdN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "asinh", ()=>asinh);
|
|
parcelHelpers.export(exports, "asinhConfig", ()=>asinhConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const asinh = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Asinh), (xi)=>Math.asinh(xi));
|
|
const asinhConfig = {
|
|
kernelName: (0, _tfjsCore.Asinh),
|
|
backendName: "cpu",
|
|
kernelFunc: asinh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a4d7R":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atan", ()=>atan);
|
|
parcelHelpers.export(exports, "atanConfig", ()=>atanConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const atan = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Atan), (xi)=>Math.atan(xi));
|
|
const atanConfig = {
|
|
kernelName: (0, _tfjsCore.Atan),
|
|
backendName: "cpu",
|
|
kernelFunc: atan
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gUrSR":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atan2Impl", ()=>atan2Impl);
|
|
parcelHelpers.export(exports, "atan2", ()=>atan2);
|
|
parcelHelpers.export(exports, "atan2Config", ()=>atan2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const atan2Impl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((aValue, bValue)=>Math.atan2(aValue, bValue));
|
|
const atan2 = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Atan2), atan2Impl);
|
|
const atan2Config = {
|
|
kernelName: (0, _tfjsCore.Atan2),
|
|
backendName: "cpu",
|
|
kernelFunc: atan2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dsEHm":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "atanh", ()=>atanh);
|
|
parcelHelpers.export(exports, "atanhConfig", ()=>atanhConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const atanh = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Atanh), (xi)=>Math.atanh(xi));
|
|
const atanhConfig = {
|
|
kernelName: (0, _tfjsCore.Atanh),
|
|
backendName: "cpu",
|
|
kernelFunc: atanh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8IIie":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPool", ()=>avgPool);
|
|
parcelHelpers.export(exports, "avgPoolConfig", ()=>avgPoolConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _poolUtils = require("../utils/pool_utils");
|
|
var _identity = require("./Identity");
|
|
function avgPool(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "avgPool");
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
const dilations = 1;
|
|
(0, _tfjsCore.util).assert((0, _tfjsCore.backend_util).eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in avgPool: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
|
|
let res;
|
|
if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 && (0, _tfjsCore.util).arraysEqual(convInfo.inShape, convInfo.outShape)) res = (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
else {
|
|
const xValues = backend.data.get(x.dataId).values;
|
|
const strides = (0, _tfjsCore.util).computeStrides(x.shape);
|
|
const buffer = (0, _poolUtils.pool)(xValues, x.shape, x.dtype, strides, convInfo, "avg");
|
|
res = backend.makeTensorInfo(convInfo.outShape, x.dtype, buffer.values);
|
|
}
|
|
return res;
|
|
}
|
|
const avgPoolConfig = {
|
|
kernelName: (0, _tfjsCore.AvgPool),
|
|
backendName: "cpu",
|
|
kernelFunc: avgPool
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../utils/pool_utils":"fzyhw","./Identity":"btREJ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fzyhw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pool", ()=>pool);
|
|
parcelHelpers.export(exports, "maxPoolPositions", ()=>maxPoolPositions);
|
|
parcelHelpers.export(exports, "pool3d", ()=>pool3d);
|
|
parcelHelpers.export(exports, "maxPool3dPositions", ()=>maxPool3dPositions);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
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 = (0, _tfjsCore.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 = (0, _tfjsCore.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 = (0, _tfjsCore.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;
|
|
// For some reason, disable-next-line is not working
|
|
// TODO(mattsoulanille): Remove this when switching to TS5.
|
|
/* tslint:disable: no-unnecessary-type-assertion */ 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;
|
|
}
|
|
function pool3d(xValues, xShape, dtype, strides, convInfo, poolType) {
|
|
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 output = (0, _tfjsCore.buffer)(convInfo.outShape, 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 * 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 * strides[1];
|
|
for(let xRow = xRowMin; xRow < xRowMax; xRow += dilationHeight){
|
|
const xRowOffset = xDepthOffset + xRow * strides[2];
|
|
for(let xCol = xColMin; xCol < xColMax; xCol += dilationWidth){
|
|
const xColOffset = xRowOffset + xCol * 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 / Math.max(count, 1) : minMaxValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return output;
|
|
}
|
|
function maxPool3dPositions(xBuf, convInfo) {
|
|
const maxPositions = (0, _tfjsCore.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;
|
|
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;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eu5qc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPool3D", ()=>avgPool3D);
|
|
parcelHelpers.export(exports, "avgPool3DConfig", ()=>avgPool3DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _poolUtils = require("../utils/pool_utils");
|
|
function avgPool3D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { filterSize, strides, pad, dimRoundingMode, dataFormat } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "avgPool3d");
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool3DInfo(x.shape, filterSize, strides, 1 /* dilations */ , pad, dimRoundingMode, dataFormat);
|
|
const xValues = backend.data.get(x.dataId).values;
|
|
const outBuf = (0, _poolUtils.pool3d)(xValues, x.shape, x.dtype, (0, _tfjsCore.util).computeStrides(x.shape), convInfo, "avg");
|
|
return backend.makeTensorInfo(outBuf.shape, "float32", outBuf.values);
|
|
}
|
|
const avgPool3DConfig = {
|
|
kernelName: (0, _tfjsCore.AvgPool3D),
|
|
backendName: "cpu",
|
|
kernelFunc: avgPool3D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../utils/pool_utils":"fzyhw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iGPNS":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPool3DGrad", ()=>avgPool3DGrad);
|
|
parcelHelpers.export(exports, "avgPool3DGradConfig", ()=>avgPool3DGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function avgPool3DGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, input } = inputs;
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy,
|
|
input
|
|
], "avgPool3DGrad");
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool3DInfo(input.shape, filterSize, strides, 1 /* dilations */ , pad, dimRoundingMode);
|
|
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 = (0, _tfjsCore.buffer)(input.shape, "float32");
|
|
const avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);
|
|
const dyBuf = backend.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 backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
|
|
}
|
|
const avgPool3DGradConfig = {
|
|
kernelName: (0, _tfjsCore.AvgPool3DGrad),
|
|
backendName: "cpu",
|
|
kernelFunc: avgPool3DGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kCJ3l":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "avgPoolGrad", ()=>avgPoolGrad);
|
|
parcelHelpers.export(exports, "avgPoolGradConfig", ()=>avgPoolGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function avgPoolGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, input } = inputs;
|
|
const x = input;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy,
|
|
input
|
|
], "avgPoolGrad");
|
|
const { filterSize, strides, pad } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, 1 /* dilations */ , pad);
|
|
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 = (0, _tfjsCore.buffer)(x.shape, "float32");
|
|
const avgMultiplier = 1 / (filterHeight * filterWidth);
|
|
const dyData = backend.data.get(dy.dataId).values;
|
|
const dyBuf = (0, _tfjsCore.buffer)(dy.shape, "float32", dyData);
|
|
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 backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
|
|
}
|
|
const avgPoolGradConfig = {
|
|
kernelName: (0, _tfjsCore.AvgPoolGrad),
|
|
backendName: "cpu",
|
|
kernelFunc: avgPoolGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a3KQN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchNorm", ()=>batchNorm);
|
|
parcelHelpers.export(exports, "batchNormConfig", ()=>batchNormConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function batchNorm(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, scale, offset, mean, variance } = inputs;
|
|
(0, _tfjsCore.util).assert(mean.shape.length === variance.shape.length, ()=>"Batch normalization gradient requires mean and variance to have equal ranks.");
|
|
(0, _tfjsCore.util).assert(offset == null || mean.shape.length === offset.shape.length, ()=>"Batch normalization gradient requires mean and offset to have equal ranks.");
|
|
(0, _tfjsCore.util).assert(scale == null || mean.shape.length === scale.shape.length, ()=>"Batch normalization gradient requires mean and scale to have equal ranks.");
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
mean,
|
|
variance,
|
|
scale,
|
|
offset
|
|
], "batchNorm");
|
|
let { varianceEpsilon } = attrs;
|
|
if (varianceEpsilon == null) varianceEpsilon = 0.001;
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const mVals = backend.data.get(mean.dataId).values;
|
|
const varVals = backend.data.get(variance.dataId).values;
|
|
const sVals = scale ? backend.data.get(scale.dataId).values : new Float32Array([
|
|
1
|
|
]);
|
|
const offVals = offset ? backend.data.get(offset.dataId).values : 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 backend.makeTensorInfo(x.shape, x.dtype, outVals);
|
|
}
|
|
const batchNormConfig = {
|
|
kernelName: (0, _tfjsCore.FusedBatchNorm),
|
|
backendName: "cpu",
|
|
kernelFunc: batchNorm
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7Jug2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "batchToSpaceND", ()=>batchToSpaceND);
|
|
parcelHelpers.export(exports, "batchToSpaceNDConfig", ()=>batchToSpaceNDConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _reshape = require("./Reshape");
|
|
var _slice = require("./Slice");
|
|
var _transpose = require("./Transpose");
|
|
function batchToSpaceND(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { blockShape, crops } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x
|
|
], "batchToSpaceND");
|
|
const prod = blockShape.reduce((a, b)=>a * b);
|
|
const reshaped = (0, _tfjsCore.backend_util).getReshaped(x.shape, blockShape, prod);
|
|
const permuted = (0, _tfjsCore.backend_util).getPermuted(reshaped.length, blockShape.length);
|
|
const reshapedPermuted = (0, _tfjsCore.backend_util).getReshapedPermuted(x.shape, blockShape, prod);
|
|
const sliceBeginCoords = (0, _tfjsCore.backend_util).getSliceBeginCoords(crops, blockShape.length);
|
|
const sliceSize = (0, _tfjsCore.backend_util).getSliceSize(reshapedPermuted, crops, blockShape.length);
|
|
const xReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: reshaped
|
|
}
|
|
});
|
|
const xTransposed = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: xReshaped
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permuted
|
|
}
|
|
});
|
|
const xTransposedReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: xTransposed
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: reshapedPermuted
|
|
}
|
|
});
|
|
const result = (0, _slice.slice)({
|
|
inputs: {
|
|
x: xTransposedReshaped
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin: sliceBeginCoords,
|
|
size: sliceSize
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(xReshaped);
|
|
backend.disposeIntermediateTensorInfo(xTransposed);
|
|
backend.disposeIntermediateTensorInfo(xTransposedReshaped);
|
|
return result;
|
|
}
|
|
const batchToSpaceNDConfig = {
|
|
kernelName: (0, _tfjsCore.BatchToSpaceND),
|
|
backendName: "cpu",
|
|
kernelFunc: batchToSpaceND
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Reshape":"9350i","./Slice":"9L9GN","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hE7iz":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "bincount", ()=>bincount);
|
|
parcelHelpers.export(exports, "bincountConfig", ()=>bincountConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _bincountImpl = require("./Bincount_impl");
|
|
function bincount(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, weights } = inputs;
|
|
const { size } = attrs;
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const weightsVals = backend.data.get(weights.dataId).values;
|
|
const outVals = (0, _bincountImpl.bincountImpl)(xVals, weightsVals, weights.dtype, weights.shape, size);
|
|
return backend.makeTensorInfo([
|
|
size
|
|
], weights.dtype, outVals);
|
|
}
|
|
const bincountConfig = {
|
|
kernelName: (0, _tfjsCore.Bincount),
|
|
backendName: "cpu",
|
|
kernelFunc: bincount
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Bincount_impl":"4EF2S","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4GYx6":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "broadcastArgs", ()=>broadcastArgs);
|
|
parcelHelpers.export(exports, "broadcastArgsConfig", ()=>broadcastArgsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function broadcastArgs(args) {
|
|
const { inputs, backend } = args;
|
|
const { s0, s1 } = inputs;
|
|
const s0Vals = backend.data.get(s0.dataId).values;
|
|
const s1Vals = backend.data.get(s1.dataId).values;
|
|
const broadcastShape = (0, _tfjsCore.backend_util).assertAndGetBroadcastShape(Array.from(s0Vals), Array.from(s1Vals));
|
|
return backend.makeTensorInfo([
|
|
broadcastShape.length
|
|
], "int32", Int32Array.from(broadcastShape));
|
|
}
|
|
const broadcastArgsConfig = {
|
|
kernelName: (0, _tfjsCore.BroadcastArgs),
|
|
backendName: "cpu",
|
|
kernelFunc: broadcastArgs
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ck0lb":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "clipByValue", ()=>clipByValue);
|
|
parcelHelpers.export(exports, "clipByValueConfig", ()=>clipByValueConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const clipByValue = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.ClipByValue), (xi, attrs)=>{
|
|
const clipAttrs = attrs;
|
|
if (xi > clipAttrs.clipValueMax) return clipAttrs.clipValueMax;
|
|
return xi < clipAttrs.clipValueMin ? clipAttrs.clipValueMin : xi;
|
|
});
|
|
const clipByValueConfig = {
|
|
kernelName: (0, _tfjsCore.ClipByValue),
|
|
backendName: "cpu",
|
|
kernelFunc: clipByValue
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kThBM":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "complexAbs", ()=>complexAbs);
|
|
parcelHelpers.export(exports, "complexAbsConfig", ()=>complexAbsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const complexAbs = (args)=>{
|
|
const { x } = args.inputs;
|
|
const cpuBackend = args.backend;
|
|
const resultValues = new Float32Array((0, _tfjsCore.util).sizeFromShape(x.shape));
|
|
const complexVals = cpuBackend.data.get(x.dataId);
|
|
const real = complexVals.complexTensorInfos.real;
|
|
const imag = complexVals.complexTensorInfos.imag;
|
|
const realVals = cpuBackend.data.get(real.dataId).values;
|
|
const imagVals = cpuBackend.data.get(imag.dataId).values;
|
|
for(let i = 0; i < realVals.length; i++){
|
|
const real = realVals[i];
|
|
const imag = imagVals[i];
|
|
resultValues[i] = Math.hypot(real, imag);
|
|
}
|
|
return cpuBackend.makeOutput(resultValues, x.shape, "float32");
|
|
};
|
|
const complexAbsConfig = {
|
|
kernelName: (0, _tfjsCore.ComplexAbs),
|
|
backendName: "cpu",
|
|
kernelFunc: complexAbs
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iYEAT":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "concat", ()=>concat);
|
|
parcelHelpers.export(exports, "concatConfig", ()=>concatConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _complex = require("./Complex");
|
|
var _concatImpl = require("./Concat_impl");
|
|
var _identity = require("./Identity");
|
|
var _imag = require("./Imag");
|
|
var _real = require("./Real");
|
|
var _reshape = require("./Reshape");
|
|
function concat(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { axis } = attrs;
|
|
const $axis = (0, _tfjsCore.util).parseAxisParam(axis, inputs[0].shape)[0];
|
|
const shapes = inputs.map((t)=>t.shape);
|
|
(0, _tfjsCore.backend_util).assertParamsConsistent(shapes, $axis);
|
|
let outShape = (0, _tfjsCore.backend_util).computeOutShape(inputs.map((t)=>t.shape), $axis);
|
|
if ((0, _tfjsCore.util).sizeFromShape(outShape) === 0) return backend.makeTensorInfo(outShape, inputs[0].dtype, []);
|
|
// Keep only non-empty tensors (ignore tensors with 0 in their shape).
|
|
const $inputs = inputs.filter((t)=>(0, _tfjsCore.util).sizeFromShape(t.shape) > 0);
|
|
if ($inputs.length === 1) return (0, _identity.identity)({
|
|
inputs: {
|
|
x: $inputs[0]
|
|
},
|
|
backend
|
|
});
|
|
if ($inputs[0].dtype === "complex64") {
|
|
const reals = $inputs.map((t)=>(0, _real.real)({
|
|
inputs: {
|
|
input: t
|
|
},
|
|
backend
|
|
}));
|
|
const imags = $inputs.map((t)=>(0, _imag.imag)({
|
|
inputs: {
|
|
input: t
|
|
},
|
|
backend
|
|
}));
|
|
const realConcated = concat({
|
|
inputs: reals,
|
|
backend,
|
|
attrs: {
|
|
axis: $axis
|
|
}
|
|
});
|
|
const imagConcated = concat({
|
|
inputs: imags,
|
|
backend,
|
|
attrs: {
|
|
axis: $axis
|
|
}
|
|
});
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: realConcated,
|
|
imag: imagConcated
|
|
},
|
|
backend
|
|
});
|
|
reals.forEach((r)=>backend.disposeIntermediateTensorInfo(r));
|
|
imags.forEach((i)=>backend.disposeIntermediateTensorInfo(i));
|
|
backend.disposeIntermediateTensorInfo(realConcated);
|
|
backend.disposeIntermediateTensorInfo(imagConcated);
|
|
return result;
|
|
}
|
|
// 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 inputs2D = $inputs.map((t)=>{
|
|
const innerSize = (0, _tfjsCore.util).sizeFromShape(t.shape.slice($axis));
|
|
const shape = [
|
|
-1,
|
|
innerSize
|
|
];
|
|
return (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: t
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape
|
|
}
|
|
});
|
|
});
|
|
const inputsValShapes = inputs2D.map((t)=>{
|
|
return {
|
|
vals: backend.data.get(t.dataId).values,
|
|
shape: t.shape
|
|
};
|
|
});
|
|
// Concats 2d tensors along axis=1.
|
|
outShape = (0, _tfjsCore.backend_util).computeOutShape(inputs2D.map((t)=>t.shape), 1 /* axis */ );
|
|
const simplyConcat = inputs2D[0].shape[0] === 1;
|
|
const outVals = (0, _concatImpl.concatImpl)(inputsValShapes, outShape, inputs[0].dtype, simplyConcat);
|
|
const finalOutShape = (0, _tfjsCore.backend_util).computeOutShape($inputs.map((t)=>t.shape), $axis);
|
|
const outInfo = backend.makeTensorInfo(finalOutShape, inputs[0].dtype, outVals);
|
|
inputs2D.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return outInfo;
|
|
}
|
|
const concatConfig = {
|
|
kernelName: (0, _tfjsCore.Concat),
|
|
backendName: "cpu",
|
|
kernelFunc: concat
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Complex":"3DPmh","./Concat_impl":"50NO7","./Identity":"btREJ","./Imag":"af3Tx","./Real":"eZ7aJ","./Reshape":"9350i","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"af3Tx":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "imag", ()=>imag);
|
|
parcelHelpers.export(exports, "imagConfig", ()=>imagConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function imag(args) {
|
|
const { inputs, backend } = args;
|
|
const { input } = inputs;
|
|
const imag = backend.data.get(input.dataId).complexTensorInfos.imag;
|
|
const imagVal = backend.data.get(imag.dataId).values;
|
|
// When complex tensor is disposed, its underlying parts will be disposed too.
|
|
// Make new tensor out of the imag value of the complex. This makes sure the
|
|
// value is still accessible even if complex tensor is disposed.
|
|
return backend.makeTensorInfo(imag.shape, imag.dtype, imagVal);
|
|
}
|
|
const imagConfig = {
|
|
kernelName: (0, _tfjsCore.Imag),
|
|
backendName: "cpu",
|
|
kernelFunc: imag
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4bj3X":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2D", ()=>conv2D);
|
|
parcelHelpers.export(exports, "conv2DConfig", ()=>conv2DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function conv2D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter } = inputs;
|
|
const { strides, pad, dataFormat, dilations, dimRoundingMode } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
filter
|
|
], "conv2d");
|
|
const $dataFormat = (0, _tfjsCore.backend_util).convertConv2DDataFormat(dataFormat);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false, $dataFormat);
|
|
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 = new (0, _tfjsCore.TensorBuffer)(convInfo.outShape, x.dtype);
|
|
const xStrides = (0, _tfjsCore.util).computeStrides(x.shape);
|
|
const filterStrides = (0, _tfjsCore.util).computeStrides(filter.shape);
|
|
const xBatchStride = xStrides[0];
|
|
const xRowStride = isChannelsLast ? xStrides[1] : xStrides[2];
|
|
const xColStride = isChannelsLast ? xStrides[2] : 1;
|
|
const xChannelStride = isChannelsLast ? 1 : xStrides[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 = backend.data.get(x.dataId).values;
|
|
const wVals = backend.data.get(filter.dataId).values;
|
|
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 * filterStrides[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 * filterStrides[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 backend.makeTensorInfo(y.shape, y.dtype, yVals);
|
|
}
|
|
const conv2DConfig = {
|
|
kernelName: (0, _tfjsCore.Conv2D),
|
|
backendName: "cpu",
|
|
kernelFunc: conv2D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jHKF1":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2DBackpropFilter", ()=>conv2DBackpropFilter);
|
|
parcelHelpers.export(exports, "conv2DBackpropFilterConfig", ()=>conv2DBackpropFilterConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function conv2DBackpropFilter(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, dy } = inputs;
|
|
const { strides, pad, dataFormat, dimRoundingMode, filterShape } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
dy
|
|
], "conv2dBackpropFilter");
|
|
const $dataFormat = (0, _tfjsCore.backend_util).convertConv2DDataFormat(dataFormat);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filterShape, strides, 1 /* dilations */ , pad, dimRoundingMode, false, $dataFormat);
|
|
const { strideHeight, strideWidth, filterHeight, filterWidth } = convInfo;
|
|
const isChannelsLast = convInfo.dataFormat === "channelsLast";
|
|
const dW = new (0, _tfjsCore.TensorBuffer)(convInfo.filterShape, "float32");
|
|
const leftPad = convInfo.padInfo.left;
|
|
const topPad = convInfo.padInfo.top;
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const dyVals = backend.data.get(dy.dataId).values;
|
|
const xBuf = new (0, _tfjsCore.TensorBuffer)(x.shape, x.dtype, xVals);
|
|
const dyBuf = new (0, _tfjsCore.TensorBuffer)(dy.shape, dy.dtype, dyVals);
|
|
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){
|
|
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 backend.makeTensorInfo(dW.shape, dW.dtype, dW.values);
|
|
}
|
|
const conv2DBackpropFilterConfig = {
|
|
kernelName: (0, _tfjsCore.Conv2DBackpropFilter),
|
|
backendName: "cpu",
|
|
kernelFunc: conv2DBackpropFilter
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fBpei":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv2DBackpropInput", ()=>conv2DBackpropInput);
|
|
parcelHelpers.export(exports, "conv2DBackpropInputConfig", ()=>conv2DBackpropInputConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function conv2DBackpropInput(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, filter } = inputs;
|
|
const { inputShape, strides, pad, dataFormat, dimRoundingMode } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy,
|
|
filter
|
|
], "conv2dBackpropInput");
|
|
const filterStrides = (0, _tfjsCore.util).computeStrides(filter.shape);
|
|
const dyStrides = (0, _tfjsCore.util).computeStrides(dy.shape);
|
|
let $dataFormat = (0, _tfjsCore.backend_util).convertConv2DDataFormat(dataFormat);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(inputShape, filter.shape, strides, 1 /* dilations */ , pad, dimRoundingMode, false, $dataFormat);
|
|
const dx = new (0, _tfjsCore.TensorBuffer)(convInfo.inShape, "float32");
|
|
const dxValues = dx.values;
|
|
const dyValues = backend.data.get(dy.dataId).values;
|
|
const fltValues = backend.data.get(filter.dataId).values;
|
|
const [fltS0, fltS1, fltS2] = filterStrides;
|
|
const { batchSize, filterHeight, filterWidth, inChannels, inHeight, inWidth, outChannels, outHeight, outWidth, strideHeight, strideWidth } = convInfo;
|
|
$dataFormat = convInfo.dataFormat;
|
|
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 = dyStrides[0];
|
|
const yRowStride = isChannelsLast ? dyStrides[1] : dyStrides[2];
|
|
const yColStride = isChannelsLast ? dyStrides[2] : 1;
|
|
const yChannelStride = isChannelsLast ? 1 : dyStrides[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 backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
|
|
}
|
|
const conv2DBackpropInputConfig = {
|
|
kernelName: (0, _tfjsCore.Conv2DBackpropInput),
|
|
backendName: "cpu",
|
|
kernelFunc: conv2DBackpropInput
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iJ4dh":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3D", ()=>conv3D);
|
|
parcelHelpers.export(exports, "conv3DConfig", ()=>conv3DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function conv3D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter } = inputs;
|
|
const { strides, pad, dilations } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
filter
|
|
], "conv3d");
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv3DInfo(x.shape, filter.shape, strides, dilations, pad);
|
|
const { filterDepth, filterHeight, filterWidth, dilationDepth, dilationHeight, dilationWidth, padInfo } = convInfo;
|
|
const padFront = padInfo.front;
|
|
const padLeft = padInfo.left;
|
|
const padTop = padInfo.top;
|
|
const y = new (0, _tfjsCore.TensorBuffer)(convInfo.outShape, x.dtype);
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const wVals = backend.data.get(filter.dataId).values;
|
|
const yVals = y.values;
|
|
const xStrides = (0, _tfjsCore.util).computeStrides(x.shape);
|
|
const filterStrides = (0, _tfjsCore.util).computeStrides(filter.shape);
|
|
for(let b = 0; b < convInfo.batchSize; ++b){
|
|
const xOffset1 = b * xStrides[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 * filterStrides[0];
|
|
const xOffset2 = xOffset1 + xF * xStrides[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 * filterStrides[1];
|
|
const xOffset3 = xOffset2 + xR * xStrides[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 * filterStrides[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 backend.makeTensorInfo(y.shape, y.dtype, y.values);
|
|
}
|
|
const conv3DConfig = {
|
|
kernelName: (0, _tfjsCore.Conv3D),
|
|
backendName: "cpu",
|
|
kernelFunc: conv3D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g7cYG":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3DBackpropFilterV2", ()=>conv3DBackpropFilterV2);
|
|
parcelHelpers.export(exports, "conv3DBackpropFilterV2Config", ()=>conv3DBackpropFilterV2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function conv3DBackpropFilterV2(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, dy } = inputs;
|
|
const { strides, pad, filterShape } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
dy
|
|
], "conv3dBackpropFilterV2");
|
|
const xStrides = (0, _tfjsCore.util).computeStrides(x.shape);
|
|
const dyStrides = (0, _tfjsCore.util).computeStrides(dy.shape);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv3DInfo(x.shape, filterShape, strides, 1 /* dilations */ , pad);
|
|
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 = new (0, _tfjsCore.TensorBuffer)(convInfo.filterShape, "float32");
|
|
const dwValues = dw.values;
|
|
const [dwS0, dwS1, dwS2, dwS3] = dw.strides;
|
|
const dyValues = backend.data.get(dy.dataId).values;
|
|
const [dyS0, dyS1, dyS2, dyS3] = dyStrides;
|
|
const xValues = backend.data.get(x.dataId).values;
|
|
const [xS0, xS1, xS2, xS3] = xStrides;
|
|
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 backend.makeTensorInfo(dw.shape, dw.dtype, dw.values);
|
|
}
|
|
const conv3DBackpropFilterV2Config = {
|
|
kernelName: (0, _tfjsCore.Conv3DBackpropFilterV2),
|
|
backendName: "cpu",
|
|
kernelFunc: conv3DBackpropFilterV2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"l6kPr":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "conv3DBackpropInputV2", ()=>conv3DBackpropInputV2);
|
|
parcelHelpers.export(exports, "conv3DBackpropInputV2Config", ()=>conv3DBackpropInputV2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function conv3DBackpropInputV2(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, filter } = inputs;
|
|
const { pad, strides, inputShape } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy
|
|
], "conv3dBackpropInputV2");
|
|
const dyStrides = (0, _tfjsCore.util).computeStrides(dy.shape);
|
|
const filterStrides = (0, _tfjsCore.util).computeStrides(filter.shape);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv3DInfo(inputShape, filter.shape, strides, 1 /* dilations */ , pad);
|
|
const dx = new (0, _tfjsCore.TensorBuffer)(convInfo.inShape, "float32");
|
|
const dxValues = dx.values;
|
|
const [dxS0, dxS1, dxS2, dxS3] = dx.strides;
|
|
const dyValues = backend.data.get(dy.dataId).values;
|
|
const [dyS0, dyS1, dyS2, dyS3] = dyStrides;
|
|
const fltValues = backend.data.get(filter.dataId).values;
|
|
const [fltS0, fltS1, fltS2, fltS3] = filterStrides;
|
|
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 backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
|
|
}
|
|
const conv3DBackpropInputV2Config = {
|
|
kernelName: (0, _tfjsCore.Conv3DBackpropInputV2),
|
|
backendName: "cpu",
|
|
kernelFunc: conv3DBackpropInputV2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hkcOn":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cos", ()=>cos);
|
|
parcelHelpers.export(exports, "cosConfig", ()=>cosConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const cos = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Cos), (xi)=>Math.cos(xi));
|
|
const cosConfig = {
|
|
kernelName: (0, _tfjsCore.Cos),
|
|
backendName: "cpu",
|
|
kernelFunc: cos
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eg9u0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cosh", ()=>cosh);
|
|
parcelHelpers.export(exports, "coshConfig", ()=>coshConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const cosh = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Cosh), (xi)=>Math.cosh(xi));
|
|
const coshConfig = {
|
|
kernelName: (0, _tfjsCore.Cosh),
|
|
backendName: "cpu",
|
|
kernelFunc: cosh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8K1SK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cropAndResize", ()=>cropAndResize);
|
|
parcelHelpers.export(exports, "cropAndResizeConfig", ()=>cropAndResizeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function cropAndResize(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { image, boxes, boxInd } = inputs;
|
|
const { cropSize, method, extrapolationValue } = attrs;
|
|
const [batch, imageHeight, imageWidth, numChannels] = image.shape;
|
|
const numBoxes = boxes.shape[0];
|
|
const [cropHeight, cropWidth] = cropSize;
|
|
const output = (0, _tfjsCore.buffer)([
|
|
numBoxes,
|
|
cropHeight,
|
|
cropWidth,
|
|
numChannels
|
|
], "float32");
|
|
const boxVals = backend.data.get(boxes.dataId).values;
|
|
const boxIndVals = backend.data.get(boxInd.dataId).values;
|
|
const imageVals = backend.data.get(image.dataId).values;
|
|
const inStride = (0, _tfjsCore.util).computeStrides(image.shape); // to calculate flat indexes into image
|
|
const outStride = (0, _tfjsCore.util).computeStrides(output.shape); // 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 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 backend.makeTensorInfo(output.shape, output.dtype, output.values);
|
|
}
|
|
const cropAndResizeConfig = {
|
|
kernelName: (0, _tfjsCore.CropAndResize),
|
|
backendName: "cpu",
|
|
kernelFunc: cropAndResize
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bN0pp":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cumprod", ()=>cumprod);
|
|
parcelHelpers.export(exports, "cumprodConfig", ()=>cumprodConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _transpose = require("./Transpose");
|
|
function cumprod(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, exclusive, reverse } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "cumprod");
|
|
const permutation = (0, _tfjsCore.backend_util).getAxesPermutation([
|
|
axis
|
|
], x.shape.length);
|
|
let $x = x;
|
|
if (permutation != null) $x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutation
|
|
}
|
|
});
|
|
const permutedAxis = (0, _tfjsCore.backend_util).getInnerMostAxes(1, x.shape.length)[0];
|
|
if (permutedAxis !== $x.shape.length - 1) throw new Error(`backend.cumprod in CPU expects an inner-most ` + `axis=${$x.shape.length - 1} but got axis=${permutedAxis}`);
|
|
const resultDtype = (0, _tfjsCore.upcastType)($x.dtype, "int32");
|
|
const vals = (0, _tfjsCore.util).makeOnesTypedArray((0, _tfjsCore.util).sizeFromShape($x.shape), resultDtype);
|
|
const aVals = backend.data.get($x.dataId).values;
|
|
const finalDim = $x.shape[$x.shape.length - 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 ? 1 : aVals[idx];
|
|
else {
|
|
const prevIdx = indexAdjuster(i, j - 1);
|
|
vals[idx] = exclusive ? aVals[prevIdx] * vals[prevIdx] : aVals[idx] * vals[prevIdx];
|
|
}
|
|
}
|
|
const result = backend.makeTensorInfo($x.shape, resultDtype, vals);
|
|
if (permutation != null) {
|
|
const reversePermutation = (0, _tfjsCore.backend_util).getUndoAxesPermutation(permutation);
|
|
const reverseTransposedResult = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: reversePermutation
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
backend.disposeIntermediateTensorInfo($x);
|
|
return reverseTransposedResult;
|
|
}
|
|
return result;
|
|
}
|
|
const cumprodConfig = {
|
|
kernelName: (0, _tfjsCore.Cumprod),
|
|
backendName: "cpu",
|
|
kernelFunc: cumprod
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8YA18":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "cumsum", ()=>cumsum);
|
|
parcelHelpers.export(exports, "cumsumConfig", ()=>cumsumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _transpose = require("./Transpose");
|
|
function cumsum(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, exclusive, reverse } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "cumsum");
|
|
const permutation = (0, _tfjsCore.backend_util).getAxesPermutation([
|
|
axis
|
|
], x.shape.length);
|
|
let $x = x;
|
|
if (permutation != null) $x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutation
|
|
}
|
|
});
|
|
const permutedAxis = (0, _tfjsCore.backend_util).getInnerMostAxes(1, x.shape.length)[0];
|
|
if (permutedAxis !== $x.shape.length - 1) throw new Error(`backend.cumsum in CPU expects an inner-most ` + `axis=${$x.shape.length - 1} but got axis=${permutedAxis}`);
|
|
const resultDtype = (0, _tfjsCore.upcastType)($x.dtype, "int32");
|
|
const vals = (0, _tfjsCore.util).makeZerosTypedArray((0, _tfjsCore.util).sizeFromShape($x.shape), resultDtype);
|
|
const aVals = backend.data.get($x.dataId).values;
|
|
const finalDim = $x.shape[$x.shape.length - 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];
|
|
}
|
|
}
|
|
const result = backend.makeTensorInfo($x.shape, resultDtype, vals);
|
|
if (permutation != null) {
|
|
const reversePermutation = (0, _tfjsCore.backend_util).getUndoAxesPermutation(permutation);
|
|
const reverseTransposedResult = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: reversePermutation
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
backend.disposeIntermediateTensorInfo($x);
|
|
return reverseTransposedResult;
|
|
}
|
|
return result;
|
|
}
|
|
const cumsumConfig = {
|
|
kernelName: (0, _tfjsCore.Cumsum),
|
|
backendName: "cpu",
|
|
kernelFunc: cumsum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cpFc0":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "denseBincount", ()=>denseBincount);
|
|
parcelHelpers.export(exports, "denseBincountConfig", ()=>denseBincountConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _bincountImpl = require("./Bincount_impl");
|
|
function denseBincount(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, weights } = inputs;
|
|
const { size, binaryOutput } = attrs;
|
|
if (x.shape.length === 1) {
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const weightsVals = backend.data.get(weights.dataId).values;
|
|
const outVals = (0, _bincountImpl.bincountImpl)(xVals, weightsVals, weights.dtype, weights.shape, size);
|
|
return backend.makeTensorInfo([
|
|
size
|
|
], weights.dtype, outVals);
|
|
} else if (x.shape.length === 2) {
|
|
const xBuf = backend.bufferSync(x);
|
|
const weightsBuf = backend.bufferSync(weights);
|
|
const outBuf = (0, _bincountImpl.bincountReduceImpl)(xBuf, weightsBuf, size, binaryOutput);
|
|
return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);
|
|
}
|
|
throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank` + `${x.shape.length}.`);
|
|
}
|
|
const denseBincountConfig = {
|
|
kernelName: (0, _tfjsCore.DenseBincount),
|
|
backendName: "cpu",
|
|
kernelFunc: denseBincount
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Bincount_impl":"4EF2S","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"l4MfW":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthToSpace", ()=>depthToSpace);
|
|
parcelHelpers.export(exports, "depthToSpaceConfig", ()=>depthToSpaceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function depthToSpace(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { blockSize, dataFormat } = attrs;
|
|
(0, _tfjsCore.util).assert(dataFormat === "NHWC", ()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${dataFormat}`);
|
|
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 = backend.data.get(x.dataId).values;
|
|
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 backend.makeTensorInfo([
|
|
batchSize,
|
|
outputHeight,
|
|
outputWidth,
|
|
outputDepth
|
|
], x.dtype, result);
|
|
}
|
|
const depthToSpaceConfig = {
|
|
kernelName: (0, _tfjsCore.DepthToSpace),
|
|
backendName: "cpu",
|
|
kernelFunc: depthToSpace
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2iRpa":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNative", ()=>depthwiseConv2dNative);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeConfig", ()=>depthwiseConv2dNativeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function depthwiseConv2dNative(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter } = inputs;
|
|
const { strides, pad, dilations, dimRoundingMode } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
filter
|
|
], "depthwiseConv2DNative");
|
|
const xStrides = (0, _tfjsCore.util).computeStrides(x.shape);
|
|
const filterStrides = (0, _tfjsCore.util).computeStrides(filter.shape);
|
|
let $dilations = dilations;
|
|
if ($dilations == null) $dilations = [
|
|
1,
|
|
1
|
|
];
|
|
(0, _tfjsCore.util).assert((0, _tfjsCore.backend_util).eitherStridesOrDilationsAreOne(strides, $dilations), ()=>"Error in depthwiseConv2d: Either strides or dilations must be " + `1. Got strides ${strides} and dilations '${$dilations}'`);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filter.shape, strides, $dilations, pad, dimRoundingMode, true);
|
|
const { filterHeight, filterWidth, dilationHeight, dilationWidth, padInfo } = convInfo;
|
|
const padLeft = padInfo.left;
|
|
const padTop = padInfo.top;
|
|
const chMul = convInfo.outChannels / convInfo.inChannels;
|
|
const y = new (0, _tfjsCore.TensorBuffer)(convInfo.outShape, x.dtype);
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const wVals = backend.data.get(filter.dataId).values;
|
|
const yVals = y.values;
|
|
for(let b = 0; b < convInfo.batchSize; ++b){
|
|
const xOffset1 = b * xStrides[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 - padTop;
|
|
for(let wR = 0; wR < filterHeight; ++wR){
|
|
const xR = xRCorner + wR * dilationHeight;
|
|
if (xR < 0 || xR >= convInfo.inHeight) continue;
|
|
const wOffset1 = wR * filterStrides[0];
|
|
const xOffset2 = xOffset1 + xR * xStrides[1];
|
|
for(let yC = 0; yC < convInfo.outWidth; ++yC){
|
|
const yOffset3 = yOffset2 + yC * y.strides[2];
|
|
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 * filterStrides[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 backend.makeTensorInfo(y.shape, y.dtype, y.values);
|
|
}
|
|
const depthwiseConv2dNativeConfig = {
|
|
kernelName: (0, _tfjsCore.DepthwiseConv2dNative),
|
|
backendName: "cpu",
|
|
kernelFunc: depthwiseConv2dNative
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"j6FA2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropFilter", ()=>depthwiseConv2dNativeBackpropFilter);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropFilterConfig", ()=>depthwiseConv2dNativeBackpropFilterConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function depthwiseConv2dNativeBackpropFilter(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, dy } = inputs;
|
|
const { strides, dilations, pad, dimRoundingMode, filterShape } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
dy
|
|
], "depthwiseConv2dNativeBackpropFilter");
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(x.shape, filterShape, strides, dilations, pad, dimRoundingMode, true);
|
|
const { strideHeight, strideWidth, filterHeight, filterWidth } = convInfo;
|
|
const dW = new (0, _tfjsCore.TensorBuffer)(convInfo.filterShape, "float32");
|
|
const leftPad = convInfo.padInfo.left;
|
|
const topPad = convInfo.padInfo.top;
|
|
const chMul = convInfo.outChannels / convInfo.inChannels;
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const xBuf = new (0, _tfjsCore.TensorBuffer)(x.shape, x.dtype, xVals);
|
|
const dyVals = backend.data.get(dy.dataId).values;
|
|
const dyBuf = new (0, _tfjsCore.TensorBuffer)(dy.shape, dy.dtype, dyVals);
|
|
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 backend.makeTensorInfo(dW.shape, dW.dtype, dW.values);
|
|
}
|
|
const depthwiseConv2dNativeBackpropFilterConfig = {
|
|
kernelName: (0, _tfjsCore.DepthwiseConv2dNativeBackpropFilter),
|
|
backendName: "cpu",
|
|
kernelFunc: depthwiseConv2dNativeBackpropFilter
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4Kyp1":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropInput", ()=>depthwiseConv2dNativeBackpropInput);
|
|
parcelHelpers.export(exports, "depthwiseConv2dNativeBackpropInputConfig", ()=>depthwiseConv2dNativeBackpropInputConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function depthwiseConv2dNativeBackpropInput(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, filter } = inputs;
|
|
const { strides, dilations, pad, dimRoundingMode, inputShape } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy,
|
|
filter
|
|
], "depthwiseConv2DNativeBackpropInput");
|
|
const dyStrides = (0, _tfjsCore.util).computeStrides(dy.shape);
|
|
const filterStrides = (0, _tfjsCore.util).computeStrides(filter.shape);
|
|
const convInfo = (0, _tfjsCore.backend_util).computeConv2DInfo(inputShape, filter.shape, strides, dilations, pad, dimRoundingMode, true);
|
|
const dx = new (0, _tfjsCore.TensorBuffer)(convInfo.inShape, "float32");
|
|
const dxValues = dx.values;
|
|
const [dxS0, dxS1, dxS2] = dx.strides;
|
|
const dyValues = backend.data.get(dy.dataId).values;
|
|
const [dyS0, dyS1, dyS2] = dyStrides;
|
|
const fltValues = backend.data.get(filter.dataId).values;
|
|
const [fltS0, fltS1, fltS2] = filterStrides;
|
|
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 backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
|
|
}
|
|
const depthwiseConv2dNativeBackpropInputConfig = {
|
|
kernelName: (0, _tfjsCore.DepthwiseConv2dNativeBackpropInput),
|
|
backendName: "cpu",
|
|
kernelFunc: depthwiseConv2dNativeBackpropInput
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c5zdj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "diag", ()=>diag);
|
|
parcelHelpers.export(exports, "diagConfig", ()=>diagConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function diag(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const outBuf = (0, _tfjsCore.buffer)([
|
|
xSize,
|
|
xSize
|
|
], x.dtype);
|
|
const vals = outBuf.values;
|
|
for(let i = 0; i < xVals.length; i++)vals[i * xSize + i] = xVals[i];
|
|
const outShape = [
|
|
...x.shape,
|
|
...x.shape
|
|
];
|
|
return backend.makeTensorInfo(outShape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const diagConfig = {
|
|
kernelName: (0, _tfjsCore.Diag),
|
|
backendName: "cpu",
|
|
kernelFunc: diag
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8CglA":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "dilation2DConfig", ()=>dilation2DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const dilation2DConfig = {
|
|
kernelName: (0, _tfjsCore.Dilation2D),
|
|
backendName: "cpu",
|
|
kernelFunc: ({ inputs, backend, attrs })=>{
|
|
const { x, filter } = inputs;
|
|
const { strides, pad, dilations } = attrs;
|
|
const cpuBackend = backend;
|
|
const xVals = cpuBackend.data.get(x.dataId).values;
|
|
const xRank = x.shape.length;
|
|
const filterVals = cpuBackend.data.get(filter.dataId).values;
|
|
const filterRank = filter.shape.length;
|
|
const { batchSize, inHeight, inWidth, inChannels, outHeight, outWidth, padInfo, strideHeight, strideWidth, filterHeight, filterWidth, dilationHeight, dilationWidth, outShape } = (0, _tfjsCore.backend_util).computeDilation2DInfo(x.shape, filter.shape, strides, pad, "NHWC" /* dataFormat */ , dilations);
|
|
const outSize = (0, _tfjsCore.util).sizeFromShape(outShape);
|
|
const outRank = outShape.length;
|
|
const outputVals = (0, _tfjsCore.util).getArrayFromDType(x.dtype, outSize);
|
|
// Upsampling the input by fill in `dilation size - 1` values between each
|
|
// input value.
|
|
// This implementation follows the TF c++ implementation:
|
|
// https://github.com/tensorflow/tensorflow/blob/d9a3a849edc198e90172bc58eb293de457f9d986/tensorflow/core/kernels/dilation_ops.cc
|
|
for(let b = 0; b < batchSize; ++b)for(let hOut = 0; hOut < outHeight; ++hOut){
|
|
const hBeg = hOut * strideHeight - padInfo.top;
|
|
for(let wOut = 0; wOut < outWidth; ++wOut){
|
|
const wBeg = wOut * strideWidth - padInfo.left;
|
|
for(let d = 0; d < inChannels; ++d){
|
|
let curVal = Number.MIN_SAFE_INTEGER;
|
|
for(let h = 0; h < filterHeight; ++h){
|
|
const hIn = hBeg + h * dilationHeight;
|
|
if (hIn >= 0 && hIn < inHeight) for(let w = 0; w < filterWidth; ++w){
|
|
const wIn = wBeg + w * dilationWidth;
|
|
if (wIn >= 0 && wIn < inWidth) {
|
|
const xIndex = (0, _tfjsCore.util).locToIndex([
|
|
b,
|
|
hIn,
|
|
wIn,
|
|
d
|
|
], xRank, (0, _tfjsCore.util).computeStrides(x.shape));
|
|
const filterIndex = (0, _tfjsCore.util).locToIndex([
|
|
h,
|
|
w,
|
|
d
|
|
], filterRank, (0, _tfjsCore.util).computeStrides(filter.shape));
|
|
const val = xVals[xIndex] + filterVals[filterIndex];
|
|
if (val > curVal) curVal = val;
|
|
}
|
|
}
|
|
}
|
|
const outputIndex = (0, _tfjsCore.util).locToIndex([
|
|
b,
|
|
hOut,
|
|
wOut,
|
|
d
|
|
], outRank, (0, _tfjsCore.util).computeStrides(outShape));
|
|
outputVals[outputIndex] = curVal;
|
|
}
|
|
}
|
|
}
|
|
const dataId = cpuBackend.write((0, _tfjsCore.util).toTypedArray(outputVals, x.dtype), outShape, x.dtype);
|
|
return {
|
|
dataId,
|
|
shape: outShape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5GOEE":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "dilation2DBackpropFilterConfig", ()=>dilation2DBackpropFilterConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const dilation2DBackpropFilterConfig = {
|
|
kernelName: (0, _tfjsCore.Dilation2DBackpropFilter),
|
|
backendName: "cpu",
|
|
kernelFunc: ({ inputs, backend, attrs })=>{
|
|
const { x, filter, dy } = inputs;
|
|
const { strides, pad, dilations } = attrs;
|
|
const cpuBackend = backend;
|
|
const $x = (0, _tfjsCore.util).toNestedArray(x.shape, cpuBackend.data.get(x.dataId).values);
|
|
const $filter = (0, _tfjsCore.util).toNestedArray(filter.shape, cpuBackend.data.get(filter.dataId).values);
|
|
const { batchSize, inHeight, inWidth, inChannels, outHeight, outWidth, padInfo, strideHeight, strideWidth, filterHeight, filterWidth, dilationHeight, dilationWidth, outShape } = (0, _tfjsCore.backend_util).computeDilation2DInfo(x.shape, filter.shape, strides, pad, "NHWC" /* dataFormat */ , dilations);
|
|
(0, _tfjsCore.util).assert(dy.rank === outShape.length, ()=>`Error in ${0, _tfjsCore.Dilation2DBackpropFilter}, dy ` + `must have the same rank as output ${outShape.length}, but got ` + `${dy.rank}`);
|
|
const $dy = (0, _tfjsCore.util).toNestedArray(outShape, cpuBackend.data.get(dy.dataId).values);
|
|
// The computed filter gradients has the same dimensions as the filter:
|
|
// [filterHeight, filterWidth, depth]
|
|
const gradients = (0, _tfjsCore.util).makeZerosNestedTypedArray(filter.shape, filter.dtype);
|
|
// In the case of multiple argmax branches, we only back-propagate along the
|
|
// last branch, i.e., the one with largest value of `h * filter_cols + w`,
|
|
// similarly to the max-pooling backward routines.
|
|
// This implementation follows the TF c++ implementation:
|
|
// https://github.com/tensorflow/tensorflow/blob/d9a3a849edc198e90172bc58eb293de457f9d986/tensorflow/core/kernels/dilation_ops.cc
|
|
for(let b = 0; b < batchSize; ++b)for(let hOut = 0; hOut < outHeight; ++hOut){
|
|
const hBeg = hOut * strideHeight - padInfo.top;
|
|
for(let wOut = 0; wOut < outWidth; ++wOut){
|
|
const wBeg = wOut * strideWidth - padInfo.left;
|
|
for(let d = 0; d < inChannels; ++d){
|
|
let curVal = Number.MIN_SAFE_INTEGER;
|
|
let hMax = 0;
|
|
let wMax = 0;
|
|
for(let h = 0; h < filterHeight; ++h){
|
|
const hIn = hBeg + h * dilationHeight;
|
|
if (hIn >= 0 && hIn < inHeight) for(let w = 0; w < filterWidth; ++w){
|
|
const wIn = wBeg + w * dilationWidth;
|
|
if (wIn >= 0 && wIn < inWidth) {
|
|
const val = $x[b][hIn][wIn][d] + $filter[h][w][d];
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
hMax = h;
|
|
wMax = w;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
gradients[hMax][wMax][d] += $dy[b][hOut][wOut][d];
|
|
}
|
|
}
|
|
}
|
|
const dataId = cpuBackend.write((0, _tfjsCore.util).toTypedArray(gradients, x.dtype), filter.shape, filter.dtype);
|
|
return {
|
|
dataId,
|
|
shape: filter.shape,
|
|
dtype: filter.dtype
|
|
};
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fnjGq":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "dilation2DBackpropInputConfig", ()=>dilation2DBackpropInputConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const dilation2DBackpropInputConfig = {
|
|
kernelName: (0, _tfjsCore.Dilation2DBackpropInput),
|
|
backendName: "cpu",
|
|
kernelFunc: ({ inputs, backend, attrs })=>{
|
|
const { x, filter, dy } = inputs;
|
|
const { strides, pad, dilations } = attrs;
|
|
const cpuBackend = backend;
|
|
const $x = (0, _tfjsCore.util).toNestedArray(x.shape, cpuBackend.data.get(x.dataId).values);
|
|
const $filter = (0, _tfjsCore.util).toNestedArray(filter.shape, cpuBackend.data.get(filter.dataId).values);
|
|
const { batchSize, inHeight, inWidth, inChannels, outHeight, outWidth, padInfo, strideHeight, strideWidth, filterHeight, filterWidth, dilationHeight, dilationWidth, outShape } = (0, _tfjsCore.backend_util).computeDilation2DInfo(x.shape, filter.shape, strides, pad, "NHWC" /* dataFormat */ , dilations);
|
|
(0, _tfjsCore.util).assert(dy.rank === outShape.length, ()=>`Error in ${0, _tfjsCore.Dilation2DBackpropInput}, dy ` + `must have the same rank as output ${outShape.length}, but got ` + `${dy.rank}`);
|
|
const $dy = (0, _tfjsCore.util).toNestedArray(outShape, cpuBackend.data.get(dy.dataId).values);
|
|
// The computed gradients has the same dimensions as the input:
|
|
// [batch, inputHeight, inputCols, inChannel]
|
|
const gradients = (0, _tfjsCore.util).makeZerosNestedTypedArray(x.shape, x.dtype);
|
|
// In the case of multiple argmax branches, we only back-propagate along the
|
|
// last branch, i.e., the one with largest value of `h * filter_cols + w`,
|
|
// similarly to the max-pooling backward routines.
|
|
// This implementation follows the TF c++ implementation:
|
|
// https://github.com/tensorflow/tensorflow/blob/d9a3a849edc198e90172bc58eb293de457f9d986/tensorflow/core/kernels/dilation_ops.cc
|
|
for(let b = 0; b < batchSize; ++b)for(let hOut = 0; hOut < outHeight; ++hOut){
|
|
const hBeg = hOut * strideHeight - padInfo.top;
|
|
for(let wOut = 0; wOut < outWidth; ++wOut){
|
|
const wBeg = wOut * strideWidth - padInfo.left;
|
|
for(let d = 0; d < inChannels; ++d){
|
|
let curVal = Number.MIN_SAFE_INTEGER;
|
|
let hInMax = hBeg < 0 ? 0 : hBeg;
|
|
let wInMax = wBeg < 0 ? 0 : wBeg;
|
|
for(let h = 0; h < filterHeight; ++h){
|
|
const hIn = hBeg + h * dilationHeight;
|
|
if (hIn >= 0 && hIn < inHeight) for(let w = 0; w < filterWidth; ++w){
|
|
const wIn = wBeg + w * dilationWidth;
|
|
if (wIn >= 0 && wIn < inWidth) {
|
|
const val = $x[b][hIn][wIn][d] + $filter[h][w][d];
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
hInMax = hIn;
|
|
wInMax = wIn;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
gradients[b][hInMax][wInMax][d] += $dy[b][hOut][wOut][d];
|
|
}
|
|
}
|
|
}
|
|
const dataId = cpuBackend.write((0, _tfjsCore.util).toTypedArray(gradients, x.dtype), x.shape, x.dtype);
|
|
return {
|
|
dataId,
|
|
shape: x.shape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9ZCFV":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2023 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "draw", ()=>draw);
|
|
parcelHelpers.export(exports, "drawConfig", ()=>drawConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function draw(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { image } = inputs;
|
|
const { canvas, options } = attrs;
|
|
const { contextOptions, imageOptions } = options || {};
|
|
const alpha = (imageOptions === null || imageOptions === void 0 ? void 0 : imageOptions.alpha) || 1;
|
|
const contextType = (contextOptions === null || contextOptions === void 0 ? void 0 : contextOptions.contextType) || "2d";
|
|
if (contextType !== "2d") throw new Error(`Context type ${contextOptions.contextType} is not supported by the CPU backend.`);
|
|
const ctx = canvas.getContext(contextType, (contextOptions === null || contextOptions === void 0 ? void 0 : contextOptions.contextAttributes) || {});
|
|
if (ctx == null) throw new Error(`Could not get the context with ${contextType} type.`);
|
|
const [height, width] = image.shape.slice(0, 2);
|
|
const depth = image.shape.length === 2 ? 1 : image.shape[2];
|
|
const data = backend.data.get(image.dataId).values;
|
|
const multiplier = image.dtype === "float32" ? 255 : 1;
|
|
const bytes = new Uint8ClampedArray(width * height * 4);
|
|
for(let i = 0; i < height * width; ++i){
|
|
const rgba = [
|
|
0,
|
|
0,
|
|
0,
|
|
255 * alpha
|
|
];
|
|
for(let d = 0; d < depth; d++){
|
|
const value = data[i * depth + d];
|
|
if (image.dtype === "float32") {
|
|
if (value < 0 || value > 1) throw new Error(`Tensor values for a float32 Tensor must be in the ` + `range [0 - 1] but encountered ${value}.`);
|
|
} else if (image.dtype === "int32") {
|
|
if (value < 0 || value > 255) throw new Error(`Tensor values for a int32 Tensor must be in the ` + `range [0 - 255] but encountered ${value}.`);
|
|
}
|
|
if (depth === 1) {
|
|
rgba[0] = value * multiplier;
|
|
rgba[1] = value * multiplier;
|
|
rgba[2] = value * multiplier;
|
|
} else rgba[d] = value * multiplier;
|
|
}
|
|
const j = i * 4;
|
|
bytes[j + 0] = Math.round(rgba[0]);
|
|
bytes[j + 1] = Math.round(rgba[1]);
|
|
bytes[j + 2] = Math.round(rgba[2]);
|
|
bytes[j + 3] = Math.round(rgba[3]);
|
|
}
|
|
canvas.width = width;
|
|
canvas.height = height;
|
|
const imageData = new ImageData(bytes, width, height);
|
|
ctx.putImageData(imageData, 0, 0);
|
|
return image;
|
|
}
|
|
const drawConfig = {
|
|
kernelName: (0, _tfjsCore.Draw),
|
|
backendName: "cpu",
|
|
kernelFunc: draw
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lXbVv":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "einsum", ()=>einsum);
|
|
parcelHelpers.export(exports, "einsumConfig", ()=>einsumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _multiply = require("./Multiply");
|
|
var _reshape = require("./Reshape");
|
|
var _sum = require("./Sum");
|
|
var _transpose = require("./Transpose");
|
|
function einsum(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { equation } = attrs;
|
|
const tensors = inputs;
|
|
const { allDims, summedDims, idDims } = (0, _tfjsCore.backend_util).decodeEinsumEquation(equation, tensors.length);
|
|
(0, _tfjsCore.backend_util).checkEinsumDimSizes(allDims.length, idDims, tensors);
|
|
const { path, steps } = (0, _tfjsCore.backend_util).getEinsumComputePath(summedDims, idDims);
|
|
const nSteps = steps.length;
|
|
let out = null;
|
|
let numDimsRemaining = allDims.length;
|
|
const tensorsToDispose = [];
|
|
for(let i = 0; i < nSteps; ++i){
|
|
for (const idTerm of steps[i]){
|
|
const { permutationIndices: perm, expandDims: dimsToExpand } = (0, _tfjsCore.backend_util).getEinsumPermutation(numDimsRemaining, idDims[idTerm]);
|
|
let x;
|
|
if ((0, _tfjsCore.backend_util).isIdentityPermutation(perm)) x = tensors[idTerm];
|
|
else {
|
|
x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: tensors[idTerm]
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm
|
|
}
|
|
});
|
|
tensorsToDispose.push(x);
|
|
}
|
|
const targetShape = x.shape.slice();
|
|
for(let k = 0; k < dimsToExpand.length; ++k)targetShape.splice(dimsToExpand[k], 0, 1);
|
|
if (!(0, _tfjsCore.util).arraysEqual(x.shape, targetShape)) {
|
|
x = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: targetShape
|
|
}
|
|
});
|
|
tensorsToDispose.push(x);
|
|
}
|
|
if (out === null) out = x;
|
|
else {
|
|
// tslint:disable-next-line: no-unnecessary-type-assertion
|
|
out = (0, _multiply.multiply)({
|
|
inputs: {
|
|
a: x,
|
|
b: out
|
|
},
|
|
backend
|
|
});
|
|
tensorsToDispose.push(out);
|
|
}
|
|
}
|
|
if (i < nSteps - 1) {
|
|
if (path[i] >= 0) {
|
|
out = (0, _sum.sum)({
|
|
inputs: {
|
|
x: out
|
|
},
|
|
backend,
|
|
attrs: {
|
|
axis: path[i] - (allDims.length - numDimsRemaining),
|
|
keepDims: false
|
|
}
|
|
});
|
|
tensorsToDispose.push(out);
|
|
}
|
|
numDimsRemaining--;
|
|
}
|
|
}
|
|
// Clean up intermediate tensors.
|
|
for (const tensorInfo of tensorsToDispose){
|
|
if (tensorInfo === out) continue;
|
|
backend.disposeIntermediateTensorInfo(tensorInfo);
|
|
}
|
|
return out;
|
|
}
|
|
const einsumConfig = {
|
|
kernelName: (0, _tfjsCore.Einsum),
|
|
backendName: "cpu",
|
|
kernelFunc: einsum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Multiply":"FrRi2","./Reshape":"9350i","./Sum":"6gbbV","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6gbbV":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sum", ()=>sum);
|
|
parcelHelpers.export(exports, "sumConfig", ()=>sumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _zerosImpl = require("../utils/zeros_impl");
|
|
var _cast = require("./Cast");
|
|
var _identity = require("./Identity");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function sum(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "sum");
|
|
let $x;
|
|
if (x.dtype === "bool") $x = (0, _cast.cast)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dtype: "int32"
|
|
}
|
|
});
|
|
else $x = (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
const xRank = $x.shape.length;
|
|
const axes = (0, _tfjsCore.util).parseAxisParam(axis, $x.shape);
|
|
const permutation = (0, _tfjsCore.backend_util).getAxesPermutation(axes, xRank);
|
|
let reductionAxes = axes;
|
|
let permutedX = $x;
|
|
if (permutation != null) {
|
|
permutedX = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x: $x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutation
|
|
}
|
|
});
|
|
reductionAxes = (0, _tfjsCore.backend_util).getInnerMostAxes(reductionAxes.length, xRank);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("sum", reductionAxes, permutedX.shape.length);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(permutedX.shape, reductionAxes);
|
|
const resultDtype = (0, _tfjsCore.backend_util).upcastType(permutedX.dtype, "int32");
|
|
let result = (0, _zerosImpl.zeros)(backend, outShape, resultDtype);
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const vals = backend.data.get(result.dataId).values;
|
|
const aVals = backend.data.get(permutedX.dataId).values;
|
|
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;
|
|
}
|
|
if (keepDims) {
|
|
const newShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(result.shape, axes);
|
|
const oldResult = result;
|
|
result = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: newShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(oldResult);
|
|
}
|
|
backend.disposeIntermediateTensorInfo($x);
|
|
if (permutation != null) backend.disposeIntermediateTensorInfo(permutedX);
|
|
return result;
|
|
}
|
|
const sumConfig = {
|
|
kernelName: (0, _tfjsCore.Sum),
|
|
backendName: "cpu",
|
|
kernelFunc: sum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../utils/zeros_impl":"6us7T","./Cast":"fAtIw","./Identity":"btREJ","./Reshape":"9350i","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cZudI":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "eluGrad", ()=>eluGrad);
|
|
parcelHelpers.export(exports, "eluGradConfig", ()=>eluGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function eluGrad(args) {
|
|
const { inputs, backend } = args;
|
|
const { dy, y } = inputs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy,
|
|
y
|
|
], "eluGrad");
|
|
const resultValues = new Float32Array((0, _tfjsCore.util).sizeFromShape(y.shape));
|
|
const values = backend.data.get(y.dataId).values;
|
|
const dyValues = backend.data.get(dy.dataId).values;
|
|
for(let i = 0; i < values.length; ++i){
|
|
const v = values[i];
|
|
if (v >= 0) resultValues[i] = dyValues[i];
|
|
else resultValues[i] = dyValues[i] * (v + 1);
|
|
}
|
|
return backend.makeTensorInfo(y.shape, "float32", resultValues);
|
|
}
|
|
const eluGradConfig = {
|
|
kernelName: (0, _tfjsCore.EluGrad),
|
|
backendName: "cpu",
|
|
kernelFunc: eluGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"g7iiK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "erf", ()=>erf);
|
|
parcelHelpers.export(exports, "erfConfig", ()=>erfConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const p = (0, _tfjsCore.backend_util).ERF_P;
|
|
const a1 = (0, _tfjsCore.backend_util).ERF_A1;
|
|
const a2 = (0, _tfjsCore.backend_util).ERF_A2;
|
|
const a3 = (0, _tfjsCore.backend_util).ERF_A3;
|
|
const a4 = (0, _tfjsCore.backend_util).ERF_A4;
|
|
const a5 = (0, _tfjsCore.backend_util).ERF_A5;
|
|
const erf = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Erf), (xi)=>{
|
|
const sign = Math.sign(xi);
|
|
const v = Math.abs(xi);
|
|
const t = 1.0 / (1.0 + p * v);
|
|
return sign * (1.0 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-v * v));
|
|
});
|
|
const erfConfig = {
|
|
kernelName: (0, _tfjsCore.Erf),
|
|
backendName: "cpu",
|
|
kernelFunc: erf
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4z77l":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "expandDims", ()=>expandDims);
|
|
parcelHelpers.export(exports, "expandDimsConfig", ()=>expandDimsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reshape = require("./Reshape");
|
|
function expandDims(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { input } = inputs;
|
|
const { dim } = attrs;
|
|
const inputRank = input.shape.length;
|
|
const newShape = input.shape.slice();
|
|
let $dim = dim;
|
|
if (dim < 0) {
|
|
// Negative value is counted from the tail of rank.
|
|
(0, _tfjsCore.util).assert(-(inputRank + 1) <= dim, ()=>`Axis must be in the interval [${-(inputRank + 1)}, ${inputRank}]`);
|
|
$dim = inputRank + dim + 1;
|
|
}
|
|
newShape.splice($dim, 0, 1);
|
|
return (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: input
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: newShape
|
|
}
|
|
});
|
|
}
|
|
const expandDimsConfig = {
|
|
kernelName: (0, _tfjsCore.ExpandDims),
|
|
backendName: "cpu",
|
|
kernelFunc: expandDims
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Reshape":"9350i","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7gqPz":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fft", ()=>fft);
|
|
parcelHelpers.export(exports, "fftConfig", ()=>fftConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fftUtils = require("../utils/fft_utils");
|
|
var _reshape = require("./Reshape");
|
|
function fft(args) {
|
|
const { inputs, backend } = args;
|
|
const { input } = inputs;
|
|
const inputSize = (0, _tfjsCore.util).sizeFromShape(input.shape);
|
|
// Collapse all outer dimensions to a single batch dimension.
|
|
const innerDimensionSize = input.shape[input.shape.length - 1];
|
|
const batch = inputSize / innerDimensionSize;
|
|
const input2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: input
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
batch,
|
|
innerDimensionSize
|
|
]
|
|
}
|
|
});
|
|
const result = (0, _fftUtils.fftBatch)(input2D, false, backend);
|
|
const resultReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: input.shape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(input2D);
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
return resultReshaped;
|
|
}
|
|
const fftConfig = {
|
|
kernelName: (0, _tfjsCore.FFT),
|
|
backendName: "cpu",
|
|
kernelFunc: fft
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/fft_utils":"8ziy5","./Reshape":"9350i","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8ziy5":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
/**
|
|
* Calculate FFT of inner most elements of batch tensor.
|
|
*/ parcelHelpers.export(exports, "fftBatch", ()=>fftBatch);
|
|
parcelHelpers.export(exports, "fftImpl", ()=>fftImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _add = require("../kernels/Add");
|
|
var _complex = require("../kernels/Complex");
|
|
var _concat = require("../kernels/Concat");
|
|
var _identity = require("../kernels/Identity");
|
|
var _imag = require("../kernels/Imag");
|
|
var _multiply = require("../kernels/Multiply");
|
|
var _real = require("../kernels/Real");
|
|
var _realDiv = require("../kernels/RealDiv");
|
|
var _slice = require("../kernels/Slice");
|
|
var _sub = require("../kernels/Sub");
|
|
function fftBatch(input, inverse, cpuBackend) {
|
|
const inputShape = input.shape;
|
|
const batch = inputShape[0];
|
|
const innerDim = inputShape[1];
|
|
const inputVals = cpuBackend.data.get(input.dataId);
|
|
const real2D = inputVals.complexTensorInfos.real;
|
|
const imag2D = inputVals.complexTensorInfos.imag;
|
|
// Collects real and imaginary values separately.
|
|
const resultShape = [
|
|
batch,
|
|
innerDim
|
|
];
|
|
const resultSize = (0, _tfjsCore.util).sizeFromShape(resultShape);
|
|
const resultReal = (0, _tfjsCore.util).getTypedArrayFromDType("float32", resultSize);
|
|
const resultImag = (0, _tfjsCore.util).getTypedArrayFromDType("float32", resultSize);
|
|
for(let b = 0; b < batch; b++){
|
|
// TODO: Support slice ops for complex type.
|
|
const r = (0, _slice.slice)({
|
|
inputs: {
|
|
x: real2D
|
|
},
|
|
backend: cpuBackend,
|
|
attrs: {
|
|
begin: [
|
|
b,
|
|
0
|
|
],
|
|
size: [
|
|
1,
|
|
innerDim
|
|
]
|
|
}
|
|
});
|
|
const i = (0, _slice.slice)({
|
|
inputs: {
|
|
x: imag2D
|
|
},
|
|
backend: cpuBackend,
|
|
attrs: {
|
|
begin: [
|
|
b,
|
|
0
|
|
],
|
|
size: [
|
|
1,
|
|
innerDim
|
|
]
|
|
}
|
|
});
|
|
const input = (0, _complex.complex)({
|
|
inputs: {
|
|
real: r,
|
|
imag: i
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
// Run FFT by batch element.
|
|
const { real, imag } = fftImpl(input, inverse, cpuBackend);
|
|
const res = (0, _tfjsCore.backend_util).mergeRealAndImagArrays(real, imag);
|
|
for(let d = 0; d < innerDim; d++){
|
|
const c = (0, _tfjsCore.backend_util).getComplexWithIndex(res, d);
|
|
resultReal[b * innerDim + d] = c.real;
|
|
resultImag[b * innerDim + d] = c.imag;
|
|
}
|
|
cpuBackend.disposeIntermediateTensorInfo(r);
|
|
cpuBackend.disposeIntermediateTensorInfo(i);
|
|
cpuBackend.disposeIntermediateTensorInfo(input);
|
|
}
|
|
const $realInfo = cpuBackend.makeTensorInfo(resultShape, "float32", resultReal);
|
|
const $imagInfo = cpuBackend.makeTensorInfo(resultShape, "float32", resultImag);
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: $realInfo,
|
|
imag: $imagInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
cpuBackend.disposeIntermediateTensorInfo($realInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo($imagInfo);
|
|
return result;
|
|
}
|
|
function fftImpl(input, inverse, cpuBackend) {
|
|
const inputSize = (0, _tfjsCore.util).sizeFromShape(input.shape);
|
|
const inputVals = cpuBackend.data.get(input.dataId);
|
|
const realVals = cpuBackend.data.get(inputVals.complexTensorInfos.real.dataId).values;
|
|
const imagVals = cpuBackend.data.get(inputVals.complexTensorInfos.imag.dataId).values;
|
|
if (isExponentOf2(inputSize)) {
|
|
const result = fftRadix2(realVals, imagVals, inputSize, inverse, cpuBackend);
|
|
const resultShape = [
|
|
input.shape[0],
|
|
input.shape[1]
|
|
];
|
|
if (inverse) {
|
|
const realInfo = cpuBackend.makeTensorInfo(resultShape, "float32", result.real);
|
|
const imagInfo = cpuBackend.makeTensorInfo(resultShape, "float32", result.imag);
|
|
const sizeInfo = cpuBackend.makeTensorInfo([], "float32", (0, _tfjsCore.util).createScalarValue(inputSize, "float32"));
|
|
const sizeInfoCopy = (0, _identity.identity)({
|
|
inputs: {
|
|
x: sizeInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const divRealInfo = (0, _realDiv.realDivConfig).kernelFunc({
|
|
inputs: {
|
|
a: realInfo,
|
|
b: sizeInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const divImagInfo = (0, _realDiv.realDivConfig).kernelFunc({
|
|
inputs: {
|
|
a: imagInfo,
|
|
b: sizeInfoCopy
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const divRealVals = cpuBackend.data.get(divRealInfo.dataId).values;
|
|
const divImagVals = cpuBackend.data.get(divImagInfo.dataId).values;
|
|
cpuBackend.disposeIntermediateTensorInfo(realInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(imagInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(sizeInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(sizeInfoCopy);
|
|
cpuBackend.disposeIntermediateTensorInfo(divRealInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(divImagInfo);
|
|
return {
|
|
real: divRealVals,
|
|
imag: divImagVals
|
|
};
|
|
}
|
|
return result;
|
|
} else {
|
|
const data = (0, _tfjsCore.backend_util).mergeRealAndImagArrays(realVals, imagVals);
|
|
const rawOutput = fourierTransformByMatmul(data, inputSize, inverse);
|
|
return (0, _tfjsCore.backend_util).splitRealAndImagArrays(rawOutput);
|
|
}
|
|
}
|
|
function isExponentOf2(size) {
|
|
return (size & size - 1) === 0;
|
|
}
|
|
// FFT using Cooley-Tukey algorithm on radix 2 dimensional input.
|
|
function fftRadix2(realVals, imagVals, size, inverse, cpuBackend) {
|
|
if (size === 1) return {
|
|
real: realVals,
|
|
imag: imagVals
|
|
};
|
|
const data = (0, _tfjsCore.backend_util).mergeRealAndImagArrays(realVals, imagVals);
|
|
const half = size / 2;
|
|
const evenComplex = (0, _tfjsCore.backend_util).complexWithEvenIndex(data);
|
|
const evenRealVals = evenComplex.real;
|
|
const evenImagVals = evenComplex.imag;
|
|
const evenShape = [
|
|
evenRealVals.length
|
|
];
|
|
const evenRealInfo = cpuBackend.makeTensorInfo(evenShape, "float32", evenRealVals);
|
|
const evenImagInfo = cpuBackend.makeTensorInfo(evenShape, "float32", evenImagVals);
|
|
const evenTensorInfo = (0, _complex.complex)({
|
|
inputs: {
|
|
real: evenRealInfo,
|
|
imag: evenImagInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const oddComplex = (0, _tfjsCore.backend_util).complexWithOddIndex(data);
|
|
const oddRealVals = oddComplex.real;
|
|
const oddImagVals = oddComplex.imag;
|
|
const oddShape = [
|
|
oddRealVals.length
|
|
];
|
|
const oddRealInfo = cpuBackend.makeTensorInfo(oddShape, "float32", oddRealVals);
|
|
const oddImagInfo = cpuBackend.makeTensorInfo(oddShape, "float32", oddImagVals);
|
|
const oddTensorInfo = (0, _complex.complex)({
|
|
inputs: {
|
|
real: oddRealInfo,
|
|
imag: oddImagInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
// Recursive call for half part of original input.
|
|
const $evenComplex = fftRadix2(evenRealVals, evenImagVals, half, inverse, cpuBackend);
|
|
const $evenRealVals = $evenComplex.real;
|
|
const $evenImagVals = $evenComplex.imag;
|
|
const $evenShape = [
|
|
$evenRealVals.length
|
|
];
|
|
const $evenRealInfo = cpuBackend.makeTensorInfo($evenShape, "float32", $evenRealVals);
|
|
const $evenImagInfo = cpuBackend.makeTensorInfo($evenShape, "float32", $evenImagVals);
|
|
const $evenTensorInfo = (0, _complex.complex)({
|
|
inputs: {
|
|
real: $evenRealInfo,
|
|
imag: $evenImagInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const $oddComplex = fftRadix2(oddRealVals, oddImagVals, half, inverse, cpuBackend);
|
|
const $oddRealVals = $oddComplex.real;
|
|
const $oddImagVals = $oddComplex.imag;
|
|
const $oddShape = [
|
|
$oddRealVals.length
|
|
];
|
|
const $oddRealInfo = cpuBackend.makeTensorInfo($oddShape, "float32", $oddRealVals);
|
|
const $oddImagInfo = cpuBackend.makeTensorInfo($oddShape, "float32", $oddImagVals);
|
|
const $oddTensorInfo = (0, _complex.complex)({
|
|
inputs: {
|
|
real: $oddRealInfo,
|
|
imag: $oddImagInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const e = (0, _tfjsCore.backend_util).exponents(size, inverse);
|
|
const eShape = [
|
|
e.real.length
|
|
];
|
|
const eRealInfo = cpuBackend.makeTensorInfo(eShape, "float32", e.real);
|
|
const eImagInfo = cpuBackend.makeTensorInfo(eShape, "float32", e.imag);
|
|
const complexInfo = (0, _complex.complex)({
|
|
inputs: {
|
|
real: eRealInfo,
|
|
imag: eImagInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const exponentInfo = (0, _multiply.multiply)({
|
|
inputs: {
|
|
a: complexInfo,
|
|
b: $oddTensorInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const addPart = (0, _add.add)({
|
|
inputs: {
|
|
a: $evenTensorInfo,
|
|
b: exponentInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const subPart = (0, _sub.sub)({
|
|
inputs: {
|
|
a: $evenTensorInfo,
|
|
b: exponentInfo
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const addPartReal = (0, _real.real)({
|
|
inputs: {
|
|
input: addPart
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const subPartReal = (0, _real.real)({
|
|
inputs: {
|
|
input: subPart
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const addPartImag = (0, _imag.imag)({
|
|
inputs: {
|
|
input: addPart
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const subPartImag = (0, _imag.imag)({
|
|
inputs: {
|
|
input: subPart
|
|
},
|
|
backend: cpuBackend
|
|
});
|
|
const $real = (0, _concat.concat)({
|
|
inputs: [
|
|
addPartReal,
|
|
subPartReal
|
|
],
|
|
backend: cpuBackend,
|
|
attrs: {
|
|
axis: 0
|
|
}
|
|
});
|
|
const $imag = (0, _concat.concat)({
|
|
inputs: [
|
|
addPartImag,
|
|
subPartImag
|
|
],
|
|
backend: cpuBackend,
|
|
attrs: {
|
|
axis: 0
|
|
}
|
|
});
|
|
const $realVals = cpuBackend.data.get($real.dataId).values;
|
|
const $imagVals = cpuBackend.data.get($imag.dataId).values;
|
|
cpuBackend.disposeIntermediateTensorInfo(evenRealInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(evenImagInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(evenTensorInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(oddRealInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(oddImagInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(oddTensorInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo($evenRealInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo($evenImagInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo($evenTensorInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo($oddRealInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo($oddImagInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo($oddTensorInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(eRealInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(eImagInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(complexInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(exponentInfo);
|
|
cpuBackend.disposeIntermediateTensorInfo(addPart);
|
|
cpuBackend.disposeIntermediateTensorInfo(subPart);
|
|
cpuBackend.disposeIntermediateTensorInfo(addPartReal);
|
|
cpuBackend.disposeIntermediateTensorInfo(addPartImag);
|
|
cpuBackend.disposeIntermediateTensorInfo(subPartReal);
|
|
cpuBackend.disposeIntermediateTensorInfo(subPartImag);
|
|
cpuBackend.disposeIntermediateTensorInfo($real);
|
|
cpuBackend.disposeIntermediateTensorInfo($imag);
|
|
return {
|
|
real: $realVals,
|
|
imag: $imagVals
|
|
};
|
|
}
|
|
// Calculate fourier transform by multplying sinusoid matrix.
|
|
function 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 = (0, _tfjsCore.backend_util).exponent(r * c, size, inverse);
|
|
const term = (0, _tfjsCore.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;
|
|
}
|
|
(0, _tfjsCore.backend_util).assignToTypedArray(ret, real, imag, r);
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../kernels/Add":"dippY","../kernels/Complex":"3DPmh","../kernels/Concat":"iYEAT","../kernels/Identity":"btREJ","../kernels/Imag":"af3Tx","../kernels/Multiply":"FrRi2","../kernels/Real":"eZ7aJ","../kernels/RealDiv":"9Ly75","../kernels/Slice":"9L9GN","../kernels/Sub":"4DByI","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9Ly75":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "realDivImpl", ()=>realDivImpl);
|
|
parcelHelpers.export(exports, "div", ()=>div);
|
|
parcelHelpers.export(exports, "realDivConfig", ()=>realDivConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const realDivImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a / b);
|
|
const div = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.RealDiv), realDivImpl);
|
|
const realDivConfig = {
|
|
kernelName: (0, _tfjsCore.RealDiv),
|
|
backendName: "cpu",
|
|
kernelFunc: div
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4BMgR":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fill", ()=>fill);
|
|
parcelHelpers.export(exports, "fillConfig", ()=>fillConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function fill(args) {
|
|
const { backend, attrs } = args;
|
|
const { shape, value, dtype } = attrs;
|
|
const $dtype = dtype || (0, _tfjsCore.util).inferDtype(value);
|
|
const values = (0, _tfjsCore.util).getArrayFromDType($dtype, (0, _tfjsCore.util).sizeFromShape(shape));
|
|
fillValues(values, value, $dtype);
|
|
return backend.makeTensorInfo(shape, $dtype, values);
|
|
}
|
|
const fillConfig = {
|
|
kernelName: (0, _tfjsCore.Fill),
|
|
backendName: "cpu",
|
|
kernelFunc: fill
|
|
};
|
|
function fillValues(values, value, dtype) {
|
|
if (dtype === "string") values.fill(value);
|
|
else values.fill(value);
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"8d8ZF":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "flipLeftRightConfig", ()=>flipLeftRightConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const flipLeftRightConfig = {
|
|
kernelName: (0, _tfjsCore.FlipLeftRight),
|
|
backendName: "cpu",
|
|
kernelFunc: ({ inputs, attrs, backend })=>{
|
|
const { image } = inputs;
|
|
const cpuBackend = backend;
|
|
const output = (0, _tfjsCore.util).getTypedArrayFromDType(image.dtype, (0, _tfjsCore.util).sizeFromShape(image.shape));
|
|
const [batch, imageHeight, imageWidth, numChannels] = image.shape;
|
|
const imageVals = cpuBackend.data.get(image.dataId).values;
|
|
for(let batchIdx = 0; batchIdx < batch; batchIdx++){
|
|
const batchOffset = batchIdx * imageWidth * imageHeight * numChannels;
|
|
for(let row = 0; row < imageHeight; row++){
|
|
const rowOffset = row * (imageWidth * numChannels);
|
|
for(let col = 0; col < imageWidth; col++){
|
|
const colOffset = col * numChannels;
|
|
for(let channel = 0; channel < numChannels; channel++){
|
|
const coordX = Math.round(imageWidth - col - 1);
|
|
const outIdx = batchOffset + rowOffset + colOffset + channel;
|
|
let outputValue = imageVals[outIdx];
|
|
// If the coordinate position falls within the image boundaries...
|
|
if (coordX >= 0 && coordX < imageWidth) {
|
|
// set the output to the image value at the coordinate position.
|
|
const rotatedColOffset = coordX * numChannels;
|
|
const imageIdx = batchOffset + rowOffset + rotatedColOffset + channel;
|
|
outputValue = imageVals[imageIdx];
|
|
}
|
|
output[outIdx] = outputValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const dataId = cpuBackend.write(output, image.shape, image.dtype);
|
|
return {
|
|
dataId,
|
|
shape: image.shape,
|
|
dtype: image.dtype
|
|
};
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1OWT7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fusedConv2D", ()=>fusedConv2D);
|
|
parcelHelpers.export(exports, "fusedConv2DConfig", ()=>fusedConv2DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fusedUtils = require("../utils/fused_utils");
|
|
var _add = require("./Add");
|
|
var _conv2D = require("./Conv2D");
|
|
var _reshape = require("./Reshape");
|
|
function fusedConv2D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter, bias, preluActivationWeights } = inputs;
|
|
const { strides, pad, dataFormat, dilations, dimRoundingMode, activation, leakyreluAlpha } = attrs;
|
|
let result = (0, _conv2D.conv2D)({
|
|
inputs: {
|
|
x,
|
|
filter
|
|
},
|
|
backend,
|
|
attrs: {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dilations,
|
|
dimRoundingMode
|
|
}
|
|
});
|
|
if (bias) {
|
|
const resultOld = result;
|
|
// For NCHW format, if bias is a 1-D tensor, it is supposed to be aligned
|
|
// to the channel of the conv2d's result; if the bias is a scalar, the
|
|
// bias_add is computed as if the bias was broadcasted to the shape of the
|
|
// conv2d's result.
|
|
if (dataFormat === "NCHW" && bias.shape.length === 1 && bias.shape[0] !== 1) {
|
|
const reshapedBias = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: bias
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
bias.shape[0],
|
|
1,
|
|
1
|
|
]
|
|
}
|
|
});
|
|
result = (0, _add.add)({
|
|
inputs: {
|
|
a: result,
|
|
b: reshapedBias
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(reshapedBias);
|
|
} else // This condition handles NHWC and NCHW (scalar case). The only other case
|
|
// for NCHW (1D case) is handled above.
|
|
result = (0, _add.add)({
|
|
inputs: {
|
|
a: result,
|
|
b: bias
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(resultOld);
|
|
}
|
|
if (activation) {
|
|
const resultOld = result;
|
|
// For NCHW format, if PReLu activation weights is a 1-D tensor, it is
|
|
// supposed to be aligned with the channel of the conv2d's result. For other
|
|
// cases, whether NCHW or NHWC data format, the conv2d result is
|
|
// already aligned with the activation weights.
|
|
if (dataFormat === "NCHW" && activation === "prelu" && preluActivationWeights.shape.length === 1 && preluActivationWeights.shape[0] !== 1) {
|
|
const reshapedAlpha = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: preluActivationWeights
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
preluActivationWeights.shape[0],
|
|
1,
|
|
1
|
|
]
|
|
}
|
|
});
|
|
result = (0, _fusedUtils.applyActivation)(backend, result, activation, reshapedAlpha, leakyreluAlpha);
|
|
backend.disposeIntermediateTensorInfo(reshapedAlpha);
|
|
} else result = (0, _fusedUtils.applyActivation)(backend, result, activation, preluActivationWeights, leakyreluAlpha);
|
|
backend.disposeIntermediateTensorInfo(resultOld);
|
|
}
|
|
return result;
|
|
}
|
|
const fusedConv2DConfig = {
|
|
kernelName: (0, _tfjsCore.FusedConv2D),
|
|
backendName: "cpu",
|
|
kernelFunc: fusedConv2D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/fused_utils":"6DUEF","./Add":"dippY","./Conv2D":"4bj3X","./Reshape":"9350i","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5SkmJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "fusedDepthwiseConv2D", ()=>fusedDepthwiseConv2D);
|
|
parcelHelpers.export(exports, "fusedDepthwiseConv2DConfig", ()=>fusedDepthwiseConv2DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fusedUtils = require("../utils/fused_utils");
|
|
var _add = require("./Add");
|
|
var _depthwiseConv2DNative = require("./DepthwiseConv2dNative");
|
|
function fusedDepthwiseConv2D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, filter, bias, preluActivationWeights } = inputs;
|
|
const { strides, pad, dataFormat, dilations, dimRoundingMode, activation, leakyreluAlpha } = attrs;
|
|
let result = (0, _depthwiseConv2DNative.depthwiseConv2dNative)({
|
|
inputs: {
|
|
x,
|
|
filter
|
|
},
|
|
backend,
|
|
attrs: {
|
|
strides,
|
|
pad,
|
|
dataFormat,
|
|
dilations,
|
|
dimRoundingMode
|
|
}
|
|
});
|
|
if (bias) {
|
|
const oldResult = result;
|
|
result = (0, _add.add)({
|
|
inputs: {
|
|
a: result,
|
|
b: bias
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(oldResult);
|
|
}
|
|
if (activation) {
|
|
const oldResult = result;
|
|
result = (0, _fusedUtils.applyActivation)(backend, result, activation, preluActivationWeights, leakyreluAlpha);
|
|
backend.disposeIntermediateTensorInfo(oldResult);
|
|
}
|
|
return result;
|
|
}
|
|
const fusedDepthwiseConv2DConfig = {
|
|
kernelName: (0, _tfjsCore.FusedDepthwiseConv2D),
|
|
backendName: "cpu",
|
|
kernelFunc: fusedDepthwiseConv2D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/fused_utils":"6DUEF","./Add":"dippY","./DepthwiseConv2dNative":"2iRpa","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6Owm3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gatherNd", ()=>gatherNd);
|
|
parcelHelpers.export(exports, "gatherNdConfig", ()=>gatherNdConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _gatherNdImpl = require("./GatherNd_Impl");
|
|
function gatherNd(args) {
|
|
const { inputs, backend } = args;
|
|
const { params, indices } = inputs;
|
|
const paramsSize = (0, _tfjsCore.util).sizeFromShape(params.shape);
|
|
const indicesShape = indices.shape;
|
|
const sliceRank = indicesShape[indicesShape.length - 1];
|
|
const [resultShape, numSlices, sliceSize, strides] = (0, _tfjsCore.backend_util).prepareAndValidate(params, indices);
|
|
if (numSlices === 0) return backend.makeTensorInfo(resultShape, params.dtype, []);
|
|
const indicesData = backend.data.get(indices.dataId).values;
|
|
const paramsBuf = backend.bufferSync(params);
|
|
const outBuf = (0, _gatherNdImpl.gatherNdImpl)(indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize, strides, params.shape, paramsSize);
|
|
return backend.makeTensorInfo(resultShape, params.dtype, outBuf.values);
|
|
}
|
|
const gatherNdConfig = {
|
|
kernelName: (0, _tfjsCore.GatherNd),
|
|
backendName: "cpu",
|
|
kernelFunc: gatherNd
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./GatherNd_Impl":"klZow","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dUokB":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "gatherV2", ()=>gatherV2);
|
|
parcelHelpers.export(exports, "gatherV2Config", ()=>gatherV2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _gatherV2Impl = require("./GatherV2_impl");
|
|
var _reshape = require("./Reshape");
|
|
function gatherV2(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, indices } = inputs;
|
|
const { axis, batchDims } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x,
|
|
indices
|
|
], "gatherV2");
|
|
// Throw error when any index is out of bound.
|
|
const parsedAxis = (0, _tfjsCore.util).parseAxisParam(axis, x.shape)[0];
|
|
const indicesVals = backend.data.get(indices.dataId).values;
|
|
const axisDim = x.shape[parsedAxis];
|
|
for(let i = 0; i < indicesVals.length; ++i){
|
|
const index = indicesVals[i];
|
|
(0, _tfjsCore.util).assert(index <= axisDim - 1 && index >= 0, ()=>`GatherV2: the index value ${index} is not in [0, ${axisDim - 1}]`);
|
|
}
|
|
let $batchDims = batchDims;
|
|
if (batchDims == null) $batchDims = 0;
|
|
const indicesSize = (0, _tfjsCore.util).sizeFromShape(indices.shape);
|
|
const shapeInfo = (0, _tfjsCore.backend_util).segment_util.collectGatherOpShapeInfo(x, indices, parsedAxis, $batchDims);
|
|
const flattenX = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
shapeInfo.batchSize,
|
|
shapeInfo.outerSize,
|
|
shapeInfo.dimSize,
|
|
shapeInfo.sliceSize
|
|
]
|
|
}
|
|
});
|
|
const flattenIndex = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: indices
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
shapeInfo.batchSize,
|
|
indicesSize / shapeInfo.batchSize
|
|
]
|
|
}
|
|
});
|
|
const flattenOutputShape = [
|
|
shapeInfo.batchSize,
|
|
shapeInfo.outerSize,
|
|
indicesSize / shapeInfo.batchSize,
|
|
shapeInfo.sliceSize
|
|
];
|
|
const indicesBuf = backend.bufferSync(flattenIndex);
|
|
const xBuf = backend.bufferSync(flattenX);
|
|
const outBuf = (0, _gatherV2Impl.gatherV2Impl)(xBuf, indicesBuf, flattenOutputShape);
|
|
backend.disposeIntermediateTensorInfo(flattenX);
|
|
backend.disposeIntermediateTensorInfo(flattenIndex);
|
|
return backend.makeTensorInfo(shapeInfo.outputShape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const gatherV2Config = {
|
|
kernelName: (0, _tfjsCore.GatherV2),
|
|
backendName: "cpu",
|
|
kernelFunc: gatherV2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./GatherV2_impl":"5y26k","./Reshape":"9350i","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hHvJu":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "ifft", ()=>ifft);
|
|
parcelHelpers.export(exports, "ifftConfig", ()=>ifftConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _fftUtils = require("../utils/fft_utils");
|
|
var _reshape = require("./Reshape");
|
|
function ifft(args) {
|
|
const { inputs, backend } = args;
|
|
const { input } = inputs;
|
|
const inputSize = (0, _tfjsCore.util).sizeFromShape(input.shape);
|
|
// Collapse all outer dimensions to a single batch dimension.
|
|
const innerDimensionSize = input.shape[input.shape.length - 1];
|
|
const batch = inputSize / innerDimensionSize;
|
|
const input2D = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: input
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: [
|
|
batch,
|
|
innerDimensionSize
|
|
]
|
|
}
|
|
});
|
|
const result = (0, _fftUtils.fftBatch)(input2D, true, backend);
|
|
const resultReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: input.shape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(input2D);
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
return resultReshaped;
|
|
}
|
|
const ifftConfig = {
|
|
kernelName: (0, _tfjsCore.IFFT),
|
|
backendName: "cpu",
|
|
kernelFunc: ifft
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/fft_utils":"8ziy5","./Reshape":"9350i","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"a8CWT":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isFinite", ()=>isFinite);
|
|
parcelHelpers.export(exports, "isFiniteConfig", ()=>isFiniteConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const isFinite = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.IsFinite), (xi)=>Number.isFinite(xi) ? 1 : 0, "bool");
|
|
const isFiniteConfig = {
|
|
kernelName: (0, _tfjsCore.IsFinite),
|
|
backendName: "cpu",
|
|
kernelFunc: isFinite
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"342Gs":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isInf", ()=>isInf);
|
|
parcelHelpers.export(exports, "isInfConfig", ()=>isInfConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const isInf = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.IsInf), (xi)=>Math.abs(xi) === Infinity ? 1 : 0, "bool");
|
|
const isInfConfig = {
|
|
kernelName: (0, _tfjsCore.IsInf),
|
|
backendName: "cpu",
|
|
kernelFunc: isInf
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gKXUy":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "isNaN", ()=>isNaN);
|
|
parcelHelpers.export(exports, "isNaNConfig", ()=>isNaNConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const isNaN = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.IsNan), (xi)=>Number.isNaN(xi) ? 1 : 0, "bool");
|
|
const isNaNConfig = {
|
|
kernelName: (0, _tfjsCore.IsNan),
|
|
backendName: "cpu",
|
|
kernelFunc: isNaN
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3aMpD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "linSpace", ()=>linSpace);
|
|
parcelHelpers.export(exports, "linSpaceConfig", ()=>linSpaceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _linSpaceImpl = require("./LinSpace_impl");
|
|
function linSpace(args) {
|
|
const { backend, attrs } = args;
|
|
const { start, stop, num } = attrs;
|
|
const outVals = (0, _linSpaceImpl.linSpaceImpl)(start, stop, num);
|
|
return backend.makeTensorInfo([
|
|
outVals.length
|
|
], "float32", outVals);
|
|
}
|
|
const linSpaceConfig = {
|
|
kernelName: (0, _tfjsCore.LinSpace),
|
|
backendName: "cpu",
|
|
kernelFunc: linSpace
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./LinSpace_impl":"4tRcP","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bNfse":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "log1p", ()=>log1p);
|
|
parcelHelpers.export(exports, "log1pConfig", ()=>log1pConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const log1p = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Log1p), (xi)=>Math.log1p(xi));
|
|
const log1pConfig = {
|
|
kernelName: (0, _tfjsCore.Log1p),
|
|
backendName: "cpu",
|
|
kernelFunc: log1p
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9q52j":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalAndImpl", ()=>logicalAndImpl);
|
|
parcelHelpers.export(exports, "logicalAnd", ()=>logicalAnd);
|
|
parcelHelpers.export(exports, "logicalAndConfig", ()=>logicalAndConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const logicalAndImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a && b);
|
|
const logicalAnd = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.LogicalAnd), logicalAndImpl, null, "bool");
|
|
const logicalAndConfig = {
|
|
kernelName: (0, _tfjsCore.LogicalAnd),
|
|
backendName: "cpu",
|
|
kernelFunc: logicalAnd
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"929wA":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalNot", ()=>logicalNot);
|
|
parcelHelpers.export(exports, "logicalNotConfig", ()=>logicalNotConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const logicalNot = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.LogicalNot), (xi)=>xi ? 0 : 1, "bool");
|
|
const logicalNotConfig = {
|
|
kernelName: (0, _tfjsCore.LogicalNot),
|
|
backendName: "cpu",
|
|
kernelFunc: logicalNot
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4bpjj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "logicalOrImpl", ()=>logicalOrImpl);
|
|
parcelHelpers.export(exports, "logicalOr", ()=>logicalOr);
|
|
parcelHelpers.export(exports, "logicalOrConfig", ()=>logicalOrConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const logicalOrImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>a || b);
|
|
const logicalOr = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.LogicalOr), logicalOrImpl, null, "bool");
|
|
const logicalOrConfig = {
|
|
kernelName: (0, _tfjsCore.LogicalOr),
|
|
backendName: "cpu",
|
|
kernelFunc: logicalOr
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1ZDWc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "lRN", ()=>lRN);
|
|
parcelHelpers.export(exports, "LRNConfig", ()=>LRNConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function lRN(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { depthRadius, bias, alpha, beta } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "LRN");
|
|
const channels = x.shape[3];
|
|
const maxD = channels - 1;
|
|
const xValues = backend.data.get(x.dataId).values;
|
|
const size = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
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 backend.makeTensorInfo(x.shape, x.dtype, result);
|
|
}
|
|
const LRNConfig = {
|
|
kernelName: (0, _tfjsCore.LRN),
|
|
backendName: "cpu",
|
|
kernelFunc: lRN
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"01nUa":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "lRNGrad", ()=>lRNGrad);
|
|
parcelHelpers.export(exports, "LRNGradConfig", ()=>LRNGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function lRNGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, y, dy } = inputs;
|
|
const { depthRadius, bias, alpha, beta } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(dy, "LRNGrad");
|
|
const dySize = (0, _tfjsCore.util).sizeFromShape(dy.shape);
|
|
const channels = dy.shape[3];
|
|
const dyValues = backend.data.get(dy.dataId).values;
|
|
const xValues = backend.data.get(x.dataId).values;
|
|
const yValues = backend.data.get(y.dataId).values;
|
|
const result = new Float32Array(dySize);
|
|
const size = dySize;
|
|
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(xValues[k], 2);
|
|
norm = alpha * norm + bias;
|
|
for(let k = depthBegin; k < depthEnd; k++){
|
|
let dyi = -2 * alpha * beta * xValues[k] * yValues[offset] / norm;
|
|
if (offset === k) dyi += Math.pow(norm, -beta);
|
|
dyi *= dyValues[offset];
|
|
result[k] += dyi;
|
|
}
|
|
}
|
|
return backend.makeTensorInfo(dy.shape, x.dtype, result);
|
|
}
|
|
const LRNGradConfig = {
|
|
kernelName: (0, _tfjsCore.LRNGrad),
|
|
backendName: "cpu",
|
|
kernelFunc: lRNGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ceCEC":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "max", ()=>max);
|
|
parcelHelpers.export(exports, "maxConfig", ()=>maxConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _maxImpl = require("./Max_impl");
|
|
var _transposeImpl = require("./Transpose_impl");
|
|
function max(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { reductionIndices, keepDims } = attrs;
|
|
const cpuBackend = backend;
|
|
let xShape = x.shape;
|
|
const xRank = xShape.length;
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(reductionIndices, xShape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.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 = (0, _transposeImpl.transposeImpl)(xVals, xShape, x.dtype, permutedAxes, newShape);
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, xRank);
|
|
xShape = newShape;
|
|
}
|
|
(0, _cpuUtil.assertNotComplex)(x, "max");
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("max", axes, xRank);
|
|
const [maxOutShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(xShape, axes);
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const result = (0, _maxImpl.maxImpl)(xVals, reduceSize, maxOutShape, x.dtype);
|
|
const dataId = cpuBackend.write(result, maxOutShape, x.dtype);
|
|
let outShape = maxOutShape;
|
|
if (keepDims) {
|
|
// reshape
|
|
const newShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(maxOutShape, origAxes);
|
|
outShape = newShape;
|
|
}
|
|
return {
|
|
dataId,
|
|
shape: outShape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
const maxConfig = {
|
|
kernelName: (0, _tfjsCore.Max),
|
|
backendName: "cpu",
|
|
kernelFunc: max
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Max_impl":"6BNe1","./Transpose_impl":"2fFZe","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2HK6O":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPool", ()=>maxPool);
|
|
parcelHelpers.export(exports, "maxPoolConfig", ()=>maxPoolConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _poolUtils = require("../utils/pool_utils");
|
|
var _identity = require("./Identity");
|
|
function maxPool(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "maxPool");
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
const dilations = 1;
|
|
(0, _tfjsCore.util).assert((0, _tfjsCore.backend_util).eitherStridesOrDilationsAreOne(strides, dilations), ()=>"Error in maxPool: Either strides or dilations must be 1. " + `Got strides ${strides} and dilations '${dilations}'`);
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
|
|
let res;
|
|
if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 && (0, _tfjsCore.util).arraysEqual(convInfo.inShape, convInfo.outShape)) res = (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
else {
|
|
const xValues = backend.data.get(x.dataId).values;
|
|
const strides = (0, _tfjsCore.util).computeStrides(x.shape);
|
|
const buffer = (0, _poolUtils.pool)(xValues, x.shape, x.dtype, strides, convInfo, "max");
|
|
res = backend.makeTensorInfo(convInfo.outShape, x.dtype, buffer.values);
|
|
}
|
|
return res;
|
|
}
|
|
const maxPoolConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPool),
|
|
backendName: "cpu",
|
|
kernelFunc: maxPool
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../utils/pool_utils":"fzyhw","./Identity":"btREJ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"guFsS":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPool3D", ()=>maxPool3D);
|
|
parcelHelpers.export(exports, "maxPool3DConfig", ()=>maxPool3DConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _poolUtils = require("../utils/pool_utils");
|
|
function maxPool3D(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { filterSize, strides, pad, dimRoundingMode, dataFormat } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "maxPool3d");
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool3DInfo(x.shape, filterSize, strides, 1 /* dilations */ , pad, dimRoundingMode, dataFormat);
|
|
const xValues = backend.data.get(x.dataId).values;
|
|
const outBuf = (0, _poolUtils.pool3d)(xValues, x.shape, x.dtype, (0, _tfjsCore.util).computeStrides(x.shape), convInfo, "max");
|
|
return backend.makeTensorInfo(outBuf.shape, "float32", outBuf.values);
|
|
}
|
|
const maxPool3DConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPool3D),
|
|
backendName: "cpu",
|
|
kernelFunc: maxPool3D
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../utils/pool_utils":"fzyhw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bsOhi":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPool3DGrad", ()=>maxPool3DGrad);
|
|
parcelHelpers.export(exports, "maxPool3DGradConfig", ()=>maxPool3DGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _poolUtils = require("../utils/pool_utils");
|
|
function maxPool3DGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, input } = inputs;
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy,
|
|
input
|
|
], "maxPool3DGrad");
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool3DInfo(input.shape, filterSize, strides, 1 /* dilations */ , pad, dimRoundingMode);
|
|
const inputBuf = backend.bufferSync(input);
|
|
const maxPosBuf = (0, _poolUtils.maxPool3dPositions)(inputBuf, 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 = (0, _tfjsCore.buffer)(input.shape, "float32");
|
|
const dyBuf = backend.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 backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
|
|
}
|
|
const maxPool3DGradConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPool3DGrad),
|
|
backendName: "cpu",
|
|
kernelFunc: maxPool3DGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../utils/pool_utils":"fzyhw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"esvnZ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPoolGrad", ()=>maxPoolGrad);
|
|
parcelHelpers.export(exports, "maxPoolGradConfig", ()=>maxPoolGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _poolUtils = require("../utils/pool_utils");
|
|
function maxPoolGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { dy, input, output } = inputs;
|
|
const x = input;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
input,
|
|
output
|
|
], "maxPoolGrad");
|
|
const { filterSize, strides, pad, dimRoundingMode } = attrs;
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, 1 /* dilations */ , pad, dimRoundingMode);
|
|
const xValues = backend.data.get(x.dataId).values;
|
|
const maxPosBuf = (0, _tfjsCore.buffer)(convInfo.outShape, x.dtype, (0, _poolUtils.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 = (0, _tfjsCore.buffer)(x.shape, "float32");
|
|
const dyData = backend.data.get(dy.dataId).values;
|
|
const dyBuf = (0, _tfjsCore.buffer)(dy.shape, "float32", dyData);
|
|
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 backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
|
|
}
|
|
const maxPoolGradConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPoolGrad),
|
|
backendName: "cpu",
|
|
kernelFunc: maxPoolGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","../utils/pool_utils":"fzyhw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aBn34":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPoolWithArgmaxConfig", ()=>maxPoolWithArgmaxConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _maxPoolWithArgmaxImpl = require("./MaxPoolWithArgmax_impl");
|
|
const maxPoolWithArgmaxConfig = {
|
|
kernelName: (0, _tfjsCore.MaxPoolWithArgmax),
|
|
backendName: "cpu",
|
|
kernelFunc: ({ inputs, attrs, backend })=>{
|
|
const { x } = inputs;
|
|
const { filterSize, strides, pad, includeBatchInIndex } = attrs;
|
|
const cpuBackend = backend;
|
|
(0, _cpuUtil.assertNotComplex)(x, "MaxPoolWithArgmax");
|
|
const values = cpuBackend.data.get(x.dataId).values;
|
|
const convInfo = (0, _tfjsCore.backend_util).computePool2DInfo(x.shape, filterSize, strides, [
|
|
1,
|
|
1
|
|
], pad);
|
|
const [pooled, indexes] = (0, _maxPoolWithArgmaxImpl.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"
|
|
}
|
|
];
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./MaxPoolWithArgmax_impl":"7OAHL","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7OAHL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "maxPoolWithArgmaxImpl", ()=>maxPoolWithArgmaxImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _poolUtils = require("../utils/pool_utils");
|
|
function maxPoolWithArgmaxImpl(xValues, xShape, dtype, includeBatchInIndex, convInfo) {
|
|
const strides = (0, _tfjsCore.util).computeStrides(xShape);
|
|
const maxPools = (0, _poolUtils.pool)(xValues, xShape, dtype, strides, convInfo, "max");
|
|
const maxPositions = (0, _poolUtils.maxPoolPositions)(xValues, xShape, dtype, convInfo, true, includeBatchInIndex);
|
|
return [
|
|
maxPools.values,
|
|
maxPositions.values
|
|
];
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/pool_utils":"fzyhw","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hu1l4":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mean", ()=>mean);
|
|
parcelHelpers.export(exports, "meanConfig", ()=>meanConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cast = require("./Cast");
|
|
var _realDiv = require("./RealDiv");
|
|
var _sum = require("./Sum");
|
|
function mean(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
const axes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
const shapes = (0, _tfjsCore.backend_util).computeOutAndReduceShapes(x.shape, axes);
|
|
const reduceShape = shapes[1];
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const toDispose = [];
|
|
const reduceSizeScalar = backend.makeTensorInfo([], "float32", new Float32Array([
|
|
reduceSize
|
|
]));
|
|
toDispose.push(reduceSizeScalar);
|
|
const $x = (0, _cast.cast)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dtype: "float32"
|
|
}
|
|
});
|
|
toDispose.push($x);
|
|
const res = (0, _realDiv.div)({
|
|
inputs: {
|
|
a: $x,
|
|
b: reduceSizeScalar
|
|
},
|
|
backend
|
|
});
|
|
toDispose.push(res);
|
|
const result = (0, _sum.sum)({
|
|
inputs: {
|
|
x: res
|
|
},
|
|
backend,
|
|
attrs: {
|
|
axis,
|
|
keepDims
|
|
}
|
|
});
|
|
toDispose.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return result;
|
|
}
|
|
const meanConfig = {
|
|
kernelName: (0, _tfjsCore.Mean),
|
|
backendName: "cpu",
|
|
kernelFunc: mean
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Cast":"fAtIw","./RealDiv":"9Ly75","./Sum":"6gbbV","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"h3WES":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "min", ()=>min);
|
|
parcelHelpers.export(exports, "minConfig", ()=>minConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function min(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { axis, keepDims } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "min");
|
|
const origAxes = (0, _tfjsCore.util).parseAxisParam(axis, x.shape);
|
|
let axes = origAxes;
|
|
const permutedAxes = (0, _tfjsCore.backend_util).getAxesPermutation(axes, x.shape.length);
|
|
let $x = x;
|
|
if (permutedAxes != null) {
|
|
$x = (0, _transpose.transpose)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
perm: permutedAxes
|
|
}
|
|
});
|
|
axes = (0, _tfjsCore.backend_util).getInnerMostAxes(axes.length, x.shape.length);
|
|
}
|
|
(0, _tfjsCore.backend_util).assertAxesAreInnerMostDims("min", axes, $x.shape.length);
|
|
const [outShape, reduceShape] = (0, _tfjsCore.backend_util).computeOutAndReduceShapes($x.shape, axes);
|
|
const reduceSize = (0, _tfjsCore.util).sizeFromShape(reduceShape);
|
|
const vals = (0, _tfjsCore.util).makeZerosTypedArray((0, _tfjsCore.util).sizeFromShape(outShape), $x.dtype);
|
|
const aVals = backend.data.get($x.dataId).values;
|
|
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 (Number.isNaN(value) || value < min) min = value;
|
|
}
|
|
vals[i] = min;
|
|
}
|
|
if (permutedAxes != null) backend.disposeIntermediateTensorInfo($x);
|
|
const result = backend.makeTensorInfo(outShape, $x.dtype, vals);
|
|
if (keepDims) {
|
|
const expandedShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(outShape, origAxes);
|
|
const reshapedResult = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: result
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: expandedShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(result);
|
|
return reshapedResult;
|
|
}
|
|
return result;
|
|
}
|
|
const minConfig = {
|
|
kernelName: (0, _tfjsCore.Min),
|
|
backendName: "cpu",
|
|
kernelFunc: min
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Reshape":"9350i","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1HbpJ":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "mirrorPad", ()=>mirrorPad);
|
|
parcelHelpers.export(exports, "mirrorPadConfig", ()=>mirrorPadConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function mirrorPad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { paddings, mode } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "mirrorPad");
|
|
const outShape = paddings.map((p, i)=>p[0] + x.shape[i] + p[1]);
|
|
const start = paddings.map((p)=>p[0]);
|
|
const end = paddings.map((p, i)=>p[0] + x.shape[i]);
|
|
const offset = mode === "reflect" ? 0 : 1;
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const xRank = x.shape.length;
|
|
const xStrides = (0, _tfjsCore.util).computeStrides(x.shape);
|
|
const resultSize = (0, _tfjsCore.util).sizeFromShape(outShape);
|
|
const resultRank = outShape.length;
|
|
const resultStrides = (0, _tfjsCore.util).computeStrides(outShape);
|
|
const resVals = (0, _tfjsCore.util).getTypedArrayFromDType(x.dtype, resultSize);
|
|
for(let i = 0; i < resultSize; i++){
|
|
let coords = (0, _tfjsCore.util).indexToLoc(i, resultRank, resultStrides);
|
|
for(let i = 0; i < resultRank; i++){
|
|
if (coords[i] < start[i]) coords[i] = start[i] * 2 - coords[i] - offset;
|
|
else if (coords[i] >= end[i]) coords[i] = (end[i] - 1) * 2 - coords[i] + offset;
|
|
}
|
|
coords = coords.map((c, i)=>c - start[i]);
|
|
const inIndex = (0, _tfjsCore.util).locToIndex(coords, xRank, xStrides);
|
|
resVals[i] = xVals[inIndex];
|
|
}
|
|
const outId = backend.write(resVals, outShape, x.dtype);
|
|
return {
|
|
dataId: outId,
|
|
shape: outShape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
const mirrorPadConfig = {
|
|
kernelName: (0, _tfjsCore.MirrorPad),
|
|
backendName: "cpu",
|
|
kernelFunc: mirrorPad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iD4b6":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "modImpl", ()=>modImpl);
|
|
parcelHelpers.export(exports, "mod", ()=>mod);
|
|
parcelHelpers.export(exports, "modConfig", ()=>modConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const modImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((aValue, bValue)=>{
|
|
const rem = aValue % bValue;
|
|
if (aValue < 0 && bValue < 0 || aValue >= 0 && bValue >= 0) return rem;
|
|
else return (rem + bValue) % bValue;
|
|
});
|
|
const mod = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Mod), modImpl);
|
|
const modConfig = {
|
|
kernelName: (0, _tfjsCore.Mod),
|
|
backendName: "cpu",
|
|
kernelFunc: mod
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dy4Sw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "multinomial", ()=>multinomial);
|
|
parcelHelpers.export(exports, "multinomialConfig", ()=>multinomialConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _seedrandom = require("seedrandom");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _softmax = require("./Softmax");
|
|
function multinomial(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { logits } = inputs;
|
|
const { numSamples, seed, normalized } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(logits, "multinomial");
|
|
const probabilities = normalized ? logits : (0, _softmax.softmax)({
|
|
inputs: {
|
|
logits
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dim: -1
|
|
}
|
|
});
|
|
const batchSize = probabilities.shape[0];
|
|
const numEvents = probabilities.shape[1];
|
|
const probVals = backend.data.get(probabilities.dataId).values;
|
|
const resShape = [
|
|
batchSize,
|
|
numSamples
|
|
];
|
|
const resVals = (0, _tfjsCore.util).makeZerosTypedArray((0, _tfjsCore.util).sizeFromShape(resShape), "int32");
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
if (!normalized) backend.disposeIntermediateTensorInfo(probabilities);
|
|
return backend.makeTensorInfo(resShape, "int32", resVals);
|
|
}
|
|
const multinomialConfig = {
|
|
kernelName: (0, _tfjsCore.Multinomial),
|
|
backendName: "cpu",
|
|
kernelFunc: multinomial
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","seedrandom":"9SiBG","../cpu_util":"1l037","./Softmax":"1UnfO","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1UnfO":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "softmax", ()=>softmax);
|
|
parcelHelpers.export(exports, "softmaxConfig", ()=>softmaxConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _exp = require("./Exp");
|
|
var _max = require("./Max");
|
|
var _realDiv = require("./RealDiv");
|
|
var _reshape = require("./Reshape");
|
|
var _sub = require("./Sub");
|
|
var _sum = require("./Sum");
|
|
function softmax(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { logits } = inputs;
|
|
const { dim } = attrs;
|
|
const logitsRank = logits.shape.length;
|
|
let $dim = dim;
|
|
if ($dim === -1) $dim = logitsRank - 1;
|
|
if ($dim !== logitsRank - 1) throw Error("Softmax along a non-last dimension is not yet supported. " + `Logits was rank ${logitsRank} and dim was ${$dim}`);
|
|
const axes = (0, _tfjsCore.util).parseAxisParam([
|
|
$dim
|
|
], logits.shape);
|
|
const maxLogit = (0, _max.max)({
|
|
inputs: {
|
|
x: logits
|
|
},
|
|
backend,
|
|
attrs: {
|
|
reductionIndices: axes,
|
|
keepDims: false
|
|
}
|
|
});
|
|
const expandedShape = (0, _tfjsCore.backend_util).expandShapeToKeepDim(maxLogit.shape, axes);
|
|
const maxLogitReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: maxLogit
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: expandedShape
|
|
}
|
|
});
|
|
const a = (0, _sub.sub)({
|
|
inputs: {
|
|
a: logits,
|
|
b: maxLogitReshaped
|
|
},
|
|
backend
|
|
});
|
|
const b = (0, _exp.exp)({
|
|
inputs: {
|
|
x: a
|
|
},
|
|
backend
|
|
});
|
|
const sumExp = (0, _sum.sum)({
|
|
inputs: {
|
|
x: b
|
|
},
|
|
backend,
|
|
attrs: {
|
|
axis: axes,
|
|
keepDims: false
|
|
}
|
|
});
|
|
const sumReshaped = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: sumExp
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: expandedShape
|
|
}
|
|
});
|
|
const result = (0, _realDiv.div)({
|
|
inputs: {
|
|
a: b,
|
|
b: sumReshaped
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(maxLogit);
|
|
backend.disposeIntermediateTensorInfo(maxLogitReshaped);
|
|
backend.disposeIntermediateTensorInfo(a);
|
|
backend.disposeIntermediateTensorInfo(b);
|
|
backend.disposeIntermediateTensorInfo(sumExp);
|
|
backend.disposeIntermediateTensorInfo(sumReshaped);
|
|
return result;
|
|
}
|
|
const softmaxConfig = {
|
|
kernelName: (0, _tfjsCore.Softmax),
|
|
backendName: "cpu",
|
|
kernelFunc: softmax
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Exp":"6eexr","./Max":"ceCEC","./RealDiv":"9Ly75","./Reshape":"9350i","./Sub":"4DByI","./Sum":"6gbbV","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cU4dv":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV3", ()=>nonMaxSuppressionV3);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV3Config", ()=>nonMaxSuppressionV3Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
const nonMaxSuppressionV3Impl = (0, _tfjsCore.kernel_impls).nonMaxSuppressionV3Impl;
|
|
function nonMaxSuppressionV3(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { boxes, scores } = inputs;
|
|
const { maxOutputSize, iouThreshold, scoreThreshold } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(boxes, "NonMaxSuppression");
|
|
const boxesVals = backend.data.get(boxes.dataId).values;
|
|
const scoresVals = backend.data.get(scores.dataId).values;
|
|
const { selectedIndices } = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);
|
|
return backend.makeTensorInfo([
|
|
selectedIndices.length
|
|
], "int32", new Int32Array(selectedIndices));
|
|
}
|
|
const nonMaxSuppressionV3Config = {
|
|
kernelName: (0, _tfjsCore.NonMaxSuppressionV3),
|
|
backendName: "cpu",
|
|
kernelFunc: nonMaxSuppressionV3
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"chYiL":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV4", ()=>nonMaxSuppressionV4);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV4Config", ()=>nonMaxSuppressionV4Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
const nonMaxSuppressionV4Impl = (0, _tfjsCore.kernel_impls).nonMaxSuppressionV4Impl;
|
|
function nonMaxSuppressionV4(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { boxes, scores } = inputs;
|
|
const { maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(boxes, "NonMaxSuppressionPadded");
|
|
const boxesVals = backend.data.get(boxes.dataId).values;
|
|
const scoresVals = backend.data.get(scores.dataId).values;
|
|
const { selectedIndices, validOutputs } = nonMaxSuppressionV4Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize);
|
|
return [
|
|
backend.makeTensorInfo([
|
|
selectedIndices.length
|
|
], "int32", new Int32Array(selectedIndices)),
|
|
backend.makeTensorInfo([], "int32", new Int32Array([
|
|
validOutputs
|
|
]))
|
|
];
|
|
}
|
|
const nonMaxSuppressionV4Config = {
|
|
kernelName: (0, _tfjsCore.NonMaxSuppressionV4),
|
|
backendName: "cpu",
|
|
kernelFunc: nonMaxSuppressionV4
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bVnt1":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV5", ()=>nonMaxSuppressionV5);
|
|
parcelHelpers.export(exports, "nonMaxSuppressionV5Config", ()=>nonMaxSuppressionV5Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
const nonMaxSuppressionV5Impl = (0, _tfjsCore.kernel_impls).nonMaxSuppressionV5Impl;
|
|
function nonMaxSuppressionV5(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { boxes, scores } = inputs;
|
|
const { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(boxes, "NonMaxSuppressionWithScore");
|
|
const boxesVals = backend.data.get(boxes.dataId).values;
|
|
const scoresVals = backend.data.get(scores.dataId).values;
|
|
const maxOutputSizeVal = maxOutputSize;
|
|
const iouThresholdVal = iouThreshold;
|
|
const scoreThresholdVal = scoreThreshold;
|
|
const softNmsSigmaVal = softNmsSigma;
|
|
const { selectedIndices, selectedScores } = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal, scoreThresholdVal, softNmsSigmaVal);
|
|
return [
|
|
backend.makeTensorInfo([
|
|
selectedIndices.length
|
|
], "int32", new Int32Array(selectedIndices)),
|
|
backend.makeTensorInfo([
|
|
selectedScores.length
|
|
], "float32", new Float32Array(selectedScores))
|
|
];
|
|
}
|
|
const nonMaxSuppressionV5Config = {
|
|
kernelName: (0, _tfjsCore.NonMaxSuppressionV5),
|
|
backendName: "cpu",
|
|
kernelFunc: nonMaxSuppressionV5
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9Evwj":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "oneHot", ()=>oneHot);
|
|
parcelHelpers.export(exports, "oneHotConfig", ()=>oneHotConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function oneHot(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { indices } = inputs;
|
|
const { dtype, depth, onValue, offValue } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(indices, "oneHot");
|
|
const indicesSize = (0, _tfjsCore.util).sizeFromShape(indices.shape);
|
|
const res = new Float32Array(indicesSize * depth);
|
|
res.fill(offValue);
|
|
const indicesVal = backend.data.get(indices.dataId).values;
|
|
for(let event = 0; event < indicesSize; ++event)if (indicesVal[event] >= 0 && indicesVal[event] < depth) res[event * depth + indicesVal[event]] = onValue;
|
|
return backend.makeTensorInfo([
|
|
...indices.shape,
|
|
depth
|
|
], dtype, res);
|
|
}
|
|
const oneHotConfig = {
|
|
kernelName: (0, _tfjsCore.OneHot),
|
|
backendName: "cpu",
|
|
kernelFunc: oneHot
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kWIOw":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "onesLike", ()=>onesLike);
|
|
parcelHelpers.export(exports, "onesLikeConfig", ()=>onesLikeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _complex = require("./Complex");
|
|
var _fill = require("./Fill");
|
|
var _imag = require("./Imag");
|
|
var _real = require("./Real");
|
|
var _zerosLike = require("./ZerosLike");
|
|
function onesLike(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
if (x.dtype === "string") throw new Error("onesLike is not supported for string tensors");
|
|
else if (x.dtype === "complex64") {
|
|
const realPart = (0, _real.real)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const r = onesLike({
|
|
inputs: {
|
|
x: realPart
|
|
},
|
|
backend
|
|
});
|
|
const imagPart = (0, _imag.imag)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const i = (0, _zerosLike.zerosLike)({
|
|
inputs: {
|
|
x: imagPart
|
|
},
|
|
backend
|
|
});
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: r,
|
|
imag: i
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(realPart);
|
|
backend.disposeIntermediateTensorInfo(r);
|
|
backend.disposeIntermediateTensorInfo(imagPart);
|
|
backend.disposeIntermediateTensorInfo(i);
|
|
return result;
|
|
} else return (0, _fill.fill)({
|
|
backend,
|
|
attrs: {
|
|
shape: x.shape,
|
|
value: 1,
|
|
dtype: x.dtype
|
|
}
|
|
});
|
|
}
|
|
const onesLikeConfig = {
|
|
kernelName: (0, _tfjsCore.OnesLike),
|
|
backendName: "cpu",
|
|
kernelFunc: onesLike
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Complex":"3DPmh","./Fill":"4BMgR","./Imag":"af3Tx","./Real":"eZ7aJ","./ZerosLike":"hfVJr","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hfVJr":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "zerosLike", ()=>zerosLike);
|
|
parcelHelpers.export(exports, "zerosLikeConfig", ()=>zerosLikeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _complex = require("./Complex");
|
|
var _fill = require("./Fill");
|
|
var _imag = require("./Imag");
|
|
var _real = require("./Real");
|
|
function zerosLike(args) {
|
|
const { inputs, backend } = args;
|
|
const { x } = inputs;
|
|
if (x.dtype === "string") throw new Error("zerosLike is not supported for string tensors");
|
|
else if (x.dtype === "complex64") {
|
|
const realPart = (0, _real.real)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const r = zerosLike({
|
|
inputs: {
|
|
x: realPart
|
|
},
|
|
backend
|
|
});
|
|
const imagPart = (0, _imag.imag)({
|
|
inputs: {
|
|
input: x
|
|
},
|
|
backend
|
|
});
|
|
const i = zerosLike({
|
|
inputs: {
|
|
x: imagPart
|
|
},
|
|
backend
|
|
});
|
|
const result = (0, _complex.complex)({
|
|
inputs: {
|
|
real: r,
|
|
imag: i
|
|
},
|
|
backend
|
|
});
|
|
backend.disposeIntermediateTensorInfo(realPart);
|
|
backend.disposeIntermediateTensorInfo(r);
|
|
backend.disposeIntermediateTensorInfo(imagPart);
|
|
backend.disposeIntermediateTensorInfo(i);
|
|
return result;
|
|
} else return (0, _fill.fill)({
|
|
backend,
|
|
attrs: {
|
|
shape: x.shape,
|
|
value: 0,
|
|
dtype: x.dtype
|
|
}
|
|
});
|
|
}
|
|
const zerosLikeConfig = {
|
|
kernelName: (0, _tfjsCore.ZerosLike),
|
|
backendName: "cpu",
|
|
kernelFunc: zerosLike
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Complex":"3DPmh","./Fill":"4BMgR","./Imag":"af3Tx","./Real":"eZ7aJ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3NDYm":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "pack", ()=>pack);
|
|
parcelHelpers.export(exports, "packConfig", ()=>packConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _concat = require("./Concat");
|
|
var _expandDims = require("./ExpandDims");
|
|
function pack(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { axis } = attrs;
|
|
if (inputs.length === 1) return (0, _expandDims.expandDims)({
|
|
inputs: {
|
|
input: inputs[0]
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dim: axis
|
|
}
|
|
});
|
|
const shape = inputs[0].shape;
|
|
const dtype = inputs[0].dtype;
|
|
inputs.forEach((t)=>{
|
|
(0, _tfjsCore.util).assertShapesMatch(shape, t.shape, "All tensors passed to stack must have matching shapes");
|
|
(0, _tfjsCore.util).assert(dtype === t.dtype, ()=>"All tensors passed to stack must have matching dtypes");
|
|
});
|
|
const intermediateTensorInfos = [];
|
|
const expandedTensors = inputs.map((t)=>{
|
|
const expandedT = (0, _expandDims.expandDims)({
|
|
inputs: {
|
|
input: t
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dim: axis
|
|
}
|
|
});
|
|
intermediateTensorInfos.push(expandedT);
|
|
return expandedT;
|
|
});
|
|
const result = (0, _concat.concat)({
|
|
inputs: expandedTensors,
|
|
backend,
|
|
attrs: {
|
|
axis
|
|
}
|
|
});
|
|
intermediateTensorInfos.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return result;
|
|
}
|
|
const packConfig = {
|
|
kernelName: (0, _tfjsCore.Pack),
|
|
backendName: "cpu",
|
|
kernelFunc: pack
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Concat":"iYEAT","./ExpandDims":"4z77l","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dssNb":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "padV2", ()=>padV2);
|
|
parcelHelpers.export(exports, "padV2Config", ()=>padV2Config);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function padV2(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { paddings, constantValue } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "pad");
|
|
const outShape = paddings.map((p, i)=>p[0] + x.shape[i] + p[1]);
|
|
const start = paddings.map((p)=>p[0]);
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const xSize = (0, _tfjsCore.util).sizeFromShape(x.shape);
|
|
const xRank = x.shape.length;
|
|
const xStrides = (0, _tfjsCore.util).computeStrides(x.shape);
|
|
const resultSize = (0, _tfjsCore.util).sizeFromShape(outShape);
|
|
const resultRank = outShape.length;
|
|
const resultStrides = (0, _tfjsCore.util).computeStrides(outShape);
|
|
const resVals = (0, _tfjsCore.util).getTypedArrayFromDType(x.dtype, resultSize);
|
|
if (constantValue !== 0) resVals.fill(constantValue);
|
|
for(let i = 0; i < xSize; i++){
|
|
const coords = (0, _tfjsCore.util).indexToLoc(i, xRank, xStrides);
|
|
const outCoords = coords.map((c, i)=>c + start[i]);
|
|
const outIndex = (0, _tfjsCore.util).locToIndex(outCoords, resultRank, resultStrides);
|
|
resVals[outIndex] = xVals[i];
|
|
}
|
|
const outId = backend.write(resVals, outShape, x.dtype);
|
|
return {
|
|
dataId: outId,
|
|
shape: outShape,
|
|
dtype: x.dtype
|
|
};
|
|
}
|
|
const padV2Config = {
|
|
kernelName: (0, _tfjsCore.PadV2),
|
|
backendName: "cpu",
|
|
kernelFunc: padV2
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jx4g8":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "powImpl", ()=>powImpl);
|
|
parcelHelpers.export(exports, "pow", ()=>pow);
|
|
parcelHelpers.export(exports, "powConfig", ()=>powConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _binaryImpl = require("../utils/binary_impl");
|
|
var _binaryUtils = require("../utils/binary_utils");
|
|
const powImpl = (0, _binaryImpl.createSimpleBinaryKernelImpl)((a, b)=>Math.pow(a, b));
|
|
const pow = (0, _binaryUtils.binaryKernelFunc)((0, _tfjsCore.Pow), powImpl);
|
|
const powConfig = {
|
|
kernelName: (0, _tfjsCore.Pow),
|
|
backendName: "cpu",
|
|
kernelFunc: pow
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/binary_impl":"7WPlP","../utils/binary_utils":"dUQGx","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4jEHO":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedGather", ()=>raggedGather);
|
|
parcelHelpers.export(exports, "raggedGatherConfig", ()=>raggedGatherConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _raggedGatherImpl = require("./RaggedGather_impl");
|
|
function raggedGather(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { paramsNestedSplits, paramsDenseValues, indices } = inputs;
|
|
const { outputRaggedRank } = attrs;
|
|
const $paramsNestedSplits = paramsNestedSplits.map((t)=>backend.data.get(t.dataId).values);
|
|
const $paramsNestedSplitsShapes = paramsNestedSplits.map((t)=>t.shape);
|
|
const $paramsDenseValues = backend.data.get(paramsDenseValues.dataId).values;
|
|
const $indices = backend.data.get(indices.dataId).values;
|
|
const [outputNestedSplits, outputDenseValues, outputDenseValuesShape] = (0, _raggedGatherImpl.raggedGatherImpl)($paramsNestedSplits, $paramsNestedSplitsShapes, $paramsDenseValues, paramsDenseValues.shape, paramsDenseValues.dtype, $indices, indices.shape, outputRaggedRank);
|
|
const outputNestedSplitsTensors = outputNestedSplits.map((splits)=>backend.makeTensorInfo([
|
|
splits.length
|
|
], "int32", splits));
|
|
const outputDenseValuesTensor = backend.makeTensorInfo(outputDenseValuesShape, paramsDenseValues.dtype, outputDenseValues);
|
|
return outputNestedSplitsTensors.concat([
|
|
outputDenseValuesTensor
|
|
]);
|
|
}
|
|
const raggedGatherConfig = {
|
|
kernelName: (0, _tfjsCore.RaggedGather),
|
|
backendName: "cpu",
|
|
kernelFunc: raggedGather
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./RaggedGather_impl":"59HGn","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kFVpX":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 Google LLC.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedRange", ()=>raggedRange);
|
|
parcelHelpers.export(exports, "raggedRangeConfig", ()=>raggedRangeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _raggedRangeImpl = require("./RaggedRange_impl");
|
|
function raggedRange(args) {
|
|
const { inputs, backend } = args;
|
|
const { starts, limits, deltas } = inputs;
|
|
const $starts = backend.data.get(starts.dataId).values;
|
|
const $limits = backend.data.get(limits.dataId).values;
|
|
const $deltas = backend.data.get(deltas.dataId).values;
|
|
const [rtNestedSplitsData, rtDenseValuesData] = (0, _raggedRangeImpl.raggedRangeImpl)($starts, starts.shape, starts.dtype, $limits, limits.shape, $deltas, deltas.shape);
|
|
const rtNestedSplits = backend.makeTensorInfo([
|
|
rtNestedSplitsData.length
|
|
], "int32", rtNestedSplitsData);
|
|
const rtDenseValues = backend.makeTensorInfo([
|
|
rtDenseValuesData.length
|
|
], starts.dtype, rtDenseValuesData);
|
|
return [
|
|
rtNestedSplits,
|
|
rtDenseValues
|
|
];
|
|
}
|
|
const raggedRangeConfig = {
|
|
kernelName: (0, _tfjsCore.RaggedRange),
|
|
backendName: "cpu",
|
|
kernelFunc: raggedRange
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./RaggedRange_impl":"l2R3s","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bJlTR":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "raggedTensorToTensor", ()=>raggedTensorToTensor);
|
|
parcelHelpers.export(exports, "raggedTensorToTensorConfig", ()=>raggedTensorToTensorConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _raggedTensorToTensorImpl = require("./RaggedTensorToTensor_impl");
|
|
function raggedTensorToTensor(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { shape, values, defaultValue, rowPartitionTensors } = inputs;
|
|
const { rowPartitionTypes } = attrs;
|
|
const $shape = backend.data.get(shape.dataId).values;
|
|
const $values = backend.data.get(values.dataId).values;
|
|
const $defaultValue = backend.data.get(defaultValue.dataId).values;
|
|
const $rowPartitionValues = rowPartitionTensors.map((t)=>backend.data.get(t.dataId).values);
|
|
const rowPartitionValuesShapes = rowPartitionTensors.map((t)=>t.shape);
|
|
const [outputShape, output] = (0, _raggedTensorToTensorImpl.raggedTensorToTensorImpl)($shape, shape.shape, $values, values.shape, values.dtype, $defaultValue, defaultValue.shape, $rowPartitionValues, rowPartitionValuesShapes, rowPartitionTypes);
|
|
return backend.makeTensorInfo(outputShape, values.dtype, output);
|
|
}
|
|
const raggedTensorToTensorConfig = {
|
|
kernelName: (0, _tfjsCore.RaggedTensorToTensor),
|
|
backendName: "cpu",
|
|
kernelFunc: raggedTensorToTensor
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./RaggedTensorToTensor_impl":"jDwSG","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"1Dov9":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "range", ()=>range);
|
|
parcelHelpers.export(exports, "rangeConfig", ()=>rangeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _rangeImpl = require("./Range_impl");
|
|
function range(args) {
|
|
const { backend, attrs } = args;
|
|
const { start, stop, dtype, step } = attrs;
|
|
const values = (0, _rangeImpl.rangeImpl)(start, stop, step, dtype);
|
|
return backend.makeTensorInfo([
|
|
values.length
|
|
], dtype, values);
|
|
}
|
|
const rangeConfig = {
|
|
kernelName: (0, _tfjsCore.Range),
|
|
backendName: "cpu",
|
|
kernelFunc: range
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Range_impl":"gJNJp","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"3BhEV":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reciprocal", ()=>reciprocal);
|
|
parcelHelpers.export(exports, "reciprocalConfig", ()=>reciprocalConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const reciprocal = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Reciprocal), (xi)=>1 / xi);
|
|
const reciprocalConfig = {
|
|
kernelName: (0, _tfjsCore.Reciprocal),
|
|
backendName: "cpu",
|
|
kernelFunc: reciprocal
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kU0RB":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeBilinear", ()=>resizeBilinear);
|
|
parcelHelpers.export(exports, "resizeBilinearConfig", ()=>resizeBilinearConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function resizeBilinear(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { images } = inputs;
|
|
const { alignCorners, halfPixelCenters, size } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(images, "resizeBilinear");
|
|
const imagesStrides = (0, _tfjsCore.util).computeStrides(images.shape);
|
|
const [newHeight, newWidth] = size;
|
|
const [batch, oldHeight, oldWidth, numChannels] = images.shape;
|
|
const xValues = backend.data.get(images.dataId).values;
|
|
const result = new Float32Array((0, _tfjsCore.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++){
|
|
let sourceFracRow;
|
|
if (halfPixelCenters) sourceFracRow = effectiveRowSizeRatio * (r + 0.5) - 0.5;
|
|
else sourceFracRow = effectiveRowSizeRatio * r;
|
|
const sourceRowFloor = Math.max(0, Math.floor(sourceFracRow));
|
|
const rowFrac = sourceFracRow - sourceRowFloor;
|
|
const sourceRowCeil = Math.min(oldHeight - 1, Math.ceil(sourceFracRow));
|
|
const topRowOffset = b * imagesStrides[0] + sourceRowFloor * imagesStrides[1];
|
|
const botRowOffset = b * imagesStrides[0] + sourceRowCeil * imagesStrides[1];
|
|
for(let c = 0; c < newWidth; c++){
|
|
let sourceFracCol;
|
|
if (halfPixelCenters) sourceFracCol = effectiveColSizeRatio * (c + 0.5) - 0.5;
|
|
else sourceFracCol = effectiveColSizeRatio * c;
|
|
const sourceColFloor = Math.max(0, Math.floor(sourceFracCol));
|
|
const colFrac = sourceFracCol - sourceColFloor;
|
|
const sourceColCeil = Math.min(oldWidth - 1, Math.ceil(sourceFracCol));
|
|
const topLeftOffest = topRowOffset + sourceColFloor * imagesStrides[2];
|
|
const botLeftOffset = botRowOffset + sourceColFloor * imagesStrides[2];
|
|
const topRightOffset = topRowOffset + sourceColCeil * imagesStrides[2];
|
|
const botRightOffest = botRowOffset + sourceColCeil * imagesStrides[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 backend.makeTensorInfo([
|
|
batch,
|
|
newHeight,
|
|
newWidth,
|
|
numChannels
|
|
], "float32", result);
|
|
}
|
|
const resizeBilinearConfig = {
|
|
kernelName: (0, _tfjsCore.ResizeBilinear),
|
|
backendName: "cpu",
|
|
kernelFunc: resizeBilinear
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"76Mq3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeBilinearGrad", ()=>resizeBilinearGrad);
|
|
parcelHelpers.export(exports, "resizeBilinearGradConfig", ()=>resizeBilinearGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function resizeBilinearGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { images, dy } = inputs;
|
|
const { alignCorners } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy,
|
|
images
|
|
], "resizeBilinearGrad");
|
|
const imagesStrides = (0, _tfjsCore.util).computeStrides(images.shape);
|
|
const [batch, xHeight, xWidth, depth] = images.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 = backend.data.get(dy.dataId).values;
|
|
let offset = 0;
|
|
for(let b = 0; b < batch; b++){
|
|
const bOffset = b * imagesStrides[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 * imagesStrides[1];
|
|
const bottomDxROffset = bOffset + bottomDxRIndex * imagesStrides[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 * imagesStrides[2];
|
|
const topRightRCOffset = topDxROffset + rightDxCIndex * imagesStrides[2];
|
|
const bottomLeftRCOffset = bottomDxROffset + leftDxCIndex * imagesStrides[2];
|
|
const bottomRightRCOffset = bottomDxROffset + rightDxCIndex * imagesStrides[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 backend.makeTensorInfo([
|
|
batch,
|
|
xWidth,
|
|
xHeight,
|
|
depth
|
|
], "float32", output);
|
|
}
|
|
const resizeBilinearGradConfig = {
|
|
kernelName: (0, _tfjsCore.ResizeBilinearGrad),
|
|
backendName: "cpu",
|
|
kernelFunc: resizeBilinearGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"5c1lG":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeNearestNeighbor", ()=>resizeNearestNeighbor);
|
|
parcelHelpers.export(exports, "resizeNearestNeighborConfig", ()=>resizeNearestNeighborConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function resizeNearestNeighbor(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { images } = inputs;
|
|
const { alignCorners, halfPixelCenters, size } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(images, "resizeNearestNeighbor");
|
|
const imagesStrides = (0, _tfjsCore.util).computeStrides(images.shape);
|
|
const [newHeight, newWidth] = size;
|
|
const [batch, oldHeight, oldWidth, numChannels] = images.shape;
|
|
const xValues = backend.data.get(images.dataId).values;
|
|
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 * imagesStrides[0];
|
|
for(let r = 0; r < newHeight; r++){
|
|
const sourceFracRow = halfPixelCenters ? effectiveRowSizeRatio * (r + 0.5) : effectiveRowSizeRatio * r;
|
|
let sourceNearestRow = Math.min(oldHeight - 1, alignCorners ? Math.round(sourceFracRow) : Math.floor(sourceFracRow));
|
|
if (halfPixelCenters) sourceNearestRow = Math.max(0, sourceNearestRow);
|
|
const rowOffset = batchOffset + sourceNearestRow * imagesStrides[1];
|
|
for(let c = 0; c < newWidth; c++){
|
|
const sourceFracCol = halfPixelCenters ? effectiveColSizeRatio * (c + 0.5) : effectiveColSizeRatio * c;
|
|
let sourceNearestCol = Math.min(oldWidth - 1, alignCorners ? Math.round(sourceFracCol) : Math.floor(sourceFracCol));
|
|
if (halfPixelCenters) sourceNearestCol = Math.max(0, sourceNearestCol);
|
|
const colOffset = rowOffset + sourceNearestCol * imagesStrides[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 backend.makeTensorInfo([
|
|
batch,
|
|
newHeight,
|
|
newWidth,
|
|
numChannels
|
|
], images.dtype, output);
|
|
}
|
|
const resizeNearestNeighborConfig = {
|
|
kernelName: (0, _tfjsCore.ResizeNearestNeighbor),
|
|
backendName: "cpu",
|
|
kernelFunc: resizeNearestNeighbor
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"4hhu6":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "resizeNearestNeighborGrad", ()=>resizeNearestNeighborGrad);
|
|
parcelHelpers.export(exports, "resizeNearestNeighborGradConfig", ()=>resizeNearestNeighborGradConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function resizeNearestNeighborGrad(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { images, dy } = inputs;
|
|
const { alignCorners } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
dy,
|
|
images
|
|
], "resizeNearestNeighborGrad");
|
|
const imagesStrides = (0, _tfjsCore.util).computeStrides(images.shape);
|
|
const dyStrides = (0, _tfjsCore.util).computeStrides(dy.shape);
|
|
const [batch, xHeight, xWidth, depth] = images.shape;
|
|
const [, yHeight, yWidth] = dy.shape;
|
|
const output = new Float32Array(batch * xHeight * xWidth * depth);
|
|
const dyValues = backend.data.get(dy.dataId).values;
|
|
// 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 * imagesStrides[0];
|
|
for(let r = 0; r < xHeight; r++){
|
|
const rowOffset = batchOffset + r * imagesStrides[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 * imagesStrides[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 * dyStrides[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 * dyStrides[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 backend.makeTensorInfo(images.shape, images.dtype, output);
|
|
}
|
|
const resizeNearestNeighborGradConfig = {
|
|
kernelName: (0, _tfjsCore.ResizeNearestNeighborGrad),
|
|
backendName: "cpu",
|
|
kernelFunc: resizeNearestNeighborGrad
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"ff3xk":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "reverse", ()=>reverse);
|
|
parcelHelpers.export(exports, "reverseConfig", ()=>reverseConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _identity = require("./Identity");
|
|
function reverse(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { dims } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "reverse");
|
|
const xRank = x.shape.length;
|
|
const $dims = (0, _tfjsCore.util).parseAxisParam(dims, x.shape);
|
|
if (xRank === 0) return (0, _identity.identity)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend
|
|
});
|
|
const outBuf = new (0, _tfjsCore.TensorBuffer)(x.shape, x.dtype);
|
|
const xBuf = backend.bufferSync(x);
|
|
for(let i = 0; i < outBuf.size; i++){
|
|
const outLoc = outBuf.indexToLoc(i);
|
|
const inLoc = outLoc.slice();
|
|
$dims.forEach((d)=>inLoc[d] = x.shape[d] - 1 - inLoc[d]);
|
|
outBuf.set(xBuf.get(...inLoc), ...outLoc);
|
|
}
|
|
return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const reverseConfig = {
|
|
kernelName: (0, _tfjsCore.Reverse),
|
|
backendName: "cpu",
|
|
kernelFunc: reverse
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Identity":"btREJ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"d9nWG":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "rotateWithOffsetConfig", ()=>rotateWithOffsetConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
const rotateWithOffsetConfig = {
|
|
kernelName: (0, _tfjsCore.RotateWithOffset),
|
|
backendName: "cpu",
|
|
kernelFunc: ({ inputs, attrs, backend })=>{
|
|
const { image } = inputs;
|
|
const { radians, fillValue, center } = attrs;
|
|
const cpuBackend = backend;
|
|
const output = (0, _tfjsCore.util).getTypedArrayFromDType(image.dtype, (0, _tfjsCore.util).sizeFromShape(image.shape));
|
|
const [batch, imageHeight, imageWidth, numChannels] = image.shape;
|
|
const [centerX, centerY] = (0, _tfjsCore.backend_util).getImageCenter(center, imageHeight, imageWidth);
|
|
const fullOpacityValue = 255;
|
|
const sinFactor = Math.sin(radians);
|
|
const cosFactor = Math.cos(radians);
|
|
const imageVals = cpuBackend.data.get(image.dataId).values;
|
|
for(let batchIdx = 0; batchIdx < batch; batchIdx++){
|
|
const batchOffset = batchIdx * imageWidth * imageHeight * numChannels;
|
|
for(let row = 0; row < imageHeight; row++){
|
|
const rowOffset = row * (imageWidth * numChannels);
|
|
for(let col = 0; col < imageWidth; col++){
|
|
const colOffset = col * numChannels;
|
|
for(let channel = 0; channel < numChannels; channel++){
|
|
const coords = [
|
|
batch,
|
|
row,
|
|
col,
|
|
channel
|
|
];
|
|
const x = coords[2];
|
|
const y = coords[1];
|
|
// coordX/coordY are the result of rotating and translating x/y.
|
|
let coordX = (x - centerX) * cosFactor - (y - centerY) * sinFactor;
|
|
let coordY = (x - centerX) * sinFactor + (y - centerY) * cosFactor;
|
|
coordX = Math.round(coordX + centerX);
|
|
coordY = Math.round(coordY + centerY);
|
|
let outputValue = fillValue;
|
|
if (typeof fillValue !== "number") {
|
|
if (channel === 3) outputValue = fullOpacityValue;
|
|
else outputValue = fillValue[channel];
|
|
}
|
|
// If the coordinate position falls within the image boundaries...
|
|
if (coordX >= 0 && coordX < imageWidth && coordY >= 0 && coordY < imageHeight) {
|
|
// set the output to the image value at the coordinate position.
|
|
const rotatedRowOffset = coordY * (imageWidth * numChannels);
|
|
const rotatedColOffset = coordX * numChannels;
|
|
const imageIdx = batchOffset + rotatedRowOffset + rotatedColOffset + channel;
|
|
outputValue = imageVals[imageIdx];
|
|
}
|
|
const outIdx = batchOffset + rowOffset + colOffset + channel;
|
|
output[outIdx] = outputValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const dataId = cpuBackend.write(output, image.shape, image.dtype);
|
|
return {
|
|
dataId,
|
|
shape: image.shape,
|
|
dtype: image.dtype
|
|
};
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"gnp2v":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "round", ()=>round);
|
|
parcelHelpers.export(exports, "roundConfig", ()=>roundConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const round = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Round), (xi)=>{
|
|
// The algorithm is based on banker's rounding.
|
|
const base = Math.floor(xi);
|
|
if (xi - base < 0.5) return Math.floor(xi);
|
|
else if (xi - base > 0.5) return Math.ceil(xi);
|
|
else {
|
|
if (base % 2.0 === 0.0) return base;
|
|
else return base + 1.0;
|
|
}
|
|
});
|
|
const roundConfig = {
|
|
kernelName: (0, _tfjsCore.Round),
|
|
backendName: "cpu",
|
|
kernelFunc: round
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bb9Cv":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "scatterNd", ()=>scatterNd);
|
|
parcelHelpers.export(exports, "scatterNdConfig", ()=>scatterNdConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _scatterImpl = require("./Scatter_impl");
|
|
function scatterNd(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { indices, updates } = inputs;
|
|
const { shape } = attrs;
|
|
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = (0, _tfjsCore.backend_util).calculateShapes(updates, indices, shape);
|
|
const sumDupeIndices = true;
|
|
const indicesBuf = backend.bufferSync(indices);
|
|
const updatesBuf = backend.bufferSync(updates);
|
|
const outBuf = (0, _scatterImpl.scatterImpl)(indicesBuf, updatesBuf, shape, outputSize, sliceSize, numUpdates, sliceRank, strides, 0 /* defaultValue */ , sumDupeIndices);
|
|
return backend.makeTensorInfo(shape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const scatterNdConfig = {
|
|
kernelName: (0, _tfjsCore.ScatterNd),
|
|
backendName: "cpu",
|
|
kernelFunc: scatterNd
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Scatter_impl":"kMt6f","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"f7WfM":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "searchSorted", ()=>searchSorted);
|
|
parcelHelpers.export(exports, "searchSortedConfig", ()=>searchSortedConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _searchSortedImpl = require("./SearchSorted_impl");
|
|
function searchSorted(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { sortedSequence, values } = inputs;
|
|
const { side } = attrs;
|
|
const $sortedSequence = backend.data.get(sortedSequence.dataId).values;
|
|
const $values = backend.data.get(values.dataId).values;
|
|
const output = (0, _searchSortedImpl.searchSortedImpl)($sortedSequence, $values, sortedSequence.shape[0], sortedSequence.shape[1], values.shape[1], side);
|
|
return backend.makeTensorInfo(values.shape, "int32", output);
|
|
}
|
|
const searchSortedConfig = {
|
|
kernelName: (0, _tfjsCore.SearchSorted),
|
|
backendName: "cpu",
|
|
kernelFunc: searchSorted
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./SearchSorted_impl":"2K7QF","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2K7QF":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "searchSortedImpl", ()=>searchSortedImpl);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function lowerBound(array, value) {
|
|
let left = 0;
|
|
let right = array.length;
|
|
let mid = 0;
|
|
while(left < right){
|
|
mid = Math.floor((left + right) / 2);
|
|
if (array[mid] < value) left = mid + 1;
|
|
else right = mid;
|
|
}
|
|
return right;
|
|
}
|
|
function upperBound(array, value) {
|
|
let left = 0;
|
|
let right = array.length;
|
|
let mid = 0;
|
|
while(left < right){
|
|
mid = Math.floor((left + right) / 2);
|
|
if (array[mid] <= value) left = mid + 1;
|
|
else right = mid;
|
|
}
|
|
return right;
|
|
}
|
|
function searchSortedImpl(sortedInputs, values, batchSize, numInputs, numValues, side) {
|
|
const output = (0, _tfjsCore.util).getArrayFromDType("int32", batchSize * numValues);
|
|
for(let b = 0; b < batchSize; ++b){
|
|
const sortedInputsSlice = sortedInputs.slice(b * numInputs, (b + 1) * numInputs);
|
|
const outputOffset = b * numValues;
|
|
for(let i = 0; i < numValues; ++i)output[outputOffset + i] = side === "left" ? lowerBound(sortedInputsSlice, values[i + outputOffset]) : upperBound(sortedInputsSlice, values[i + outputOffset]);
|
|
}
|
|
return output;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"lDXuK":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "select", ()=>select);
|
|
parcelHelpers.export(exports, "selectConfig", ()=>selectConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
function select(args) {
|
|
const { inputs, backend } = args;
|
|
const { condition, t, e } = inputs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
condition,
|
|
t,
|
|
e
|
|
], "select");
|
|
const conditionRank = condition.shape.length;
|
|
const values = backend.data.get(condition.dataId).values;
|
|
const tValues = backend.data.get(t.dataId).values;
|
|
const eValues = backend.data.get(e.dataId).values;
|
|
const resultDtype = (0, _tfjsCore.upcastType)(t.dtype, e.dtype);
|
|
const newValues = (0, _tfjsCore.util).makeZerosTypedArray((0, _tfjsCore.util).sizeFromShape(t.shape), resultDtype);
|
|
let index = 0;
|
|
const offset = conditionRank === 0 || conditionRank > 1 || t.shape.length === 1 ? 1 : (0, _tfjsCore.util).sizeFromShape(t.shape.slice(1));
|
|
for(let i = 0; i < values.length; i++){
|
|
for(let j = 0; j < offset; j++)if (values[i] === 1) newValues[index++] = tValues[i];
|
|
else newValues[index++] = eValues[i];
|
|
}
|
|
return backend.makeTensorInfo(t.shape, resultDtype, newValues);
|
|
}
|
|
const selectConfig = {
|
|
kernelName: (0, _tfjsCore.Select),
|
|
backendName: "cpu",
|
|
kernelFunc: select
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cJWbo":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "selu", ()=>selu);
|
|
parcelHelpers.export(exports, "seluConfig", ()=>seluConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const scaleAlpha = (0, _tfjsCore.backend_util).SELU_SCALEALPHA;
|
|
const scale = (0, _tfjsCore.backend_util).SELU_SCALE;
|
|
const selu = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Selu), (xi)=>{
|
|
if (xi >= 0) return scale * xi;
|
|
else return scaleAlpha * (Math.exp(xi) - 1);
|
|
});
|
|
const seluConfig = {
|
|
kernelName: (0, _tfjsCore.Selu),
|
|
backendName: "cpu",
|
|
kernelFunc: selu
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"erXNP":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sign", ()=>sign);
|
|
parcelHelpers.export(exports, "signConfig", ()=>signConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const sign = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Sign), (xi)=>{
|
|
if (xi < 0) return -1;
|
|
else if (xi > 0) return 1;
|
|
else return 0;
|
|
});
|
|
const signConfig = {
|
|
kernelName: (0, _tfjsCore.Sign),
|
|
backendName: "cpu",
|
|
kernelFunc: sign
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"c9it7":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sin", ()=>sin);
|
|
parcelHelpers.export(exports, "sinConfig", ()=>sinConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const sin = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Sin), (xi)=>Math.sin(xi));
|
|
const sinConfig = {
|
|
kernelName: (0, _tfjsCore.Sin),
|
|
backendName: "cpu",
|
|
kernelFunc: sin
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9tr3d":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sinh", ()=>sinh);
|
|
parcelHelpers.export(exports, "sinhConfig", ()=>sinhConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const sinh = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Sinh), (xi)=>Math.sinh(xi));
|
|
const sinhConfig = {
|
|
kernelName: (0, _tfjsCore.Sinh),
|
|
backendName: "cpu",
|
|
kernelFunc: sinh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bojBS":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "softplus", ()=>softplus);
|
|
parcelHelpers.export(exports, "softplusConfig", ()=>softplusConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
// 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 softplus = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Softplus), (xi)=>{
|
|
// Value above which exp(x) may overflow, but softplus(x) == x
|
|
// is within machine epsilon.
|
|
const tooLarge = xi > -threshold;
|
|
// Value below which exp(x) may underflow, but softplus(x) == exp(x)
|
|
// is within machine epsilon.
|
|
const tooSmall = xi < threshold;
|
|
const expX = Math.exp(xi);
|
|
let result;
|
|
if (tooSmall) result = expX;
|
|
else if (tooLarge) result = xi;
|
|
else result = Math.log(1.0 + expX);
|
|
return result;
|
|
});
|
|
const softplusConfig = {
|
|
kernelName: (0, _tfjsCore.Softplus),
|
|
backendName: "cpu",
|
|
kernelFunc: softplus
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cO9CD":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "spaceToBatchND", ()=>spaceToBatchND);
|
|
parcelHelpers.export(exports, "spaceToBatchNDConfig", ()=>spaceToBatchNDConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _padV2 = require("./PadV2");
|
|
var _reshape = require("./Reshape");
|
|
var _transpose = require("./Transpose");
|
|
function spaceToBatchND(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { blockShape, paddings } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)([
|
|
x
|
|
], "spaceToBatchND");
|
|
const prod = (0, _tfjsCore.util).sizeFromShape(blockShape);
|
|
const completePaddings = [
|
|
[
|
|
0,
|
|
0
|
|
]
|
|
];
|
|
completePaddings.push(...paddings);
|
|
for(let i = 1 + blockShape.length; i < x.shape.length; ++i)completePaddings.push([
|
|
0,
|
|
0
|
|
]);
|
|
const paddedX = (0, _padV2.padV2Config).kernelFunc({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
paddings: completePaddings,
|
|
constantValue: 0
|
|
}
|
|
});
|
|
const reshapedPaddedShape = (0, _tfjsCore.backend_util).getReshaped(paddedX.shape, blockShape, prod, false);
|
|
const permutedReshapedPaddedPermutation = (0, _tfjsCore.backend_util).getPermuted(reshapedPaddedShape.length, blockShape.length, false);
|
|
const flattenShape = (0, _tfjsCore.backend_util).getReshapedPermuted(paddedX.shape, blockShape, prod, false);
|
|
const reshapeInputs = {
|
|
x: paddedX
|
|
};
|
|
const reshapeAttrs = {
|
|
shape: reshapedPaddedShape
|
|
};
|
|
const paddedXReshaped = (0, _reshape.reshape)({
|
|
inputs: reshapeInputs,
|
|
backend,
|
|
attrs: reshapeAttrs
|
|
});
|
|
const transposeInputs = {
|
|
x: paddedXReshaped
|
|
};
|
|
const transposeAttrs = {
|
|
perm: permutedReshapedPaddedPermutation
|
|
};
|
|
const paddedXT = (0, _transpose.transpose)({
|
|
inputs: transposeInputs,
|
|
backend,
|
|
attrs: transposeAttrs
|
|
});
|
|
const resultReshapeInputs = {
|
|
x: paddedXT
|
|
};
|
|
const resultReshapeAttrs = {
|
|
shape: flattenShape
|
|
};
|
|
const result = (0, _reshape.reshape)({
|
|
inputs: resultReshapeInputs,
|
|
backend,
|
|
attrs: resultReshapeAttrs
|
|
});
|
|
backend.disposeIntermediateTensorInfo(paddedX);
|
|
backend.disposeIntermediateTensorInfo(paddedXReshaped);
|
|
backend.disposeIntermediateTensorInfo(paddedXT);
|
|
return result;
|
|
}
|
|
const spaceToBatchNDConfig = {
|
|
kernelName: (0, _tfjsCore.SpaceToBatchND),
|
|
backendName: "cpu",
|
|
kernelFunc: spaceToBatchND
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./PadV2":"dssNb","./Reshape":"9350i","./Transpose":"61ywv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cLZdR":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseFillEmptyRows", ()=>sparseFillEmptyRows);
|
|
parcelHelpers.export(exports, "sparseFillEmptyRowsConfig", ()=>sparseFillEmptyRowsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _sparseFillEmptyRowsImpl = require("./SparseFillEmptyRows_impl");
|
|
function sparseFillEmptyRows(args) {
|
|
const { inputs, backend } = args;
|
|
const { indices, values, denseShape, defaultValue } = inputs;
|
|
if (denseShape.shape.length !== 1) throw new Error(`Dense shape must be a vector, saw:
|
|
${denseShape.shape}`);
|
|
if (indices.shape.length !== 2) throw new Error(`Indices must be a matrix, saw:
|
|
${indices.shape}`);
|
|
if (values.shape.length !== 1) throw new Error(`Values must be a vector, saw:
|
|
${values.shape}`);
|
|
if (defaultValue.shape.length !== 0) throw new Error(`Default value must be a scalar, saw:
|
|
${defaultValue.shape}`);
|
|
const $indices = backend.data.get(indices.dataId).values;
|
|
const $values = backend.data.get(values.dataId).values;
|
|
const $denseShape = backend.data.get(denseShape.dataId).values;
|
|
const $defaultValue = backend.data.get(defaultValue.dataId).values[0];
|
|
const [outputIndices, outputIndicesShape, outputValues, emptyRowIndicator, reverseIndexMap] = (0, _sparseFillEmptyRowsImpl.sparseFillEmptyRowsImpl)($indices, indices.shape, indices.dtype, $values, values.dtype, $denseShape, $defaultValue);
|
|
return [
|
|
backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),
|
|
backend.makeTensorInfo([
|
|
outputIndicesShape[0]
|
|
], values.dtype, outputValues),
|
|
backend.makeTensorInfo([
|
|
emptyRowIndicator.length
|
|
], "bool", new Uint8Array(emptyRowIndicator.map((value)=>Number(value)))),
|
|
backend.makeTensorInfo([
|
|
reverseIndexMap.length
|
|
], indices.dtype, new Int32Array(reverseIndexMap))
|
|
];
|
|
}
|
|
const sparseFillEmptyRowsConfig = {
|
|
kernelName: (0, _tfjsCore.SparseFillEmptyRows),
|
|
backendName: "cpu",
|
|
kernelFunc: sparseFillEmptyRows
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./SparseFillEmptyRows_impl":"72f9e","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"bVjgS":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseReshape", ()=>sparseReshape);
|
|
parcelHelpers.export(exports, "sparseReshapeConfig", ()=>sparseReshapeConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _sparseReshapeImpl = require("./SparseReshape_impl");
|
|
function sparseReshape(args) {
|
|
const { inputs, backend } = args;
|
|
const { inputIndices, inputShape, newShape } = inputs;
|
|
if (inputIndices.shape.length !== 2) throw new Error(`Input indices should be a matrix but received shape
|
|
${inputIndices.shape}`);
|
|
if (inputShape.shape.length !== 1) throw new Error(`Input shape should be a vector but received shape
|
|
${inputShape.shape}`);
|
|
if (newShape.shape.length !== 1) throw new Error(`Target shape should be a vector but received shape ${newShape.shape}`);
|
|
const $inputShape = Array.from(backend.data.get(inputShape.dataId).values);
|
|
const $inputIndices = backend.data.get(inputIndices.dataId).values;
|
|
const targetShape = Array.from(backend.data.get(newShape.dataId).values);
|
|
const [newIndices, indicesShape, outputShape] = (0, _sparseReshapeImpl.sparseReshapeImpl)($inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape, targetShape);
|
|
return [
|
|
backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),
|
|
backend.makeTensorInfo([
|
|
outputShape.length
|
|
], newShape.dtype, new Int32Array(outputShape))
|
|
];
|
|
}
|
|
const sparseReshapeConfig = {
|
|
kernelName: (0, _tfjsCore.SparseReshape),
|
|
backendName: "cpu",
|
|
kernelFunc: sparseReshape
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./SparseReshape_impl":"ecdf6","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7zRqG":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseSegmentMean", ()=>sparseSegmentMean);
|
|
parcelHelpers.export(exports, "sparseSegmentMeanConfig", ()=>sparseSegmentMeanConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _sparseSegmentReductionImpl = require("./SparseSegmentReduction_impl");
|
|
function sparseSegmentMean(args) {
|
|
const { inputs, backend } = args;
|
|
const { data, indices, segmentIds } = inputs;
|
|
if (data.shape.length < 1) throw new Error(`Data should be at least 1 dimensional but received scalar`);
|
|
if (indices.shape.length !== 1) throw new Error(`Indices should be a vector but received shape
|
|
${indices.shape}`);
|
|
if (segmentIds.shape.length !== 1) throw new Error(`Segment ids should be a vector but received shape
|
|
${segmentIds.shape}`);
|
|
if (indices.shape[0] !== segmentIds.shape[0]) throw new Error(`segmentIds and indices should have same size.`);
|
|
const $data = backend.data.get(data.dataId).values;
|
|
const $indices = backend.data.get(indices.dataId).values;
|
|
const $segmentIds = backend.data.get(segmentIds.dataId).values;
|
|
const [outputData, outputDataShape] = (0, _sparseSegmentReductionImpl.sparseSegmentReductionImpl)($data, data.shape, data.dtype, $indices, $segmentIds, true);
|
|
return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
|
|
}
|
|
const sparseSegmentMeanConfig = {
|
|
kernelName: (0, _tfjsCore.SparseSegmentMean),
|
|
backendName: "cpu",
|
|
kernelFunc: sparseSegmentMean
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./SparseSegmentReduction_impl":"ie2pQ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"dMeLQ":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseSegmentSum", ()=>sparseSegmentSum);
|
|
parcelHelpers.export(exports, "sparseSegmentSumConfig", ()=>sparseSegmentSumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _sparseSegmentReductionImpl = require("./SparseSegmentReduction_impl");
|
|
function sparseSegmentSum(args) {
|
|
const { inputs, backend } = args;
|
|
const { data, indices, segmentIds } = inputs;
|
|
if (data.shape.length < 1) throw new Error(`Data should be at least 1 dimensional but received scalar`);
|
|
if (indices.shape.length !== 1) throw new Error(`Indices should be a vector but received shape
|
|
${indices.shape}`);
|
|
if (segmentIds.shape.length !== 1) throw new Error(`Segment ids should be a vector but received shape
|
|
${segmentIds.shape}`);
|
|
if (indices.shape[0] !== segmentIds.shape[0]) throw new Error(`segmentIds and indices should have same size.`);
|
|
const $data = backend.data.get(data.dataId).values;
|
|
const $indices = backend.data.get(indices.dataId).values;
|
|
const $segmentIds = backend.data.get(segmentIds.dataId).values;
|
|
const [outputData, outputDataShape] = (0, _sparseSegmentReductionImpl.sparseSegmentReductionImpl)($data, data.shape, data.dtype, $indices, $segmentIds);
|
|
return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
|
|
}
|
|
const sparseSegmentSumConfig = {
|
|
kernelName: (0, _tfjsCore.SparseSegmentSum),
|
|
backendName: "cpu",
|
|
kernelFunc: sparseSegmentSum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./SparseSegmentReduction_impl":"ie2pQ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"kfHsN":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "sparseToDense", ()=>sparseToDense);
|
|
parcelHelpers.export(exports, "sparseToDenseConfig", ()=>sparseToDenseConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _scatterImpl = require("./Scatter_impl");
|
|
function sparseToDense(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { sparseIndices, sparseValues, defaultValue } = inputs;
|
|
const { outputShape } = attrs;
|
|
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = (0, _tfjsCore.backend_util).calculateShapes(sparseValues, sparseIndices, outputShape);
|
|
const sumDupeIndices = false;
|
|
const indicesBuf = backend.bufferSync(sparseIndices);
|
|
let outBuf;
|
|
switch(sparseValues.dtype){
|
|
case "bool":
|
|
{
|
|
const updatesBuf = backend.bufferSync(sparseValues);
|
|
const $defaultValue = Boolean(backend.data.get(defaultValue.dataId).values[0]);
|
|
outBuf = (0, _scatterImpl.scatterImpl)(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
|
|
break;
|
|
}
|
|
case "float32":
|
|
{
|
|
const updatesBuf = backend.bufferSync(sparseValues);
|
|
const $defaultValue = backend.data.get(defaultValue.dataId).values[0];
|
|
outBuf = (0, _scatterImpl.scatterImpl)(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
|
|
break;
|
|
}
|
|
case "int32":
|
|
{
|
|
const updatesBuf = backend.bufferSync(sparseValues);
|
|
const $defaultValue = backend.data.get(defaultValue.dataId).values[0];
|
|
outBuf = (0, _scatterImpl.scatterImpl)(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
|
|
break;
|
|
}
|
|
case "string":
|
|
{
|
|
const updatesBuf = backend.bufferSync(sparseValues);
|
|
const $defaultValue = (0, _tfjsCore.util).decodeString(backend.data.get(defaultValue.dataId).values[0]);
|
|
outBuf = (0, _scatterImpl.scatterImpl)(indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);
|
|
break;
|
|
}
|
|
default:
|
|
throw new Error(`Unsupported type ${sparseValues.dtype}`);
|
|
}
|
|
return backend.makeTensorInfo(outputShape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const sparseToDenseConfig = {
|
|
kernelName: (0, _tfjsCore.SparseToDense),
|
|
backendName: "cpu",
|
|
kernelFunc: sparseToDense
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Scatter_impl":"kMt6f","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"j2Sbu":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "splitV", ()=>splitV);
|
|
parcelHelpers.export(exports, "splitVConfig", ()=>splitVConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _slice = require("./Slice");
|
|
function splitV(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { numOrSizeSplits, axis } = attrs;
|
|
const $axis = (0, _tfjsCore.util).parseAxisParam(axis, x.shape)[0];
|
|
const splitSizes = (0, _tfjsCore.backend_util).prepareSplitSize(x, numOrSizeSplits, $axis);
|
|
const begin = new Array(x.shape.length).fill(0);
|
|
const size = x.shape.slice();
|
|
return splitSizes.map((s)=>{
|
|
const sliceSize = [
|
|
...size
|
|
];
|
|
sliceSize[$axis] = s;
|
|
const sliceT = (0, _slice.slice)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin,
|
|
size: sliceSize
|
|
}
|
|
});
|
|
begin[$axis] += s;
|
|
return sliceT;
|
|
});
|
|
}
|
|
const splitVConfig = {
|
|
kernelName: (0, _tfjsCore.SplitV),
|
|
backendName: "cpu",
|
|
kernelFunc: splitV
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Slice":"9L9GN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jjLIw":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "squareConfig", ()=>squareConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
const squareConfig = {
|
|
kernelName: (0, _tfjsCore.Square),
|
|
backendName: "cpu",
|
|
kernelFunc: ({ inputs, backend })=>{
|
|
const { x } = inputs;
|
|
const cpuBackend = backend;
|
|
(0, _cpuUtil.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
|
|
};
|
|
}
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"2cqHx":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "step", ()=>step);
|
|
parcelHelpers.export(exports, "stepConfig", ()=>stepConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const step = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Step), (xi, attrs)=>{
|
|
const stepAttrs = attrs;
|
|
if (isNaN(xi)) return NaN;
|
|
else return xi > 0 ? 1 : stepAttrs.alpha;
|
|
});
|
|
const stepConfig = {
|
|
kernelName: (0, _tfjsCore.Step),
|
|
backendName: "cpu",
|
|
kernelFunc: step
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"l76iO":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stridedSlice", ()=>stridedSlice);
|
|
parcelHelpers.export(exports, "stridedSliceConfig", ()=>stridedSliceConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _reshape = require("./Reshape");
|
|
var _slice = require("./Slice");
|
|
var _stridedSliceImpl = require("./StridedSlice_impl");
|
|
function stridedSlice(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "stridedSlice");
|
|
const { finalShapeSparse, finalShape, isIdentity, sliceDim0, isSimpleSlice, begin: $begin, end: $end, strides: $strides } = (0, _tfjsCore.slice_util).sliceInfo(x.shape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask);
|
|
let result;
|
|
// ref:
|
|
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/strided_slice_op.cc
|
|
if (isIdentity) // Optimization #1, slice is a no-op plus reshape
|
|
result = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: finalShape
|
|
}
|
|
});
|
|
else if (sliceDim0 || isSimpleSlice) {
|
|
// Optimization #2, slice is memory contiguous (only occurs in dim 0)
|
|
(0, _tfjsCore.util).assert(x.shape.length >= 1, ()=>`Input must have rank at least 1, got: ${x.shape.length}`);
|
|
const size = (0, _tfjsCore.slice_util).computeOutShape($begin, $end, $strides);
|
|
// To tolerate begin[0] > end[0] (a 0-output slice), we min(begin, end).
|
|
const sliced = (0, _slice.slice)({
|
|
inputs: {
|
|
x
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin: $begin,
|
|
size
|
|
}
|
|
});
|
|
result = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: sliced
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: finalShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(sliced);
|
|
} else {
|
|
const xBuf = backend.bufferSync(x);
|
|
const outBuf = (0, _stridedSliceImpl.stridedSliceImpl)(finalShapeSparse, xBuf, $strides, $begin);
|
|
result = backend.makeTensorInfo(finalShape, outBuf.dtype, outBuf.values);
|
|
}
|
|
return result;
|
|
}
|
|
const stridedSliceConfig = {
|
|
kernelName: (0, _tfjsCore.StridedSlice),
|
|
backendName: "cpu",
|
|
kernelFunc: stridedSlice
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Reshape":"9350i","./Slice":"9L9GN","./StridedSlice_impl":"kCJo9","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"7Beq9":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringNGrams", ()=>stringNGrams);
|
|
parcelHelpers.export(exports, "stringNGramsConfig", ()=>stringNGramsConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _stringNGramsImpl = require("./StringNGrams_impl");
|
|
function stringNGrams(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences } = attrs;
|
|
const { data, dataSplits } = inputs;
|
|
const $data = backend.data.get(data.dataId).values;
|
|
const $dataSplits = backend.data.get(dataSplits.dataId).values;
|
|
const [nGrams, nGramsSplits] = (0, _stringNGramsImpl.stringNGramsImpl)($data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences);
|
|
return [
|
|
backend.makeTensorInfo([
|
|
nGrams.length
|
|
], "string", nGrams),
|
|
backend.makeTensorInfo(dataSplits.shape, "int32", nGramsSplits)
|
|
];
|
|
}
|
|
const stringNGramsConfig = {
|
|
kernelName: (0, _tfjsCore.StringNGrams),
|
|
backendName: "cpu",
|
|
kernelFunc: stringNGrams
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./StringNGrams_impl":"3rAXp","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"6TsmC":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringSplit", ()=>stringSplit);
|
|
parcelHelpers.export(exports, "stringSplitConfig", ()=>stringSplitConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _stringSplitImpl = require("./StringSplit_impl");
|
|
function stringSplit(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { skipEmpty } = attrs;
|
|
const { input, delimiter } = inputs;
|
|
if (input.dtype !== "string") throw new Error("Input must be of datatype string");
|
|
if (input.shape.length !== 1) throw new Error(`Input must be a vector, got shape: ${input.shape}`);
|
|
if (delimiter.shape.length !== 0) throw new Error(`Delimiter must be a scalar, got shape: ${delimiter.shape}`);
|
|
const $input = backend.data.get(input.dataId).values;
|
|
const $delimiter = backend.data.get(delimiter.dataId).values[0];
|
|
const [indices, values, shape] = (0, _stringSplitImpl.stringSplitImpl)($input, $delimiter, skipEmpty);
|
|
const outputSize = values.length;
|
|
return [
|
|
backend.makeTensorInfo([
|
|
outputSize,
|
|
2
|
|
], "int32", indices),
|
|
backend.makeTensorInfo([
|
|
outputSize
|
|
], "string", values),
|
|
backend.makeTensorInfo([
|
|
2
|
|
], "int32", new Int32Array(shape))
|
|
];
|
|
}
|
|
const stringSplitConfig = {
|
|
kernelName: (0, _tfjsCore.StringSplit),
|
|
backendName: "cpu",
|
|
kernelFunc: stringSplit
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./StringSplit_impl":"8xmpZ","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"irRRx":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "stringToHashBucketFast", ()=>stringToHashBucketFast);
|
|
parcelHelpers.export(exports, "stringToHashBucketFastConfig", ()=>stringToHashBucketFastConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _stringToHashBucketFastImpl = require("./StringToHashBucketFast_impl");
|
|
function stringToHashBucketFast(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { numBuckets } = attrs;
|
|
const { input } = inputs;
|
|
if (input.dtype !== "string") throw new Error("Input must be of datatype string");
|
|
if (numBuckets <= 0) throw new Error(`Number of buckets must be at least 1`);
|
|
const $input = backend.data.get(input.dataId).values;
|
|
const output = (0, _stringToHashBucketFastImpl.stringToHashBucketFastImpl)($input, numBuckets);
|
|
return backend.makeTensorInfo(input.shape, "int32", output);
|
|
}
|
|
const stringToHashBucketFastConfig = {
|
|
kernelName: (0, _tfjsCore.StringToHashBucketFast),
|
|
backendName: "cpu",
|
|
kernelFunc: stringToHashBucketFast
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./StringToHashBucketFast_impl":"6jwLv","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"aMIl2":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tan", ()=>tan);
|
|
parcelHelpers.export(exports, "tanConfig", ()=>tanConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const tan = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Tan), (xi)=>Math.tan(xi));
|
|
const tanConfig = {
|
|
kernelName: (0, _tfjsCore.Tan),
|
|
backendName: "cpu",
|
|
kernelFunc: tan
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"fdqiG":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tanh", ()=>tanh);
|
|
parcelHelpers.export(exports, "tanhConfig", ()=>tanhConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _unaryUtils = require("../utils/unary_utils");
|
|
const tanh = (0, _unaryUtils.unaryKernelFunc)((0, _tfjsCore.Tanh), (xi)=>Math.tanh(xi));
|
|
const tanhConfig = {
|
|
kernelName: (0, _tfjsCore.Tanh),
|
|
backendName: "cpu",
|
|
kernelFunc: tanh
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../utils/unary_utils":"5johK","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"jFIwa":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tensorScatterUpdate", ()=>tensorScatterUpdate);
|
|
parcelHelpers.export(exports, "tensorScatterUpdateConfig", ()=>tensorScatterUpdateConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _scatterImpl = require("./Scatter_impl");
|
|
function tensorScatterUpdate(args) {
|
|
const { inputs, backend } = args;
|
|
const { tensor, indices, updates } = inputs;
|
|
const { sliceRank, numUpdates, sliceSize, strides, outputSize } = (0, _tfjsCore.backend_util).calculateShapes(updates, indices, tensor.shape);
|
|
const sumDupeIndices = false;
|
|
const indicesBuf = backend.bufferSync(indices);
|
|
const updatesBuf = backend.bufferSync(updates);
|
|
const tensorBuf = backend.bufferSync(tensor);
|
|
const outBuf = (0, _scatterImpl.scatterImpl)(indicesBuf, updatesBuf, tensor.shape, outputSize, sliceSize, numUpdates, sliceRank, strides, tensorBuf, sumDupeIndices);
|
|
return backend.makeTensorInfo(tensor.shape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const tensorScatterUpdateConfig = {
|
|
kernelName: (0, _tfjsCore.TensorScatterUpdate),
|
|
backendName: "cpu",
|
|
kernelFunc: tensorScatterUpdate
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Scatter_impl":"kMt6f","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"cYsKW":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "tile", ()=>tile);
|
|
parcelHelpers.export(exports, "tileConfig", ()=>tileConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _tileImpl = require("./Tile_impl");
|
|
function tile(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { reps } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "tile");
|
|
const outBuf = (0, _tileImpl.tileImpl)(backend.bufferSync(x), reps);
|
|
return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
|
|
}
|
|
const tileConfig = {
|
|
kernelName: (0, _tfjsCore.Tile),
|
|
backendName: "cpu",
|
|
kernelFunc: tile
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Tile_impl":"7g2re","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9RDRk":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "topK", ()=>topK);
|
|
parcelHelpers.export(exports, "topKConfig", ()=>topKConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _topKImpl = require("./TopK_impl");
|
|
function topK(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x } = inputs;
|
|
const { k, sorted } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "topk");
|
|
const xVals = backend.data.get(x.dataId).values;
|
|
const [allTopKVals, allTopKIndices] = (0, _topKImpl.topKImpl)(xVals, x.shape, x.dtype, k, sorted);
|
|
return [
|
|
backend.makeTensorInfo(allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),
|
|
backend.makeTensorInfo(allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)
|
|
];
|
|
}
|
|
const topKConfig = {
|
|
kernelName: (0, _tfjsCore.TopK),
|
|
backendName: "cpu",
|
|
kernelFunc: topK
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./TopK_impl":"dl1sf","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"hKZ0R":[function(require,module,exports) {
|
|
/**
|
|
* @license
|
|
* Copyright 2021 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 parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "transform", ()=>transform);
|
|
parcelHelpers.export(exports, "transformConfig", ()=>transformConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
function transform(args) {
|
|
const { inputs, attrs, backend } = args;
|
|
const { image, transforms } = inputs;
|
|
const { interpolation, fillMode, fillValue, outputShape } = attrs;
|
|
const [batch, imageHeight, imageWidth, numChannels] = image.shape;
|
|
const [outHeight, outWidth] = outputShape != null ? outputShape : [
|
|
imageHeight,
|
|
imageWidth
|
|
];
|
|
const outShape = [
|
|
batch,
|
|
outHeight,
|
|
outWidth,
|
|
numChannels
|
|
];
|
|
const inStrides = (0, _tfjsCore.util).computeStrides(image.shape);
|
|
const batchInStride = inStrides[0];
|
|
const rowInStride = inStrides[1];
|
|
const colInStride = inStrides[2];
|
|
const outStrides = (0, _tfjsCore.util).computeStrides(outShape);
|
|
const batchOutStride = outStrides[0];
|
|
const rowOutStride = outStrides[1];
|
|
const colOutStride = outStrides[2];
|
|
const outVals = (0, _tfjsCore.util).getTypedArrayFromDType(image.dtype, (0, _tfjsCore.util).sizeFromShape(outShape));
|
|
outVals.fill(fillValue);
|
|
const imageVals = backend.data.get(image.dataId).values;
|
|
const transformVals = backend.data.get(transforms.dataId).values;
|
|
// Ref TF implementation:
|
|
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/image/image_ops.h
|
|
for(let b = 0; b < batch; ++b){
|
|
const transform = transforms.shape[0] === 1 ? transformVals : transformVals.subarray(b * 8, b * 8 + 8);
|
|
for(let outY = 0; outY < outHeight; ++outY){
|
|
for(let outX = 0; outX < outWidth; ++outX)for(let channel = 0; channel < numChannels; ++channel){
|
|
let val;
|
|
const projection = transform[6] * outX + transform[7] * outY + 1;
|
|
if (projection === 0) continue;
|
|
const inX = (transform[0] * outX + transform[1] * outY + transform[2]) / projection;
|
|
const inY = (transform[3] * outX + transform[4] * outY + transform[5]) / projection;
|
|
const x = mapCoord(inX, imageWidth, fillMode);
|
|
const y = mapCoord(inY, imageHeight, fillMode);
|
|
switch(interpolation){
|
|
case "nearest":
|
|
val = nearestInterpolation(imageVals, imageHeight, imageWidth, batchInStride, rowInStride, colInStride, b, y, x, channel, fillValue);
|
|
break;
|
|
case "bilinear":
|
|
val = bilinearInterpolation(imageVals, imageHeight, imageWidth, batchInStride, rowInStride, colInStride, b, y, x, channel, fillValue);
|
|
break;
|
|
default:
|
|
throw new Error(`Error in Transform: Expect 'nearest' or ` + `'bilinear', but got ${interpolation}`);
|
|
}
|
|
const ind = b * batchOutStride + outY * rowOutStride + outX * colOutStride + channel;
|
|
outVals[ind] = val;
|
|
}
|
|
}
|
|
return backend.makeTensorInfo(outShape, image.dtype, outVals);
|
|
}
|
|
const dataId = backend.write(outVals, outShape, image.dtype);
|
|
return {
|
|
dataId,
|
|
shape: image.shape,
|
|
dtype: image.dtype
|
|
};
|
|
}
|
|
const transformConfig = {
|
|
kernelName: (0, _tfjsCore.Transform),
|
|
backendName: "cpu",
|
|
kernelFunc: transform
|
|
};
|
|
function mapCoord(outCoord, len, mode) {
|
|
switch(mode){
|
|
case "reflect":
|
|
return mapCoordReflect(outCoord, len);
|
|
case "wrap":
|
|
return mapCoordWrap(outCoord, len);
|
|
case "nearest":
|
|
return mapCoordNearest(outCoord, len);
|
|
case "constant":
|
|
default:
|
|
return mapCoordConstant(outCoord, len);
|
|
}
|
|
}
|
|
function mapCoordReflect(outCoord, len) {
|
|
// Reflect [abcd] to [dcba|abcd|dcba].
|
|
let inCoord = outCoord;
|
|
if (inCoord < 0) {
|
|
if (len <= 1) inCoord = 0;
|
|
else {
|
|
const sz2 = 2 * len;
|
|
if (inCoord < sz2) inCoord = sz2 * Math.trunc(-inCoord / sz2) + inCoord;
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1;
|
|
}
|
|
} else if (inCoord > len - 1) {
|
|
if (len <= 1) inCoord = 0;
|
|
else {
|
|
const sz2 = 2 * len;
|
|
inCoord -= sz2 * Math.trunc(inCoord / sz2);
|
|
if (inCoord >= len) inCoord = sz2 - inCoord - 1;
|
|
}
|
|
}
|
|
// clamp is necessary because when outCoord = 3.5 and len = 4,
|
|
// inCoord = 3.5 and will be rounded to 4 in nearest interpolation.
|
|
return (0, _tfjsCore.util).clamp(0, inCoord, len - 1);
|
|
}
|
|
function mapCoordWrap(outCoord, len) {
|
|
// Wrap [abcd] to [abcd|abcd|abcd].
|
|
let inCoord = outCoord;
|
|
if (inCoord < 0) {
|
|
if (len <= 1) inCoord = 0;
|
|
else {
|
|
const sz = len - 1;
|
|
inCoord += len * (Math.trunc(-inCoord / sz) + 1);
|
|
}
|
|
} else if (inCoord > len - 1) {
|
|
if (len <= 1) inCoord = 0;
|
|
else {
|
|
const sz = len - 1;
|
|
inCoord -= len * Math.trunc(inCoord / sz);
|
|
}
|
|
}
|
|
// clamp is necessary because when outCoord = -0.5 and len = 4,
|
|
// inCoord = 3.5 and will be rounded to 4 in nearest interpolation.
|
|
return (0, _tfjsCore.util).clamp(0, inCoord, len - 1);
|
|
}
|
|
function mapCoordConstant(outCoord, len) {
|
|
return outCoord;
|
|
}
|
|
function mapCoordNearest(outCoord, len) {
|
|
return (0, _tfjsCore.util).clamp(0, outCoord, len - 1);
|
|
}
|
|
function readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, y, x, channel, fillValue) {
|
|
const ind = batch * batchStride + y * rowStride + x * colStride + channel;
|
|
if (0 <= y && y < imageHeight && 0 <= x && x < imageWidth) return imageVals[ind];
|
|
else return fillValue;
|
|
}
|
|
function nearestInterpolation(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, y, x, channel, fillValue) {
|
|
const $y = Math.round(y);
|
|
const $x = Math.round(x);
|
|
return readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, $y, $x, channel, fillValue);
|
|
}
|
|
function bilinearInterpolation(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, y, x, channel, fillValue) {
|
|
const yFloor = Math.floor(y);
|
|
const xFloor = Math.floor(x);
|
|
const yCeil = yFloor + 1;
|
|
const xCeil = xFloor + 1;
|
|
// f(x, yFloor) = (xCeil - x) / (xCeil - xFloor) * f(xFloor, yFloor)
|
|
// + (x - xFloor) / (xCeil - xFloor) * f(xCeil, yFloor)
|
|
const valueYFloor = (xCeil - x) * readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, yFloor, xFloor, channel, fillValue) + (x - xFloor) * readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, yFloor, xCeil, channel, fillValue);
|
|
// f(x, yCeil) = (xCeil - x) / (xCeil - xFloor) * f(xFloor, yCeil)
|
|
// + (x - xFloor) / (xCeil - xFloor) * f(xCeil, yCeil)
|
|
const valueYCeil = (xCeil - x) * readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, yCeil, xFloor, channel, fillValue) + (x - xFloor) * readWithFillValue(imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride, batch, yCeil, xCeil, channel, fillValue);
|
|
// f(x, y) = (yCeil - y) / (yCeil - yFloor) * f(x, yFloor)
|
|
// + (y - yFloor) / (yCeil - yFloor) * f(x, yCeil)
|
|
return (yCeil - y) * valueYFloor + (y - yFloor) * valueYCeil;
|
|
}
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"9nca3":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unique", ()=>unique);
|
|
parcelHelpers.export(exports, "uniqueConfig", ()=>uniqueConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _uniqueImpl = require("./Unique_impl");
|
|
function unique(args) {
|
|
const { inputs, attrs, backend } = args;
|
|
const { axis } = attrs;
|
|
const { x } = inputs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "unique");
|
|
const values = backend.data.get(x.dataId).values;
|
|
const { outputValues, outputShape, indices } = (0, _uniqueImpl.uniqueImpl)(values, axis, x.shape, x.dtype);
|
|
return [
|
|
backend.makeTensorInfo(outputShape, x.dtype, outputValues),
|
|
backend.makeTensorInfo([
|
|
indices.length
|
|
], "int32", indices)
|
|
];
|
|
}
|
|
const uniqueConfig = {
|
|
kernelName: (0, _tfjsCore.Unique),
|
|
backendName: "cpu",
|
|
kernelFunc: unique
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Unique_impl":"gLexL","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"iIwqM":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unpack", ()=>unpack);
|
|
parcelHelpers.export(exports, "unpackConfig", ()=>unpackConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _reshape = require("./Reshape");
|
|
var _slice = require("./Slice");
|
|
function unpack(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { value } = inputs;
|
|
let { axis } = attrs;
|
|
if (axis < 0) axis += value.shape.length;
|
|
const valueRank = value.shape.length;
|
|
const num = value.shape[axis];
|
|
const outShape = new Array(valueRank - 1);
|
|
let outIndex = 0;
|
|
for(let i = 0; i < valueRank; i++)if (i !== axis) outShape[outIndex++] = value.shape[i];
|
|
const begin = new Array(valueRank).fill(0);
|
|
const size = value.shape.slice();
|
|
size[axis] = 1;
|
|
const res = new Array(num);
|
|
for(let i = 0; i < res.length; i++){
|
|
begin[axis] = i;
|
|
const tempRes = (0, _slice.slice)({
|
|
inputs: {
|
|
x: value
|
|
},
|
|
backend,
|
|
attrs: {
|
|
begin,
|
|
size
|
|
}
|
|
});
|
|
res[i] = (0, _reshape.reshape)({
|
|
inputs: {
|
|
x: tempRes
|
|
},
|
|
backend,
|
|
attrs: {
|
|
shape: outShape
|
|
}
|
|
});
|
|
backend.disposeIntermediateTensorInfo(tempRes);
|
|
}
|
|
return res;
|
|
}
|
|
const unpackConfig = {
|
|
kernelName: (0, _tfjsCore.Unpack),
|
|
backendName: "cpu",
|
|
kernelFunc: unpack
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","./Reshape":"9350i","./Slice":"9L9GN","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}],"eWcTc":[function(require,module,exports) {
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/ var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
|
|
parcelHelpers.defineInteropFlag(exports);
|
|
parcelHelpers.export(exports, "unsortedSegmentSum", ()=>unsortedSegmentSum);
|
|
parcelHelpers.export(exports, "unsortedSegmentSumConfig", ()=>unsortedSegmentSumConfig);
|
|
var _tfjsCore = require("@tensorflow/tfjs-core");
|
|
var _cpuUtil = require("../cpu_util");
|
|
var _cast = require("./Cast");
|
|
var _equal = require("./Equal");
|
|
var _expandDims = require("./ExpandDims");
|
|
var _multiply = require("./Multiply");
|
|
var _pack = require("./Pack");
|
|
var _sum = require("./Sum");
|
|
function unsortedSegmentSum(args) {
|
|
const { inputs, backend, attrs } = args;
|
|
const { x, segmentIds } = inputs;
|
|
const { numSegments } = attrs;
|
|
(0, _cpuUtil.assertNotComplex)(x, "unsortedSegmentSum");
|
|
const xRank = x.shape.length;
|
|
const segmentIdsRank = segmentIds.shape.length;
|
|
const res = [];
|
|
const intermediates = [];
|
|
// Reshape the segment id's so that they can be broadcast with
|
|
// x. The new shape should be [segmentIds.shape, 1, ..., 1]
|
|
const numIters = xRank - segmentIdsRank;
|
|
let $segmentIds = segmentIds;
|
|
for(let i = 0; i < numIters; ++i){
|
|
const expanded = (0, _expandDims.expandDims)({
|
|
inputs: {
|
|
input: $segmentIds
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dim: i + 1
|
|
}
|
|
});
|
|
$segmentIds = expanded;
|
|
intermediates.push(expanded);
|
|
}
|
|
for(let i = 0; i < numSegments; ++i){
|
|
const scalarValue = (0, _tfjsCore.util).createScalarValue(i, "int32");
|
|
const segmentId = backend.makeTensorInfo([], "int32", scalarValue);
|
|
const mask = (0, _equal.equal)({
|
|
inputs: {
|
|
a: segmentId,
|
|
b: $segmentIds
|
|
},
|
|
backend
|
|
});
|
|
const maskCasted = (0, _cast.cast)({
|
|
inputs: {
|
|
x: mask
|
|
},
|
|
backend,
|
|
attrs: {
|
|
dtype: "float32"
|
|
}
|
|
});
|
|
const mul = (0, _multiply.multiply)({
|
|
inputs: {
|
|
a: maskCasted,
|
|
b: x
|
|
},
|
|
backend
|
|
});
|
|
const sumTensorInfo = (0, _sum.sum)({
|
|
inputs: {
|
|
x: mul
|
|
},
|
|
backend,
|
|
attrs: {
|
|
axis: 0,
|
|
keepDims: false
|
|
}
|
|
});
|
|
res.push(sumTensorInfo);
|
|
intermediates.push(segmentId);
|
|
intermediates.push(mask);
|
|
intermediates.push(maskCasted);
|
|
intermediates.push(mul);
|
|
intermediates.push(sumTensorInfo);
|
|
}
|
|
const result = (0, _pack.pack)({
|
|
inputs: res,
|
|
backend,
|
|
attrs: {
|
|
axis: 0
|
|
}
|
|
});
|
|
intermediates.forEach((t)=>backend.disposeIntermediateTensorInfo(t));
|
|
return result;
|
|
}
|
|
const unsortedSegmentSumConfig = {
|
|
kernelName: (0, _tfjsCore.UnsortedSegmentSum),
|
|
backendName: "cpu",
|
|
kernelFunc: unsortedSegmentSum
|
|
};
|
|
|
|
},{"@tensorflow/tfjs-core":"21Ftl","../cpu_util":"1l037","./Cast":"fAtIw","./Equal":"jK2O7","./ExpandDims":"4z77l","./Multiply":"FrRi2","./Pack":"3NDYm","./Sum":"6gbbV","@parcel/transformer-js/src/esmodule-helpers.js":"5dUr6"}]},["8uLJa"], "8uLJa", "parcelRequire4dc0")
|
|
|
|
//# sourceMappingURL=index.js.map
|