UNPKG

@tensorflow/tfjs-core

Version:

Hardware-accelerated JavaScript library for machine intelligence

1,424 lines (1,299 loc) 633 kB
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.tfc = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){ },{}],2:[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('./lib/alea'); // xor128, a pure xor-shift generator by George Marsaglia. // Period: 2^128-1. // Reported to fail: MatrixRank and LinearComp. var xor128 = require('./lib/xor128'); // 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('./lib/xorwow'); // 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('./lib/xorshift7'); // 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('./lib/xor4096'); // 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('./lib/tychei'); // The original ARC4-based prng included in this library. // Period: ~2^1600 var sr = require('./seedrandom'); sr.alea = alea; sr.xor128 = xor128; sr.xorwow = xorwow; sr.xorshift7 = xorshift7; sr.xor4096 = xor4096; sr.tychei = tychei; module.exports = sr; },{"./lib/alea":3,"./lib/tychei":4,"./lib/xor128":5,"./lib/xor4096":6,"./lib/xorshift7":7,"./lib/xorwow":8,"./seedrandom":9}],3:[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, module, define) { function Alea(seed) { var me = this, mash = Mash(); me.next = function() { var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32 me.s0 = me.s1; me.s1 = me.s2; return me.s2 = t - (me.c = t | 0); }; // Apply the seeding algorithm from Baagoe. me.c = 1; me.s0 = mash(' '); me.s1 = mash(' '); me.s2 = mash(' '); me.s0 -= mash(seed); if (me.s0 < 0) { me.s0 += 1; } me.s1 -= mash(seed); if (me.s1 < 0) { me.s1 += 1; } me.s2 -= mash(seed); if (me.s2 < 0) { me.s2 += 1; } mash = null; } function copy(f, t) { t.c = f.c; t.s0 = f.s0; t.s1 = f.s1; t.s2 = f.s2; return t; } function impl(seed, opts) { var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; prng.int32 = function() { return (xg.next() * 0x100000000) | 0; } prng.double = function() { return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 }; prng.quick = prng; if (state) { if (typeof(state) == 'object') copy(state, xg); prng.state = function() { return copy(xg, {}); } } return prng; } function Mash() { var n = 0xefc8249d; var mash = function(data) { data = data.toString(); for (var i = 0; i < data.length; i++) { n += data.charCodeAt(i); var h = 0.02519603282416938 * n; n = h >>> 0; h -= n; h *= n; n = h >>> 0; h -= n; n += h * 0x100000000; // 2^32 } return (n >>> 0) * 2.3283064365386963e-10; // 2^-32 }; return mash; } if (module && module.exports) { module.exports = impl; } else if (define && define.amd) { define(function() { return impl; }); } else { this.alea = impl; } })( this, (typeof module) == 'object' && module, // present in node.js (typeof define) == 'function' && define // present with an AMD loader ); },{}],4:[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, module, define) { function XorGen(seed) { var me = this, strseed = ''; // Set up generator function. me.next = function() { var b = me.b, c = me.c, d = me.d, a = me.a; b = (b << 25) ^ (b >>> 7) ^ c; c = (c - d) | 0; d = (d << 24) ^ (d >>> 8) ^ a; a = (a - b) | 0; me.b = b = (b << 20) ^ (b >>> 12) ^ c; me.c = c = (c - d) | 0; me.d = (d << 16) ^ (c >>> 16) ^ a; return me.a = (a - b) | 0; }; /* The following is non-inverted tyche, which has better internal * bit diffusion, but which is about 25% slower than tyche-i in JS. me.next = function() { var a = me.a, b = me.b, c = me.c, d = me.d; a = (me.a + me.b | 0) >>> 0; d = me.d ^ a; d = d << 16 ^ d >>> 16; c = me.c + d | 0; b = me.b ^ c; b = b << 12 ^ d >>> 20; me.a = a = a + b | 0; d = d ^ a; me.d = d = d << 8 ^ d >>> 24; me.c = c = c + d | 0; b = b ^ c; return me.b = (b << 7 ^ b >>> 25); } */ me.a = 0; me.b = 0; me.c = 2654435769 | 0; me.d = 1367130551; if (seed === Math.floor(seed)) { // Integer seed. me.a = (seed / 0x100000000) | 0; me.b = seed | 0; } else { // String seed. strseed += seed; } // Mix in string seed, then discard an initial batch of 64 values. for (var k = 0; k < strseed.length + 20; k++) { me.b ^= strseed.charCodeAt(k) | 0; me.next(); } } function copy(f, t) { t.a = f.a; t.b = f.b; t.c = f.c; t.d = f.d; return t; }; function impl(seed, opts) { var xg = new XorGen(seed), state = opts && opts.state, prng = function() { return (xg.next() >>> 0) / 0x100000000; }; prng.double = function() { do { var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 0x100000000, result = (top + bot) / (1 << 21); } while (result === 0); return result; }; prng.int32 = xg.next; prng.quick = prng; if (state) { if (typeof(state) == 'object') copy(state, xg); prng.state = function() { return copy(xg, {}); } } return prng; } if (module && module.exports) { module.exports = impl; } else if (define && define.amd) { define(function() { return impl; }); } else { this.tychei = impl; } })( this, (typeof module) == 'object' && module, // present in node.js (typeof define) == 'function' && define // present with an AMD loader ); },{}],5:[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, module, define) { function XorGen(seed) { var me = this, strseed = ''; me.x = 0; me.y = 0; me.z = 0; me.w = 0; // Set up generator function. me.next = function() { var t = me.x ^ (me.x << 11); me.x = me.y; me.y = me.z; me.z = me.w; return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8); }; if (seed === (seed | 0)) { // Integer seed. me.x = seed; } else { // String seed. strseed += seed; } // Mix in string seed, then discard an initial batch of 64 values. for (var k = 0; k < strseed.length + 64; k++) { me.x ^= strseed.charCodeAt(k) | 0; me.next(); } } function copy(f, t) { t.x = f.x; t.y = f.y; t.z = f.z; t.w = f.w; return t; } function impl(seed, opts) { var xg = new XorGen(seed), state = opts && opts.state, prng = function() { return (xg.next() >>> 0) / 0x100000000; }; prng.double = function() { do { var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 0x100000000, result = (top + bot) / (1 << 21); } while (result === 0); return result; }; prng.int32 = xg.next; prng.quick = prng; if (state) { if (typeof(state) == 'object') copy(state, xg); prng.state = function() { return copy(xg, {}); } } return prng; } if (module && module.exports) { module.exports = impl; } else if (define && define.amd) { define(function() { return impl; }); } else { this.xor128 = impl; } })( this, (typeof module) == 'object' && module, // present in node.js (typeof define) == 'function' && define // present with an AMD loader ); },{}],6:[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, module, define) { function XorGen(seed) { var me = this; // Set up generator function. me.next = function() { var w = me.w, X = me.X, i = me.i, t, v; // Update Weyl generator. me.w = w = (w + 0x61c88647) | 0; // Update xor generator. v = X[(i + 34) & 127]; t = X[i = ((i + 1) & 127)]; v ^= v << 13; t ^= t << 17; v ^= v >>> 15; t ^= t >>> 12; // Update Xor generator array state. v = X[i] = v ^ t; me.i = i; // Result is the combination. return (v + (w ^ (w >>> 16))) | 0; }; function init(me, seed) { var t, v, i, j, w, X = [], limit = 128; if (seed === (seed | 0)) { // Numeric seeds initialize v, which is used to generates X. v = seed; seed = null; } else { // String seeds are mixed into v and X one character at a time. seed = seed + '\0'; v = 0; limit = Math.max(limit, seed.length); } // Initialize circular array and weyl value. for (i = 0, j = -32; j < limit; ++j) { // Put the unicode characters into the array, and shuffle them. if (seed) v ^= seed.charCodeAt((j + 32) % seed.length); // After 32 shuffles, take v as the starting w value. if (j === 0) w = v; v ^= v << 10; v ^= v >>> 15; v ^= v << 4; v ^= v >>> 13; if (j >= 0) { w = (w + 0x61c88647) | 0; // Weyl. t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array. i = (0 == t) ? i + 1 : 0; // Count zeroes. } } // We have detected all zeroes; make the key nonzero. if (i >= 128) { X[(seed && seed.length || 0) & 127] = -1; } // Run the generator 512 times to further mix the state before using it. // Factoring this as a function slows the main generator, so it is just // unrolled here. The weyl generator is not advanced while warming up. i = 127; for (j = 4 * 128; j > 0; --j) { v = X[(i + 34) & 127]; t = X[i = ((i + 1) & 127)]; v ^= v << 13; t ^= t << 17; v ^= v >>> 15; t ^= t >>> 12; X[i] = v ^ t; } // Storing state as object members is faster than using closure variables. me.w = w; me.X = X; me.i = i; } init(me, seed); } function copy(f, t) { t.i = f.i; t.w = f.w; t.X = f.X.slice(); return t; }; function impl(seed, opts) { if (seed == null) seed = +(new Date); var xg = new XorGen(seed), state = opts && opts.state, prng = function() { return (xg.next() >>> 0) / 0x100000000; }; prng.double = function() { do { var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 0x100000000, result = (top + bot) / (1 << 21); } while (result === 0); return result; }; prng.int32 = xg.next; prng.quick = prng; if (state) { if (state.X) copy(state, xg); prng.state = function() { return copy(xg, {}); } } return prng; } if (module && module.exports) { module.exports = impl; } else if (define && define.amd) { define(function() { return impl; }); } else { this.xor4096 = impl; } })( this, // window object or global (typeof module) == 'object' && module, // present in node.js (typeof define) == 'function' && define // present with an AMD loader ); },{}],7:[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, module, define) { function XorGen(seed) { var me = this; // Set up generator function. me.next = function() { // Update xor generator. var X = me.x, i = me.i, t, v, w; t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24); t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10); t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3); t = X[(i + 4) & 7]; v ^= t ^ (t << 7); t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9); X[i] = v; me.i = (i + 1) & 7; return v; }; function init(me, seed) { var j, w, X = []; if (seed === (seed | 0)) { // Seed state array using a 32-bit integer. w = X[0] = seed; } else { // Seed state using a string. seed = '' + seed; for (j = 0; j < seed.length; ++j) { X[j & 7] = (X[j & 7] << 15) ^ (seed.charCodeAt(j) + X[(j + 1) & 7] << 13); } } // Enforce an array length of 8, not all zeroes. while (X.length < 8) X.push(0); for (j = 0; j < 8 && X[j] === 0; ++j); if (j == 8) w = X[7] = -1; else w = X[j]; me.x = X; me.i = 0; // Discard an initial 256 values. for (j = 256; j > 0; --j) { me.next(); } } init(me, seed); } function copy(f, t) { t.x = f.x.slice(); t.i = f.i; return t; } function impl(seed, opts) { if (seed == null) seed = +(new Date); var xg = new XorGen(seed), state = opts && opts.state, prng = function() { return (xg.next() >>> 0) / 0x100000000; }; prng.double = function() { do { var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 0x100000000, result = (top + bot) / (1 << 21); } while (result === 0); return result; }; prng.int32 = xg.next; prng.quick = prng; if (state) { if (state.x) copy(state, xg); prng.state = function() { return copy(xg, {}); } } return prng; } if (module && module.exports) { module.exports = impl; } else if (define && define.amd) { define(function() { return impl; }); } else { this.xorshift7 = impl; } })( this, (typeof module) == 'object' && module, // present in node.js (typeof define) == 'function' && define // present with an AMD loader ); },{}],8:[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, module, define) { function XorGen(seed) { var me = this, strseed = ''; // Set up generator function. me.next = function() { var t = (me.x ^ (me.x >>> 2)); me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v; return (me.d = (me.d + 362437 | 0)) + (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0; }; me.x = 0; me.y = 0; me.z = 0; me.w = 0; me.v = 0; if (seed === (seed | 0)) { // Integer seed. me.x = seed; } else { // String seed. strseed += seed; } // Mix in string seed, then discard an initial batch of 64 values. for (var k = 0; k < strseed.length + 64; k++) { me.x ^= strseed.charCodeAt(k) | 0; if (k == strseed.length) { me.d = me.x << 10 ^ me.x >>> 4; } me.next(); } } function copy(f, t) { t.x = f.x; t.y = f.y; t.z = f.z; t.w = f.w; t.v = f.v; t.d = f.d; return t; } function impl(seed, opts) { var xg = new XorGen(seed), state = opts && opts.state, prng = function() { return (xg.next() >>> 0) / 0x100000000; }; prng.double = function() { do { var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 0x100000000, result = (top + bot) / (1 << 21); } while (result === 0); return result; }; prng.int32 = xg.next; prng.quick = prng; if (state) { if (typeof(state) == 'object') copy(state, xg); prng.state = function() { return copy(xg, {}); } } return prng; } if (module && module.exports) { module.exports = impl; } else if (define && define.amd) { define(function() { return impl; }); } else { this.xorwow = impl; } })( this, (typeof module) == 'object' && module, // present in node.js (typeof define) == 'function' && define // present with an AMD loader ); },{}],9:[function(require,module,exports){ /* Copyright 2014 David Bau. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function (pool, math) { // // The following constants are related to IEEE 754 limits. // var global = this, width = 256, // each RC4 output is 0 <= x < 256 chunks = 6, // at least six RC4 outputs for each double digits = 52, // there are 52 significant digits in a double rngname = 'random', // rngname: name for Math.random and Math.seedrandom startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto; // node.js crypto module, initialized at the bottom. // // seedrandom() // This is the seedrandom function described above. // function seedrandom(seed, options, callback) { var key = []; options = (options == true) ? { entropy: true } : (options || {}); // Flatten the seed string or build one from local entropy if needed. var shortseed = mixkey(flatten( options.entropy ? [seed, tostring(pool)] : (seed == null) ? autoseed() : seed, 3), key); // Use the seed to initialize an ARC4 generator. var arc4 = new ARC4(key); // This function returns a random double in [0, 1) that contains // randomness in every bit of the mantissa of the IEEE 754 value. var prng = function() { var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48 d = startdenom, // and denominator d = 2 ^ 48. x = 0; // and no 'extra last byte'. while (n < significance) { // Fill up all significant digits by n = (n + x) * width; // shifting numerator and d *= width; // denominator and generating a x = arc4.g(1); // new least-significant-byte. } while (n >= overflow) { // To avoid rounding up, before adding n /= 2; // last byte, shift everything d /= 2; // right using integer math until x >>>= 1; // we have exactly the desired bits. } return (n + x) / d; // Form the number within [0, 1). }; prng.int32 = function() { return arc4.g(4) | 0; } prng.quick = function() { return arc4.g(4) / 0x100000000; } prng.double = prng; // Mix the randomness into accumulated entropy. mixkey(tostring(arc4.S), pool); // Calling convention: what to return as a function of prng, seed, is_math. return (options.pass || callback || function(prng, seed, is_math_call, state) { if (state) { // Load the arc4 state from the given state if it has an S array. if (state.S) { copy(state, arc4); } // Only provide the .state method if requested via options.state. prng.state = function() { return copy(arc4, {}); } } // If called as a method of Math (Math.seedrandom()), mutate // Math.random because that is how seedrandom.js has worked since v1.0. if (is_math_call) { math[rngname] = prng; return seed; } // Otherwise, it is a newer calling convention, so return the // prng directly. else return prng; })( prng, shortseed, 'global' in options ? options.global : (this == math), options.state); } math['seed' + rngname] = seedrandom; // // ARC4 // // An ARC4 implementation. The constructor takes a key in the form of // an array of at most (width) integers that should be 0 <= x < (width). // // The g(count) method returns a pseudorandom integer that concatenates // the next (count) outputs from ARC4. Its return value is a number x // that is in the range 0 <= x < (width ^ count). // function ARC4(key) { var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; // The empty key [] is treated as [0]. if (!keylen) { key = [keylen++]; } // Set up S using the standard key scheduling algorithm. while (i < width) { s[i] = i++; } for (i = 0; i < width; i++) { s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))]; s[j] = t; } // The "g" method returns the next (count) outputs as one number. (me.g = function(count) { // Using instance members instead of closure state nearly doubles speed. var t, r = 0, i = me.i, j = me.j, s = me.S; while (count--) { t = s[i = mask & (i + 1)]; r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))]; } me.i = i; me.j = j; return r; // For robust unpredictability, the function call below automatically // discards an initial batch of values. This is called RC4-drop[256]. // See http://google.com/search?q=rsa+fluhrer+response&btnI })(width); } // // copy() // Copies internal state of ARC4 to or from a plain object. // function copy(f, t) { t.i = f.i; t.j = f.j; t.S = f.S.slice(); return t; }; // // flatten() // Converts an object tree to nested arrays of strings. // function flatten(obj, depth) { var result = [], typ = (typeof obj), prop; if (depth && typ == 'object') { for (prop in obj) { try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} } } return (result.length ? result : typ == 'string' ? obj : obj + '\0'); } // // mixkey() // Mixes a string seed into a key that is an array of integers, and // returns a shortened string seed that is equivalent to the result key. // function mixkey(seed, key) { var stringseed = seed + '', smear, j = 0; while (j < stringseed.length) { key[mask & j] = mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++)); } return tostring(key); } // // autoseed() // Returns an object for autoseeding, using window.crypto and Node crypto // module if available. // function autoseed() { try { var out; if (nodecrypto && (out = nodecrypto.randomBytes)) { // The use of 'out' to remember randomBytes makes tight minified code. out = out(width); } else { out = new Uint8Array(width); (global.crypto || global.msCrypto).getRandomValues(out); } return tostring(out); } catch (e) { var browser = global.navigator, plugins = browser && browser.plugins; return [+new Date, global, plugins, global.screen, tostring(pool)]; } } // // tostring() // Converts an array of charcodes to a string // function tostring(a) { return String.fromCharCode.apply(0, a); } // // When seedrandom.js is loaded, we immediately mix a few bits // from the built-in RNG into the entropy pool. Because we do // not want to interfere with deterministic PRNG state later, // seedrandom will not call math.random on its own again after // initialization. // mixkey(math.random(), pool); // // Nodejs and AMD support: export the implementation as a module using // either convention. // if ((typeof module) == 'object' && module.exports) { module.exports = seedrandom; // When in node.js, try using crypto package for autoseeding. try { nodecrypto = require('crypto'); } catch (ex) {} } else if ((typeof define) == 'function' && define.amd) { define(function() { return seedrandom; }); } // End anonymous scope, and pass initial values. })( [], // pool: entropy pool starts empty Math // math: package containing random, pow, and seedrandom ); },{"crypto":1}],10:[function(require,module,exports){ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var doc_1 = require("./doc"); var BrowserUtil = (function () { function BrowserUtil() { } BrowserUtil.nextFrame = function () { return new Promise(function (resolve) { return requestAnimationFrame(function () { return resolve(); }); }); }; __decorate([ doc_1.doc({ heading: 'Performance', subheading: 'Timing' }) ], BrowserUtil, "nextFrame", null); return BrowserUtil; }()); exports.BrowserUtil = BrowserUtil; },{"./doc":12}],11:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isMobile() { var a = navigator.userAgent || navigator.vendor || window.opera; 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) || /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)); } exports.isMobile = isMobile; },{}],12:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function doc(info) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } }; } exports.doc = doc; },{}],13:[function(require,module,exports){ "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var environment_1 = require("./environment"); var globals_1 = require("./globals"); var ops = require("./ops/ops"); var profiler_1 = require("./profiler"); var tape_1 = require("./tape"); var tensor_1 = require("./tensor"); var util = require("./util"); var Engine = (function () { function Engine(backend, safeMode) { this.backend = backend; this.safeMode = safeMode; this.registeredVariables = {}; this.refCounter = new WeakMap(); this.nextTapeNodeId = 0; this.numBytes = 0; this.numTensors = 0; this.numDataBuffers = 0; this.gradientScopeCount = 0; this.customGradientDepth = 0; this.activeScope = { keep: [], track: [] }; this.scopeStack = [this.activeScope]; this.profiler = new profiler_1.Profiler(backend); } Engine.prototype.runKernel = function (forwardFunc, inputs, backwardsFunc) { var _this = this; var result; var saved = []; var saveFunc = function (x) { saved.push(x); return x; }; var scopeName = this.activeScope.name; this.customGradientDepth++; if (!environment_1.ENV.get('DEBUG')) { result = forwardFunc(this.backend, saveFunc); } else { result = this.profiler.profileKernel(scopeName, function () { return forwardFunc(_this.backend, saveFunc); }); } this.customGradientDepth--; if (this.shouldRecord()) { var tapeNode = { id: this.nextTapeNodeId++, name: scopeName, inputs: inputs, output: result, }; if (backwardsFunc != null) { tapeNode.gradient = function (dy) { return backwardsFunc(dy, saved); }; } this.activeTape.push(tapeNode); } return result; }; Engine.prototype.registerTensor = function (a) { var refCount = this.refCounter.has(a.dataId) ? this.refCounter.get(a.dataId) : 0; this.numTensors++; if (refCount === 0) { this.numDataBuffers++; this.numBytes += util.sizeFromShape(a.shape) * util.bytesPerElement(a.dtype); this.backend.register(a.dataId, a.shape, a.dtype); } this.refCounter.set(a.dataId, refCount + 1); if (!(a instanceof tensor_1.Variable)) { this.track(a); } }; Engine.prototype.registerVariable = function (v) { if (this.registeredVariables[v.name] != null) { throw new Error("Variable with name " + v.name + " was already registered"); } this.registeredVariables[v.name] = v; }; Engine.prototype.disposeTensor = function (a) { if (!this.refCounter.has(a.dataId)) { return; } this.numTensors--; var refCount = this.refCounter.get(a.dataId); if (refCount <= 1) { this.refCounter.delete(a.dataId); this.backend.disposeData(a.dataId); this.numDataBuffers--; this.numBytes -= util.sizeFromShape(a.shape) * util.bytesPerElement(a.dtype); } else { this.refCounter.set(a.dataId, refCount - 1); } }; Engine.prototype.memory = function () { var info = this.backend.memory(); info.numTensors = this.numTensors; info.numDataBuffers = this.numDataBuffers; info.numBytes = this.numBytes; return info; }; Engine.prototype.shouldRecord = function () { return this.activeTape != null && this.customGradientDepth === 0; }; Engine.prototype.addTapeNode = function (inputs, result, gradientsFunc) { var inputsMap = {}; inputs.forEach(function (input, idx) { inputsMap[idx] = input; }); var gradient = function (dy) { var res = gradientsFunc(dy); var resMap = {}; res.forEach(function (r, idx) { resMap[idx] = function () { return r; }; }); return resMap; }; var tapeNode = { id: this.nextTapeNodeId++, name: this.activeScope.name, inputs: inputsMap, output: result, gradient: gradient }; this.activeTape.push(tapeNode); }; Engine.prototype.keep = function (result) { if (this.scopeStack.length === 1 && environment_1.ENV.engine.safeMode) { throw new Error('Safe mode is ON. Enclose all tensor operations inside tf.tidy(): ' + 'tf.tidy(() => {...}) to avoid memory leaks.'); } this.activeScope.keep.push(result); return result; }; Engine.prototype.startScope = function (name, gradientsMode) { if (gradientsMode === void 0) { gradientsMode = false; } if (gradientsMode && this.gradientScopeCount === 0) { this.activeTape = []; } if (gradientsMode) { this.gradientScopeCount++; } var scopeInfo = { keep: [], track: [] }; if (name) { scopeInfo.name = name; } this.scopeStack.push(scopeInfo); this.activeScope = scopeInfo; }; Engine.prototype.endScope = function (result, gradientsMode) { var _this = this; if (gradientsMode === void 0) { gradientsMode = false; } if (gradientsMode) { this.gradientScopeCount--; if (this.gradientScopeCount === 0) { this.activeTape = null; } } var tensorsToKeep = this.activeScope.keep; var tensorsToTrackInParent = util.extractTensorsFromContainer(result); tensorsToKeep = tensorsToKeep.concat(tensorsToTrackInParent); for (var i = 0; i < this.activeScope.track.length; i++) { var tensor = this.activeScope.track[i]; if (util.isTensorInList(tensor, tensorsToKeep)) { continue; } if (this.activeTape != null) { tensorsToTrackInParent.push(tensor); } else { tensor.dispose(); } } this.scopeStack.pop(); this.activeScope = this.scopeStack.length === 0 ? { keep: [], track: [] } : this.scopeStack[this.scopeStack.length - 1]; tensorsToTrackInParent.forEach(function (tensor) { if (!util.isTensorInList(tensor, _this.activeScope.keep)) { _this.track(tensor); } }); }; Engine.prototype.dispose = function () { }; Engine.prototype.gradients = function (f, xs, dy, allowNoGradients) { var _this = this; if (allowNoGradients === void 0) { allowNoGradients = false; } util.assert(xs.length > 0, 'gradients() received an empty list of xs.'); return globals_1.tidy('gradients', function () { var y = f(); util.assert(y instanceof tensor_1.Tensor, 'The result y returned by f() must be a tensor.'); var filteredTape = tape_1.getFilteredNodesXToY(_this.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.'); } var accumulatedGradientMap = {}; accumulatedGradientMap[y.id] = (dy == null) ? ops.ones(y.shape) : dy; tape_1.backpropagateGradients(accumulatedGradientMap, filteredTape); var grads = xs.map(function (x) { return accumulatedGradientMap[x.id]; }); return { value: y, grads: grads }; }, true); }; Engine.prototype.customGrad = function (f) { var _this = this; util.assert(util.isFunction(f), 'The f passed in customGrad(f) must be a function.'); return function () { var inputs = []; for (var _i = 0; _i < arguments.length; _i++) { inputs[_i] = arguments[_i]; } util.assert(inputs.every(function (t) { return t instanceof tensor_1.Tensor; }), 'The args passed in customGrad(f)(x1, x2,...) must all be tensors'); _this.customGradientDepth++; var gradientsFunc; var gradientsMode = true; var result = globals_1.tidy(f.name, function () { var _a = f.apply(void 0, inputs), value = _a.value, gradFunc = _a.gradFunc; util.assert(value instanceof tensor_1.Tensor, 'The function f passed in customGrad(f) must return an object ' + 'where `obj.value` is a tensor'); util.assert(util.isFunction(gradFunc), 'The function f passed in customGrad(f) must return an object ' + 'where `obj.gradFunc` is a function.'); gradientsFunc = gradFunc; return value; }, gradientsMode); _this.customGradientDepth--; if (_this.shouldRecord()) { var gradFunc = function (dy) { var res = gradientsFunc(dy); var grads = Array.isArray(res) ? res : [res]; 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(function (t) { return t instanceof tensor_1.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.'); return grads; }; _this.addTapeNode(inputs, result, gradFunc); } return result; }; }; Engine.prototype.write = function (dataId, values) { this.backend.write(dataId, values); }; Engine.prototype.readSync = function (dataId) { return this.backend.readSync(dataId); }; Engine.prototype.read = function (dataId) { return this.backend.read(dataId); }; Engine.prototype.fromPixels = function (pixels, numChannels) { return this.backend.fromPixels(pixels, numChannels); }; Engine.prototype.time = function (query) { return __awaiter(this, void 0, void 0, function () { var start, timingInfo; return __generator(this, function (_a) { switch (_a.label) { case 0: start = performance.now(); return [4, this.backend.time(query)]; case 1: timingInfo = _a.sent(); timingInfo.wallMs = performance.now() - start; return [2, timingInfo]; } }); }); }; Engine.prototype.track = function (result) { if (this.scopeStack.length === 1 && this.safeMode) { throw new Error('Safe mode is ON. Enclose all tensor operations inside tf.tidy(): ' + 'tf.tidy(() => {op();...}); to avoid memory leaks.'); } this.activeScope.track.push(result); return result; }; return Engine; }()); exports.Engine = Engine; },{"./environment":14,"./globals":15,"./ops/ops":79,"./profiler":100,"./tape":101,"./tensor":102,"./util":108}],14:[function(require,module,exports){ (function (global){ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var device_util = require("./device_util"); var doc_1 = require("./doc"); var engine_1 = require("./engine"); var util = require("./util"); var Type; (function (Type) { Type[Type["NUMBER"] = 0] = "NUMBER"; Type[Type["BOOLEAN"] = 1] = "BOOLEAN"; Type[Type["STRING"] = 2] = "STRING"; })(Type = exports.Type || (exports.Type = {})); exports.URL_PROPERTIES = [ { name: 'DEBUG', type: Type.BOOLEAN }, { name: 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION', type: Type.NUMBER }, { name: 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE', type: Type.BOOLEAN }, { name: 'WEBGL_VERSION', type: Type.NUMBER }, { name: 'WEBGL_FLOAT_TEXTURE_ENABLED', type: Type.BOOLEAN }, { name: 'WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED', type: Type.BOOLEAN }, { name: 'BACKEND', type: Type.STRING } ]; function hasExtension(gl, extensionName) { var ext = gl.getExtension(extensionName); return ext != null; } function getWebGLRenderingContext(webGLVersion) { if (webGLVersion === 0) { throw new Error('Cannot get WebGL rendering context, WebGL is disabled.'); } var tempCanvas = document.createElement('canvas'); if (webGLVersion === 1) { return (tempCanvas.getContext('webgl') || tempCanvas.getContext('experimental-webgl')); } return tempCanvas.getContext('webgl2'); } function loseContext(gl) { if (gl != null) { var loseContextExtension = gl.getExtension('WEBGL_lose_context'); if (loseContextExtension == null) { throw new Error('Extension WEBGL_lose_context not supported on this browser.'); } loseContextExtension.loseContext(); } } function isWebGLVersionEnabled(webGLVersion) { var gl = getWebGLRenderingContext(webGLVersion); if (gl != null) { loseContext(gl); return true; } return false; } function getWebGLDisjointQueryTimerVersion(webGLVersion) { if (webGLVersion === 0) { return 0; } var queryTimerVersion; var gl = getWebGLRenderingContext(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; } if (gl != null) { loseContext(gl); } return queryTimerVersion; } function isFloatTextureReadPixelsEnabled(webGLVersion) { if (webGLVersion === 0) { return false; } var gl = getWebGLRenderingContext(webGLVersion); if (webGLVersion === 1) { if (!hasExtension(gl, 'OES_texture_float')) { return false; } } else { if (!hasExtension(gl, 'EXT_color_buffer_float')) { return false; } } var frameBuffer = gl.createFramebuffer(); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); var internalFormat = webGLVersion === 2 ? gl.RGBA32F : gl.RGBA; gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null); gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);