bry-biometric-collector
Version:
BRy web-collector component for biometric capture.
49,178 lines • 1.88 MB
JavaScript
import { bo as eo } from "./main_379f7152_3.0.0.js";
import { r as x1, l as b1, L as y1 } from "./___vite-browser-external_commonjs-proxy_be4e9a04_3.0.0.js";
import "./face_api_0e3ce8c8_3.0.0.js";
var pu = { exports: {} };
pu.exports;
(function(n) {
(function(t, e, s) {
function o(l) {
var c = this, u = a();
c.next = function() {
var h = 2091639 * c.s0 + c.c * 23283064365386963e-26;
return c.s0 = c.s1, c.s1 = c.s2, c.s2 = h - (c.c = h | 0);
}, c.c = 1, c.s0 = u(" "), c.s1 = u(" "), c.s2 = u(" "), c.s0 -= u(l), c.s0 < 0 && (c.s0 += 1), c.s1 -= u(l), c.s1 < 0 && (c.s1 += 1), c.s2 -= u(l), c.s2 < 0 && (c.s2 += 1), u = null;
}
function r(l, c) {
return c.c = l.c, c.s0 = l.s0, c.s1 = l.s1, c.s2 = l.s2, c;
}
function i(l, c) {
var u = new o(l), h = c && c.state, d = u.next;
return d.int32 = function() {
return u.next() * 4294967296 | 0;
}, d.double = function() {
return d() + (d() * 2097152 | 0) * 11102230246251565e-32;
}, d.quick = d, h && (typeof h == "object" && r(h, u), d.state = function() {
return r(u, {});
}), d;
}
function a() {
var l = 4022871197, c = function(u) {
u = String(u);
for (var h = 0; h < u.length; h++) {
l += u.charCodeAt(h);
var d = 0.02519603282416938 * l;
l = d >>> 0, d -= l, d *= l, l = d >>> 0, d -= l, l += d * 4294967296;
}
return (l >>> 0) * 23283064365386963e-26;
};
return c;
}
e && e.exports ? e.exports = i : s && s.amd ? s(function() {
return i;
}) : this.alea = i;
})(
eo,
n,
// present in node.js
!1
// present with an AMD loader
);
})(pu);
var w1 = pu.exports, fu = { exports: {} };
fu.exports;
(function(n) {
(function(t, e, s) {
function o(a) {
var l = this, c = "";
l.x = 0, l.y = 0, l.z = 0, l.w = 0, l.next = function() {
var h = l.x ^ l.x << 11;
return l.x = l.y, l.y = l.z, l.z = l.w, l.w ^= l.w >>> 19 ^ h ^ h >>> 8;
}, a === (a | 0) ? l.x = a : c += a;
for (var u = 0; u < c.length + 64; u++)
l.x ^= c.charCodeAt(u) | 0, l.next();
}
function r(a, l) {
return l.x = a.x, l.y = a.y, l.z = a.z, l.w = a.w, l;
}
function i(a, l) {
var c = new o(a), u = l && l.state, h = function() {
return (c.next() >>> 0) / 4294967296;
};
return h.double = function() {
do
var d = c.next() >>> 11, p = (c.next() >>> 0) / 4294967296, f = (d + p) / (1 << 21);
while (f === 0);
return f;
}, h.int32 = c.next, h.quick = h, u && (typeof u == "object" && r(u, c), h.state = function() {
return r(c, {});
}), h;
}
e && e.exports ? e.exports = i : s && s.amd ? s(function() {
return i;
}) : this.xor128 = i;
})(
eo,
n,
// present in node.js
!1
// present with an AMD loader
);
})(fu);
var C1 = fu.exports, mu = { exports: {} };
mu.exports;
(function(n) {
(function(t, e, s) {
function o(a) {
var l = this, c = "";
l.next = function() {
var h = l.x ^ l.x >>> 2;
return l.x = l.y, l.y = l.z, l.z = l.w, l.w = l.v, (l.d = l.d + 362437 | 0) + (l.v = l.v ^ l.v << 4 ^ (h ^ h << 1)) | 0;
}, l.x = 0, l.y = 0, l.z = 0, l.w = 0, l.v = 0, a === (a | 0) ? l.x = a : c += a;
for (var u = 0; u < c.length + 64; u++)
l.x ^= c.charCodeAt(u) | 0, u == c.length && (l.d = l.x << 10 ^ l.x >>> 4), l.next();
}
function r(a, l) {
return l.x = a.x, l.y = a.y, l.z = a.z, l.w = a.w, l.v = a.v, l.d = a.d, l;
}
function i(a, l) {
var c = new o(a), u = l && l.state, h = function() {
return (c.next() >>> 0) / 4294967296;
};
return h.double = function() {
do
var d = c.next() >>> 11, p = (c.next() >>> 0) / 4294967296, f = (d + p) / (1 << 21);
while (f === 0);
return f;
}, h.int32 = c.next, h.quick = h, u && (typeof u == "object" && r(u, c), h.state = function() {
return r(c, {});
}), h;
}
e && e.exports ? e.exports = i : s && s.amd ? s(function() {
return i;
}) : this.xorwow = i;
})(
eo,
n,
// present in node.js
!1
// present with an AMD loader
);
})(mu);
var $1 = mu.exports, gu = { exports: {} };
gu.exports;
(function(n) {
(function(t, e, s) {
function o(a) {
var l = this;
l.next = function() {
var u = l.x, h = l.i, d, p;
return d = u[h], d ^= d >>> 7, p = d ^ d << 24, d = u[h + 1 & 7], p ^= d ^ d >>> 10, d = u[h + 3 & 7], p ^= d ^ d >>> 3, d = u[h + 4 & 7], p ^= d ^ d << 7, d = u[h + 7 & 7], d = d ^ d << 13, p ^= d ^ d << 9, u[h] = p, l.i = h + 1 & 7, p;
};
function c(u, h) {
var d, p = [];
if (h === (h | 0))
p[0] = h;
else
for (h = "" + h, d = 0; d < h.length; ++d)
p[d & 7] = p[d & 7] << 15 ^ h.charCodeAt(d) + p[d + 1 & 7] << 13;
for (; p.length < 8; )
p.push(0);
for (d = 0; d < 8 && p[d] === 0; ++d)
;
for (d == 8 ? p[7] = -1 : p[d], u.x = p, u.i = 0, d = 256; d > 0; --d)
u.next();
}
c(l, a);
}
function r(a, l) {
return l.x = a.x.slice(), l.i = a.i, l;
}
function i(a, l) {
a == null && (a = +/* @__PURE__ */ new Date());
var c = new o(a), u = l && l.state, h = function() {
return (c.next() >>> 0) / 4294967296;
};
return h.double = function() {
do
var d = c.next() >>> 11, p = (c.next() >>> 0) / 4294967296, f = (d + p) / (1 << 21);
while (f === 0);
return f;
}, h.int32 = c.next, h.quick = h, u && (u.x && r(u, c), h.state = function() {
return r(c, {});
}), h;
}
e && e.exports ? e.exports = i : s && s.amd ? s(function() {
return i;
}) : this.xorshift7 = i;
})(
eo,
n,
// present in node.js
!1
// present with an AMD loader
);
})(gu);
var I1 = gu.exports, xu = { exports: {} };
xu.exports;
(function(n) {
(function(t, e, s) {
function o(a) {
var l = this;
l.next = function() {
var u = l.w, h = l.X, d = l.i, p, f;
return l.w = u = u + 1640531527 | 0, f = h[d + 34 & 127], p = h[d = d + 1 & 127], f ^= f << 13, p ^= p << 17, f ^= f >>> 15, p ^= p >>> 12, f = h[d] = f ^ p, l.i = d, f + (u ^ u >>> 16) | 0;
};
function c(u, h) {
var d, p, f, m, g, x = [], b = 128;
for (h === (h | 0) ? (p = h, h = null) : (h = h + "\0", p = 0, b = Math.max(b, h.length)), f = 0, m = -32; m < b; ++m)
h && (p ^= h.charCodeAt((m + 32) % h.length)), m === 0 && (g = p), p ^= p << 10, p ^= p >>> 15, p ^= p << 4, p ^= p >>> 13, m >= 0 && (g = g + 1640531527 | 0, d = x[m & 127] ^= p + g, f = d == 0 ? f + 1 : 0);
for (f >= 128 && (x[(h && h.length || 0) & 127] = -1), f = 127, m = 4 * 128; m > 0; --m)
p = x[f + 34 & 127], d = x[f = f + 1 & 127], p ^= p << 13, d ^= d << 17, p ^= p >>> 15, d ^= d >>> 12, x[f] = p ^ d;
u.w = g, u.X = x, u.i = f;
}
c(l, a);
}
function r(a, l) {
return l.i = a.i, l.w = a.w, l.X = a.X.slice(), l;
}
function i(a, l) {
a == null && (a = +/* @__PURE__ */ new Date());
var c = new o(a), u = l && l.state, h = function() {
return (c.next() >>> 0) / 4294967296;
};
return h.double = function() {
do
var d = c.next() >>> 11, p = (c.next() >>> 0) / 4294967296, f = (d + p) / (1 << 21);
while (f === 0);
return f;
}, h.int32 = c.next, h.quick = h, u && (u.X && r(u, c), h.state = function() {
return r(c, {});
}), h;
}
e && e.exports ? e.exports = i : s && s.amd ? s(function() {
return i;
}) : this.xor4096 = i;
})(
eo,
// window object or global
n,
// present in node.js
!1
// present with an AMD loader
);
})(xu);
var k1 = xu.exports, bu = { exports: {} };
bu.exports;
(function(n) {
(function(t, e, s) {
function o(a) {
var l = this, c = "";
l.next = function() {
var h = l.b, d = l.c, p = l.d, f = l.a;
return h = h << 25 ^ h >>> 7 ^ d, d = d - p | 0, p = p << 24 ^ p >>> 8 ^ f, f = f - h | 0, l.b = h = h << 20 ^ h >>> 12 ^ d, l.c = d = d - p | 0, l.d = p << 16 ^ d >>> 16 ^ f, l.a = f - h | 0;
}, l.a = 0, l.b = 0, l.c = -1640531527, l.d = 1367130551, a === Math.floor(a) ? (l.a = a / 4294967296 | 0, l.b = a | 0) : c += a;
for (var u = 0; u < c.length + 20; u++)
l.b ^= c.charCodeAt(u) | 0, l.next();
}
function r(a, l) {
return l.a = a.a, l.b = a.b, l.c = a.c, l.d = a.d, l;
}
function i(a, l) {
var c = new o(a), u = l && l.state, h = function() {
return (c.next() >>> 0) / 4294967296;
};
return h.double = function() {
do
var d = c.next() >>> 11, p = (c.next() >>> 0) / 4294967296, f = (d + p) / (1 << 21);
while (f === 0);
return f;
}, h.int32 = c.next, h.quick = h, u && (typeof u == "object" && r(u, c), h.state = function() {
return r(c, {});
}), h;
}
e && e.exports ? e.exports = i : s && s.amd ? s(function() {
return i;
}) : this.tychei = i;
})(
eo,
n,
// present in node.js
!1
// present with an AMD loader
);
})(bu);
var v1 = bu.exports, Ff = { exports: {} };
(function(n) {
(function(t, e, s) {
var o = 256, r = 6, i = 52, a = "random", l = s.pow(o, r), c = s.pow(2, i), u = c * 2, h = o - 1, d;
function p(y, C, $) {
var k = [];
C = C == !0 ? { entropy: !0 } : C || {};
var v = x(g(
C.entropy ? [y, w(e)] : y ?? b(),
3
), k), S = new f(k), T = function() {
for (var F = S.g(r), L = l, M = 0; F < c; )
F = (F + M) * o, L *= o, M = S.g(1);
for (; F >= u; )
F /= 2, L /= 2, M >>>= 1;
return (F + M) / L;
};
return T.int32 = function() {
return S.g(4) | 0;
}, T.quick = function() {
return S.g(4) / 4294967296;
}, T.double = T, x(w(S.S), e), (C.pass || $ || function(F, L, M, B) {
return B && (B.S && m(B, S), F.state = function() {
return m(S, {});
}), M ? (s[a] = F, L) : F;
})(
T,
v,
"global" in C ? C.global : this == s,
C.state
);
}
function f(y) {
var C, $ = y.length, k = this, v = 0, S = k.i = k.j = 0, T = k.S = [];
for ($ || (y = [$++]); v < o; )
T[v] = v++;
for (v = 0; v < o; v++)
T[v] = T[S = h & S + y[v % $] + (C = T[v])], T[S] = C;
(k.g = function(F) {
for (var L, M = 0, B = k.i, z = k.j, V = k.S; F--; )
L = V[B = h & B + 1], M = M * o + V[h & (V[B] = V[z = h & z + L]) + (V[z] = L)];
return k.i = B, k.j = z, M;
})(o);
}
function m(y, C) {
return C.i = y.i, C.j = y.j, C.S = y.S.slice(), C;
}
function g(y, C) {
var $ = [], k = typeof y, v;
if (C && k == "object")
for (v in y)
try {
$.push(g(y[v], C - 1));
} catch {
}
return $.length ? $ : k == "string" ? y : y + "\0";
}
function x(y, C) {
for (var $ = y + "", k, v = 0; v < $.length; )
C[h & v] = h & (k ^= C[h & v] * 19) + $.charCodeAt(v++);
return w(C);
}
function b() {
try {
var y;
return d && (y = d.randomBytes) ? y = y(o) : (y = new Uint8Array(o), (t.crypto || t.msCrypto).getRandomValues(y)), w(y);
} catch {
var C = t.navigator, $ = C && C.plugins;
return [+/* @__PURE__ */ new Date(), t, $, t.screen, w(e)];
}
}
function w(y) {
return String.fromCharCode.apply(0, y);
}
if (x(s.random(), e), n.exports) {
n.exports = p;
try {
d = x1;
} catch {
}
} else
s["seed" + a] = p;
})(
// global: `self` in browsers (including strict mode and web workers),
// otherwise `this` in Node and other environments
typeof self < "u" ? self : eo,
[],
// pool: entropy pool starts empty
Math
// math: package containing random, pow, and seedrandom
);
})(Ff);
var S1 = Ff.exports, N1 = w1, T1 = C1, E1 = $1, R1 = I1, D1 = k1, A1 = v1, no = S1;
no.alea = N1;
no.xor128 = T1;
no.xorwow = E1;
no.xorshift7 = R1;
no.xor4096 = D1;
no.tychei = A1;
var yu = no;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const F1 = 1e-7, O1 = 1e-4;
class Of {
constructor(t, e) {
this.backend = t, this.dataMover = e, this.data = /* @__PURE__ */ new WeakMap(), this.dataIdsCount = 0;
}
get(t) {
return this.data.has(t) || this.dataMover.moveData(this.backend, t), this.data.get(t);
}
set(t, e) {
this.dataIdsCount++, this.data.set(t, e);
}
has(t) {
return this.data.has(t);
}
delete(t) {
return this.dataIdsCount--, this.data.delete(t);
}
numDataIds() {
return this.dataIdsCount;
}
}
class wu {
refCount(t) {
return Be("refCount");
}
incRef(t) {
return Be("incRef");
}
timerAvailable() {
return !0;
}
time(t) {
return Be("time");
}
read(t) {
return Be("read");
}
readSync(t) {
return Be("readSync");
}
readToGPU(t, e) {
return Be("readToGPU");
}
numDataIds() {
return Be("numDataIds");
}
disposeData(t, e) {
return Be("disposeData");
}
write(t, e, s) {
return Be("write");
}
move(t, e, s, o, r) {
return Be("move");
}
createTensorFromGPUData(t, e, s) {
return Be("createTensorFromGPUData");
}
memory() {
return Be("memory");
}
/** Returns the highest precision for floats in bits (e.g. 16 or 32) */
floatPrecision() {
return Be("floatPrecision");
}
/** Returns the smallest representable number. */
epsilon() {
return this.floatPrecision() === 32 ? F1 : O1;
}
dispose() {
return Be("dispose");
}
}
function Be(n) {
throw new Error(`'${n}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _1(n) {
let t = n.length, e = 0;
for (; t > 0; )
e = Math.random() * t | 0, t--, xo(n, t, e);
}
function Vs(n, t, e) {
return Math.max(n, Math.min(t, e));
}
function Cu(n) {
return n % 2 === 0 ? n : n + 1;
}
function xo(n, t, e) {
const s = n[t];
n[t] = n[e], n[e] = s;
}
function L1(n) {
let t = 0;
for (let e = 0; e < n.length; e++)
t += n[e];
return t;
}
function I(n, t) {
if (!n)
throw new Error(typeof t == "string" ? t : t());
}
function $u(n, t, e = "") {
I(Et(n, t), () => e + ` Shapes ${n} and ${t} must match`);
}
function _f(n) {
I(n != null, () => "The input to the tensor constructor must be a non-null value.");
}
function G(n) {
if (n.length === 0)
return 1;
let t = n[0];
for (let e = 1; e < n.length; e++)
t *= n[e];
return t;
}
function Et(n, t) {
if (n === t)
return !0;
if (n == null || t == null || n.length !== t.length)
return !1;
for (let e = 0; e < n.length; e++)
if (n[e] !== t[e])
return !1;
return !0;
}
function vo(n) {
return n % 1 === 0;
}
function Ec(n) {
const t = Math.ceil(Math.sqrt(n));
return [t, Math.ceil(n / t)];
}
function wo(n, t) {
return t <= n.length ? n : n + " ".repeat(t - n.length);
}
function ep(n, t = (o) => 0, e, s) {
return new Promise((o, r) => {
let i = 0;
const a = () => {
if (n()) {
o();
return;
}
i++;
const l = t(i);
if (e != null && i >= e) {
r();
return;
}
s != null ? s(a, l) : setTimeout(a, l);
};
a();
});
}
function Lf(n, t) {
let e = 1, s = -1;
for (let r = 0; r < n.length; ++r)
if (n[r] >= 0)
e *= n[r];
else if (n[r] === -1) {
if (s !== -1)
throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${r}`);
s = r;
} else if (n[r] < 0)
throw Error(`Shapes can not be < 0. Found ${n[r]} at dim ${r}`);
if (s === -1) {
if (t > 0 && t !== e)
throw Error(`Size(${t}) must match the product of shape ${n}`);
return n;
}
if (e === 0)
throw Error(`Cannot infer the missing size in [${n}] when there are 0 elements`);
if (t % e !== 0)
throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${e}`);
const o = n.slice();
return o[s] = t / e, o;
}
function wt(n, t) {
const e = t.length;
return n = n == null ? t.map((s, o) => o) : [].concat(n), I(n.every((s) => s >= -e && s < e), () => `All values in axis param must be in range [-${e}, ${e}) but got axis ${n}`), I(n.every((s) => vo(s)), () => `All values in axis param must be integers but got axis ${n}`), n.map((s) => s < 0 ? e + s : s);
}
function ys(n, t) {
const e = [], s = [], o = t != null && Array.isArray(t) && t.length === 0, r = t == null || o ? null : wt(t, n).sort();
let i = 0;
for (let a = 0; a < n.length; ++a) {
if (r != null) {
if (r[i] === a && n[a] !== 1)
throw new Error(`Can't squeeze axis ${a} since its dim '${n[a]}' is not 1`);
(r[i] == null || r[i] > a) && n[a] === 1 && (e.push(n[a]), s.push(a)), r[i] <= a && i++;
}
n[a] !== 1 && (e.push(n[a]), s.push(a));
}
return { newShape: e, keptDims: s };
}
function we(n, t) {
return qt(n, t);
}
function qt(n, t) {
let e = null;
if (n == null || n === "float32")
e = new Float32Array(t);
else if (n === "int32")
e = new Int32Array(t);
else if (n === "bool")
e = new Uint8Array(t);
else if (n === "string")
e = new Array(t);
else
throw new Error(`Unknown data type ${n}`);
return e;
}
function M1(n, t) {
for (let e = 0; e < n.length; e++) {
const s = n[e];
if (isNaN(s) || !isFinite(s))
throw Error(`A tensor of type ${t} being uploaded contains ${s}.`);
}
}
function P1(n) {
return n === "bool" || n === "complex64" || n === "float32" || n === "int32" || n === "string";
}
function Mf(n, t) {
return !(t === "complex64" || t === "float32" && n !== "complex64" || t === "int32" && n !== "float32" && n !== "complex64" || t === "bool" && n === "bool");
}
function ra(n) {
if (n === "float32" || n === "int32")
return 4;
if (n === "complex64")
return 8;
if (n === "bool")
return 1;
throw new Error(`Unknown dtype ${n}`);
}
function z1(n) {
if (n == null)
return 0;
let t = 0;
return n.forEach((e) => t += e.length), t;
}
function vr(n) {
return typeof n == "string" || n instanceof String;
}
function B1(n) {
return typeof n == "boolean";
}
function Rc(n) {
return typeof n == "number";
}
function Lo(n) {
return Array.isArray(n) ? Lo(n[0]) : n instanceof Float32Array ? "float32" : n instanceof Int32Array || n instanceof Uint8Array || n instanceof Uint8ClampedArray ? "int32" : Rc(n) ? "float32" : vr(n) ? "string" : B1(n) ? "bool" : "float32";
}
function Dc(n) {
return !!(n && n.constructor && n.call && n.apply);
}
function Ac(n, t) {
for (let e = t; e < n; ++e)
if (n % e === 0)
return e;
return n;
}
function lt(n) {
const t = n.length;
if (t < 2)
return [];
const e = new Array(t - 1);
e[t - 2] = n[t - 1];
for (let s = t - 3; s >= 0; --s)
e[s] = e[s + 1] * n[s + 1];
return e;
}
function Pf(n, t, e, s = !1) {
const o = new Array();
if (t.length === 1) {
const r = t[0] * (s ? 2 : 1);
for (let i = 0; i < r; i++)
o[i] = e[n + i];
} else {
const r = t[0], i = t.slice(1), a = i.reduce((l, c) => l * c) * (s ? 2 : 1);
for (let l = 0; l < r; l++)
o[l] = Pf(n + l * a, i, e, s);
}
return o;
}
function xn(n, t, e = !1) {
if (n.length === 0)
return t[0];
const s = n.reduce((o, r) => o * r) * (e ? 2 : 1);
if (s === 0)
return [];
if (s !== t.length)
throw new Error(`[${n}] does not match the input size ${t.length}${e ? " for a complex tensor" : ""}.`);
return Pf(0, n, t, e);
}
function V1(n, t) {
if (Array.isArray(n))
return n;
if (t === "float32")
return n instanceof Float32Array ? n : new Float32Array(n);
if (t === "int32")
return n instanceof Int32Array ? n : new Int32Array(n);
if (t === "bool" || t === "string")
return Uint8Array.from(new Int32Array(n));
throw new Error(`Unknown dtype ${t}`);
}
function Iu(n, t) {
const e = Ce(n, t);
for (let s = 0; s < e.length; s++)
e[s] = 1;
return e;
}
function Ce(n, t) {
if (t == null || t === "float32" || t === "complex64")
return new Float32Array(n);
if (t === "int32")
return new Int32Array(n);
if (t === "bool")
return new Uint8Array(n);
throw new Error(`Unknown data type ${t}`);
}
function zf(n, t) {
const e = n.reduce((s, o) => s * o, 1);
if (t == null || t === "float32")
return xn(n, new Float32Array(e));
if (t === "int32")
return xn(n, new Int32Array(e));
if (t === "bool")
return xn(n, new Uint8Array(e));
throw new Error(`Unknown data type ${t}`);
}
function Jn(n) {
n.forEach((t) => {
I(Number.isInteger(t) && t >= 0, () => `Tensor must have a shape comprised of positive integers but got shape [${n}].`);
});
}
function Rn(n, t, e) {
if (t === 0)
return 0;
if (t === 1)
return n[0];
let s = n[n.length - 1];
for (let o = 0; o < n.length - 1; ++o)
s += e[o] * n[o];
return s;
}
function Mo(n, t, e) {
if (t === 0)
return [];
if (t === 1)
return [n];
const s = new Array(t);
for (let o = 0; o < s.length - 1; ++o)
s[o] = Math.floor(n / e[o]), n -= s[o] * e[o];
return s[s.length - 1] = n, s;
}
function ku(n) {
return n && n.then && typeof n.then == "function";
}
/**
* @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.
* =============================================================================
*/
const np = "tfjsflags";
class W1 {
// tslint:disable-next-line: no-any
constructor(t) {
this.global = t, this.flags = {}, this.flagRegistry = {}, this.urlFlags = {}, this.getQueryParams = U1, this.populateURLFlags();
}
setPlatform(t, e) {
this.platform != null && (P().getBool("IS_TEST") || P().getBool("PROD") || console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`)), this.platformName = t, this.platform = e;
}
registerFlag(t, e, s) {
if (this.flagRegistry[t] = { evaluationFn: e, setHook: s }, this.urlFlags[t] != null) {
const o = this.urlFlags[t];
P().getBool("IS_TEST") || P().getBool("PROD") || console.warn(`Setting feature override from URL ${t}: ${o}.`), this.set(t, o);
}
}
async getAsync(t) {
return t in this.flags ? this.flags[t] : (this.flags[t] = await this.evaluateFlag(t), this.flags[t]);
}
get(t) {
if (t in this.flags)
return this.flags[t];
const e = this.evaluateFlag(t);
if (ku(e))
throw new Error(`Flag ${t} cannot be synchronously evaluated. Please use getAsync() instead.`);
return this.flags[t] = e, this.flags[t];
}
getNumber(t) {
return this.get(t);
}
getBool(t) {
return this.get(t);
}
getString(t) {
return this.get(t);
}
getFlags() {
return this.flags;
}
// For backwards compatibility.
get features() {
return this.flags;
}
set(t, e) {
if (this.flagRegistry[t] == null)
throw new Error(`Cannot set flag ${t} as it has not been registered.`);
this.flags[t] = e, this.flagRegistry[t].setHook != null && this.flagRegistry[t].setHook(e);
}
evaluateFlag(t) {
if (this.flagRegistry[t] == null)
throw new Error(`Cannot evaluate flag '${t}': no evaluation function found.`);
return this.flagRegistry[t].evaluationFn();
}
setFlags(t) {
this.flags = Object.assign({}, t);
}
reset() {
this.flags = {}, this.urlFlags = {}, this.populateURLFlags();
}
populateURLFlags() {
if (typeof this.global > "u" || typeof this.global.location > "u" || typeof this.global.location.search > "u")
return;
const t = this.getQueryParams(this.global.location.search);
np in t && t[np].split(",").forEach((s) => {
const [o, r] = s.split(":");
this.urlFlags[o] = H1(o, r);
});
}
}
function U1(n) {
const t = {};
return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (e, ...s) => (G1(t, s[0], s[1]), s.join("="))), t;
}
function G1(n, t, e) {
n[decodeURIComponent(t)] = decodeURIComponent(e || "");
}
function H1(n, t) {
const e = t.toLowerCase();
return e === "true" || e === "false" ? e === "true" : `${+e}` === e ? +e : t;
}
function P() {
return Bf;
}
let Bf = null;
function K1(n) {
Bf = n;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
let hc;
function Vf() {
if (hc == null) {
let n;
if (typeof window < "u")
n = window;
else if (typeof global < "u")
n = global;
else if (typeof process < "u")
n = process;
else if (typeof self < "u")
n = self;
else
throw new Error("Could not find a global object");
hc = n;
}
return hc;
}
function j1() {
const n = Vf();
return n._tfGlobals == null && (n._tfGlobals = /* @__PURE__ */ new Map()), n._tfGlobals;
}
function vu(n, t) {
const e = j1();
if (e.has(n))
return e.get(n);
{
const s = t();
return e.set(n, s), e.get(n);
}
}
const Fa = "Abs", Sr = "Acos", Nr = "Acosh", Po = "Add", Su = "AddN", Nu = "All", Tu = "Any", Oa = "ArgMax", _a = "ArgMin", Tr = "Asin", Er = "Asinh", Rr = "Atan", Dr = "Atanh", Ar = "Atan2", La = "AvgPool", Eu = "AvgPoolGrad", Ma = "AvgPool3D", Ru = "AvgPool3DGrad", Pa = "BatchMatMul", za = "BatchToSpaceND", Du = "Bincount", Au = "BitwiseAnd", X1 = "BroadcastTo", Wf = "BroadcastArgs", Fr = "Cast", Or = "Ceil", _r = "ClipByValue", Fu = "Complex", Ba = "ComplexAbs", Va = "Concat", Wa = "Conv2D", Ou = "Conv2DBackpropFilter", Ua = "Conv2DBackpropInput", Ga = "Conv3D", _u = "Conv3DBackpropFilterV2", Lu = "Conv3DBackpropInputV2", Lr = "Cos", Mr = "Cosh", Mu = "Cumprod", Ha = "Cumsum", Pu = "CropAndResize", zu = "DenseBincount", Bu = "DepthToSpace", Ka = "DepthwiseConv2dNative", Vu = "DepthwiseConv2dNativeBackpropFilter", Wu = "DepthwiseConv2dNativeBackpropInput", Uf = "Diag", ja = "Dilation2D", Fc = "Dilation2DBackpropInput", Oc = "Dilation2DBackpropFilter", q1 = "Draw", Pr = "RealDiv", Uu = "Einsum", zr = "Elu", Gu = "EluGrad", Br = "Erf", Xa = "Equal", Vr = "Exp", qa = "ExpandDims", Wr = "Expm1", Hu = "FFT", Ku = "Fill", ju = "FlipLeftRight", Ur = "Floor", Gr = "FloorDiv", Ya = "FusedBatchNorm", Ja = "GatherV2", Gf = "GatherNd", Za = "Greater", Hr = "GreaterEqual", Kr = "Identity", Xu = "IFFT", qu = "Imag", jr = "IsFinite", Xr = "IsInf", qr = "IsNan", Qa = "LeakyRelu", tl = "Less", el = "LessEqual", Hf = "LinSpace", Yr = "Log", Jr = "Log1p", nl = "LogicalAnd", sl = "LogicalNot", ol = "LogicalOr", Y1 = "LogSoftmax", rl = "LRN", Yu = "LRNGrad", il = "Max", Zr = "Maximum", al = "MaxPool", Ju = "MaxPoolGrad", ll = "MaxPool3D", Zu = "MaxPool3DGrad", Kf = "MaxPoolWithArgmax", cl = "Mean", ul = "Min", Qr = "Minimum", hl = "MirrorPad", ti = "Mod", jf = "Multinomial", ei = "Multiply", dl = "Neg", pl = "NotEqual", Qu = "NonMaxSuppressionV3", th = "NonMaxSuppressionV4", eh = "NonMaxSuppressionV5", fl = "OnesLike", ml = "OneHot", gl = "Pack", xl = "PadV2", ni = "Pow", bl = "Prelu", yl = "Prod", Xf = "RaggedGather", qf = "RaggedRange", Yf = "RaggedTensorToTensor", nh = "Range", sh = "Real", si = "Reciprocal", oi = "Relu", wl = "Reshape", Cl = "ResizeNearestNeighbor", oh = "ResizeNearestNeighborGrad", $l = "ResizeBilinear", rh = "ResizeBilinearGrad", ri = "Relu6", Il = "Reverse", ii = "Round", ai = "Rsqrt", Jf = "ScatterNd", Zf = "TensorScatterUpdate", Qf = "SearchSorted", kl = "Select", li = "Selu", vl = "Slice", ci = "Sin", ui = "Sinh", hi = "Sign", di = "Sigmoid", pi = "Softplus", fi = "Sqrt", Sl = "Sum", Nl = "SpaceToBatchND", Tl = "SplitV", El = "Softmax", tm = "SparseFillEmptyRows", em = "SparseReshape", nm = "SparseSegmentMean", sm = "SparseSegmentSum", om = "SparseToDense", mi = "SquaredDifference", ih = "Square", ah = "StaticRegexReplace", lh = "StridedSlice", rm = "StringNGrams", im = "StringSplit", am = "StringToHashBucketFast", gi = "Sub", xi = "Tan", bi = "Tanh", yi = "Tile", ch = "TopK", uh = "Transform", Co = "Transpose", hh = "Unique", Rl = "Unpack", Dl = "UnsortedSegmentSum", Al = "ZerosLike", wi = "Step", J1 = "FromPixels", dh = "RotateWithOffset", ia = "_FusedMatMul", aa = "FusedConv2D", lm = "FusedDepthwiseConv2D";
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function je(...n) {
P().getBool("IS_TEST") || P().getBool("PROD") || console.warn(...n);
}
function Z1(...n) {
P().getBool("IS_TEST") || P().getBool("PROD") || console.log(...n);
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const la = vu("kernelRegistry", () => /* @__PURE__ */ new Map()), _c = vu("gradRegistry", () => /* @__PURE__ */ new Map());
function sp(n, t) {
const e = um(n, t);
return la.get(e);
}
function op(n) {
return _c.get(n);
}
function rp(n) {
const t = la.entries(), e = [];
for (; ; ) {
const { done: s, value: o } = t.next();
if (s)
break;
const [r, i] = o, [a] = r.split("_");
a === n && e.push(i);
}
return e;
}
function cm(n) {
const { kernelName: t, backendName: e } = n, s = um(t, e);
la.has(s) && je(`The kernel '${t}' for backend '${e}' is already registered`), la.set(s, n);
}
function Q1(n) {
const { kernelName: t } = n;
_c.has(t) && P().getBool("DEBUG") && je(`Overriding the gradient for '${t}'`), _c.set(t, n);
}
function um(n, t) {
return `${t}_${n}`;
}
/**
* @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.
* =============================================================================
*/
function hm(n) {
return n instanceof Float32Array || n instanceof Int32Array || n instanceof Uint8Array || n instanceof Uint8ClampedArray;
}
/**
* @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.
* =============================================================================
*/
const Fs = (
// tslint:disable-next-line
b1 || y1
);
function Fl(n) {
return Fs.fromString(n, !0, 16);
}
const dm = Fl("c3a5c85c97cb3127"), As = Fl("b492b66fbe98f273"), Te = Fl("9ae16a3b2f90404f");
function Lc(n) {
return n.xor(n.shru(47));
}
function pm(n, t, e) {
const s = n.slice(t, t + e);
return Fs.fromBytes(Array.from(s), !0, !0);
}
function Pt(n, t) {
return pm(n, t, 8);
}
function ip(n, t) {
return pm(n, t, 4);
}
function ue(n, t) {
return t === 0 ? n : n.shru(t).or(n.shl(64 - t));
}
function cs(n, t, e = Fl("9ddfea08eb382d69")) {
let s = n.xor(t).mul(e);
s = s.xor(s.shru(47));
let o = t.xor(s).mul(e);
return o = o.xor(o.shru(47)), o = o.mul(e), o;
}
function tw(n, t, e, s, o, r) {
o = o.add(n), r = ue(r.add(o).add(s), 21);
const i = o;
return o = o.add(t), o = o.add(e), r = r.add(ue(o, 44)), [o.add(s), r.add(i)];
}
function Gi(n, t, e, s) {
return tw(Pt(n, t), Pt(n, t + 8), Pt(n, t + 16), Pt(n, t + 24), e, s);
}
function ew(n, t = n.length) {
if (t >= 8) {
const e = Te.add(t * 2), s = Pt(n, 0).add(Te), o = Pt(n, t - 8), r = ue(o, 37).mul(e).add(s), i = ue(s, 25).add(o).mul(e);
return cs(r, i, e);
}
if (t >= 4) {
const e = Te.add(t * 2), s = ip(n, 0);
return cs(s.shl(3).add(t), ip(n, t - 4), e);
}
if (t > 0) {
const e = n[0], s = n[t >> 1], o = n[t - 1], r = e + (s << 8), i = t + (o << 2);
return Lc(Te.mul(r).xor(dm.mul(i))).mul(Te);
}
return Te;
}
function nw(n, t = n.length) {
const e = Te.add(t * 2), s = Pt(n, 0).mul(As), o = Pt(n, 8), r = Pt(n, t - 8).mul(e), i = Pt(n, t - 16).mul(Te);
return cs(ue(s.add(o), 43).add(ue(r, 30)).add(i), s.add(ue(o.add(Te), 18)).add(r), e);
}
function sw(n, t = n.length) {
const e = Te.add(t * 2), s = Pt(n, 0).mul(Te), o = Pt(n, 8), r = Pt(n, t - 8).mul(e), i = Pt(n, t - 16).mul(Te), a = ue(s.add(o), 43).add(ue(r, 30)).add(i), l = cs(a, s.add(ue(o.add(Te), 18)).add(r), e), c = Pt(n, 16).mul(e), u = Pt(n, 24), h = a.add(Pt(n, t - 32)).mul(e), d = l.add(Pt(n, t - 24)).mul(e);
return cs(ue(c.add(u), 43).add(ue(h, 30)).add(d), c.add(ue(u.add(s), 18)).add(h), e);
}
function ow(n, t = n.length) {
const e = Fs.fromNumber(81, !0);
if (t <= 32)
return t <= 16 ? ew(n, t) : nw(n, t);
if (t <= 64)
return sw(n, t);
let s = e, o = e.mul(As).add(113), r = Lc(o.mul(Te).add(113)).mul(Te), i = [Fs.UZERO, Fs.UZERO], a = [Fs.UZERO, Fs.UZERO];
s = s.mul(Te).add(Pt(n, 0));
let l = 0;
const c = (t - 1 >> 6) * 64, u = c + (t - 1 & 63) - 63;
do
s = ue(s.add(o).add(i[0]).add(Pt(n, l + 8)), 37).mul(As), o = ue(o.add(i[1]).add(Pt(n, l + 48)), 42).mul(As), s = s.xor(a[1]), o = o.add(i[0]).add(Pt(n, l + 40)), r = ue(r.add(a[0]), 33).mul(As), i = Gi(n, l, i[1].mul(As), s.add(a[0])), a = Gi(n, l + 32, r.add(a[1]), o.add(Pt(n, l + 16))), [r, s] = [s, r], l += 64;
while (l !== c);
const h = As.add(r.and(255).shl(1));
return l = u, a[0] = a[0].add(t - 1 & 63), i[0] = i[0].add(a[0]), a[0] = a[0].add(i[0]), s = ue(s.add(o).add(i[0]).add(Pt(n, l + 8)), 37).mul(h), o = ue(o.add(i[1]).add(Pt(n, l + 48)), 42).mul(h), s = s.xor(a[1].mul(9)), o = o.add(i[0].mul(9).add(Pt(n, l + 40))), r = ue(r.add(a[0]), 33).mul(h), i = Gi(n, l, i[1].mul(h), s.add(a[0])), a = Gi(n, l + 32, r.add(a[1]), o.add(Pt(n, l + 16))), [r, s] = [s, r], cs(cs(i[0], a[0], h).add(Lc(o).mul(dm)).add(r), cs(i[1], a[1], h).add(s), h);
}
/**
* @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.
* =============================================================================
*/
function ws(n, t) {
return t === "string" ? us(n) : so([n], t);
}
function rw(n, t) {
return n instanceof Float32Array && t === "float32" || n instanceof Int32Array && t === "int32" || n instanceof Uint8Array && t === "bool";
}
function so(n, t) {
if (t === "string")
throw new Error("Cannot convert a string[] to a TypedArray");
if (Array.isArray(n) && (n = Ws(n)), P().getBool("DEBUG") && M1(n, t), rw(n, t))
return n;
if (t == null || t === "float32" || t === "complex64")
return new Float32Array(n);
if (t === "int32")
return new Int32Array(n);
if (t === "bool") {
const e = new Uint8Array(n.length);
for (let s = 0; s < e.length; ++s)
Math.round(n[s]) !== 0 && (e[s] = 1);
return e;
} else
throw new Error(`Unknown data type ${t}`);
}
function Fe() {
return P().platform.now();
}
function us(n, t = "utf-8") {
return t = t || "utf-8", P().platform.encode(n, t);
}
function ps(n, t = "utf-8") {
return t = t || "utf-8", P().platform.decode(n, t);
}
function rn(n) {
return P().platform.isTypedArray != null ? P().platform.isTypedArray(n) : hm(n);
}
function Ws(n, t = [], e = !1) {
if (t == null && (t = []), typeof n == "boolean" || typeof n == "number" || typeof n == "string" || ku(n) || n == null || rn(n) && e)
t.push(n);
else if (Array.isArray(n) || rn(n))
for (let s = 0; s < n.length; ++s)
Ws(n[s], t, e);
else {
let s = -1;
for (const o of Object.keys(n))
/^([1-9]+[0-9]*|0)$/.test(o) && (s = Math.max(s, Number(o)));
for (let o = 0; o <= s; o++)
Ws(n[o], t, e);
}
return t;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class iw {
constructor(t, e) {
this.backendTimer = t, this.logger = e, e == null && (this.logger = new lw());
}
profileKernel(t, e, s) {
let o;
const r = () => {
o = s();
};
let i;
const a = Fe();
if (this.backendTimer.timerAvailable())
i = this.backendTimer.time(r);
else {
r();
for (const c of o)
c.dataSync();
i = Promise.resolve({ kernelMs: Fe() - a });
}
if (P().getBool("CHECK_COMPUTATION_FOR_ERRORS"))
for (let c = 0; c < o.length; c++) {
const u = o[c];
u.data().then((h) => {
aw(h, u.dtype, t);
});
}
return {
kernelName: t,
outputs: o,
inputs: e,
timeMs: i.then((c) => c.kernelMs),
extraInfo: i.then((c) => c.getExtraProfileInfo != null ? c.getExtraProfileInfo() : "")
};
}
logKernelProfile(t) {
const { kernelName: e, outputs: s, timeMs: o, inputs: r, extraInfo: i } = t;
s.forEach((a) => {
Promise.all([a.data(), o, i]).then((l) => {
this.logger.logKernelProfile(e, a, l[0], l[1], r, l[2]);
});
});
}
}
function aw(n, t, e) {
if (t !== "float32")
return !1;
for (let s = 0; s < n.length; s++) {
const o = n[s];
if (isNaN(o) || !isFinite(o))
return console.warn(`Found ${o} in the result of '${e}'`), !0;
}
return !1;
}
class lw {
logKernelProfile(t, e, s, o, r, i) {
const a = typeof o == "number" ? wo(`${o}ms`, 9) : o.error, l = wo(t, 25), c = e.rank, u = e.size, h = wo(e.shape.toString(), 14);
let d = "";
for (const p in r) {
const f = r[p];
if (f != null) {
const m = f.shape || e.shape, g = m.length;
d += `${p}: ${g}D ${g > 0 ? m : ""} `;
}
}
console.log(`%c${l} %c${a} %c${c}D ${h} %c${u} %c${d} %c${i}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue");
}
}
/**
* @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.
* =============================================================================
*/
function cw(n, t, e) {
const s = {}, o = {};
for (let l = 0; l < t.length; l++)
s[t[l].id] = !0;
for (let l = 0; l < n.length; l++) {
const c = n[l], u = c.inputs;
for (const h in u) {
const d = u[h];
let p = !1;
for (let f = 0; f < t.length; f++)
if (s[d.id]) {
c.outputs.forEach((m) => s[m.id] = !0), p = !0, o[c.id] = !0;
break;
}
if (p)
break;
}
}
const r = {};
r[e.id] = !0;
const i = {};
for (let l = n.length - 1; l >= 0; l--) {
const c = n[l], u = c.inputs;
for (let h = 0; h < c.outputs.length; h++)
if (r[c.outputs[h].id]) {
for (const d in u)
r[u[d].id] = !0, i[c.id] = !0;
break;
}
}
const a = [];
for (let l = 0; l < n.length; l++) {
const c = n[l];
if (o[c.id] && i[c.id]) {
const u = {};
for (const d in c.inputs) {
const p = c.inputs[d];
s[p.id] && (u[d] = p);
}
const h = Object.assign({}, c);
h.inputs = u, h.outputs = c.outputs, a.push(h);
}
}
return a;
}
function uw(n, t, e, s) {
for (let o = t.length - 1; o >= 0; o--) {
const r = t[o], i = [];
if (r.outputs.forEach((l) => {
const c = n[l.id];
c != null ? i.push(c) : i.push(null);
}), r.gradient == null)
throw new Error(`Cannot compute gradient: gradient function not found for ${r.kernelName}.`);
const a = r.gradient(i);
for (const l in r.inputs) {
if (!(l in a))
throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(a)}.`);
const c = e(() => a[l]());
if (c.dtype !== "float32")
throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);
const u = r.inputs[l];
if (!Et(c.shape, u.shape))
throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);
if (n[u.id] == null)
n[u.id] = c;
else {
const h = n[u.id];
n[u.id] = s(h, c), h.dispose();
}
}
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ap = 20, tr = 3, dc = 7;
function hw(n, t, e, s) {
const o = lt(t), r = dw(n, t, e, o), i = t.length, a = sa(n, t, e, o, r), l = ["Tensor"];
return s && (l.push(` dtype: ${e}`), l.push(` rank: ${i}`), l.push(` shape: [${t}]`), l.push(" values:")), l.push(a.map((c) => " " + c).join(`
`)), l.join(`
`);
}
function dw(n, t, e, s) {
const o = G(t), r = s[s.length - 1], i = new Array(r).fill(0), a = t.length, l = e === "complex64" ? rr(n) : n;
if (a > 1)
for (let c = 0; c < o / r; c++) {
const u = c * r;
for (let h = 0; h < r; h++)
i[h] = Math.max(i[h], or(l[u + h], 0, e).length);
}
return i;
}
function or(n, t, e) {
let s;
return Array.isArray(n) ? s = `${parseFloat(n[0].toFixed(dc))} + ${parseFloat(n[1].toFixed(dc))}j` : vr(n) ? s = `'${n}'` : e === "bool" ? s = fm(n) : s = parseFloat(n.toFixed(dc)).toString(), wo(s, t);
}
function fm(n) {
return n === 0 ? "false" : "true";
}
function sa(n, t, e, s, o, r = !0) {
const i = e === "complex64" ? 2 : 1, a = t[0], l = t.length;
if (l === 0) {
if (e === "complex64") {
const m = rr(n);
return [or(m[0], 0, e)];
}
return e === "bool" ? [fm(n[0])] : [n[0].toString()];
}
if (l === 1) {
if (a > ap) {
const g = tr * i;
let x = Array.from(n.slice(0, g)), b = Array.from(n.slice((a - tr) * i, a * i));
return e === "complex64" && (x = rr(x), b = rr(b)), [
"[" + x.map((w, y) => or(w, o[y], e)).join(", ") + ", ..., " + b.map((w, y) => or(w, o[a - tr + y], e)).join(", ") + "]"
];
}
return [
"[" + (e === "complex64" ? rr(n) : Array.from(n)).map((g, x) => or(g, o[x], e)).join(", ") + "]"
];
}
const c = t.slice(1), u = s.slice(1), h = s[0] * i, d = [];
if (a > ap) {
for (let m = 0; m < tr; m++) {
const g = m * h, x = g + h;
d.push(...sa(
n.slice(g, x),
c,
e,
u,
o,
!1
/* isLast */
));
}
d.push("...");
for (let m = a - tr; m < a; m++) {
const g = m * h, x = g + h;
d.push(...sa(
n.slice(g, x),
c,
e,
u,
o,
m === a - 1
/* isLast */
));
}
} else
for (let m = 0; m < a; m++) {
const g = m * h, x = g + h;
d.push(...sa(
n.slice(g, x),
c,
e,
u,
o,
m === a - 1
/* isLast */
));
}
const p = l === 2 ? "," : "";
d[0] = "[" + (a > 0 ? d[0] + p : "");
for (let m = 1; m < d.length - 1; m++)
d[m] = " " + d[m] + p;
let f = `,
`;
for (let m = 2; m < l; m++)
f += `
`;
return d[d.length - 1] = " " + d[d.length - 1] + "]" + (r ? "" : f), d;
}
function rr(n) {
const t = [];
for (let e = 0; e < n.length; e += 2)
t.push([n[e], n[e + 1]]);
return t;
}
/**
* @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.
* =============================================================================
*/
class ge {
constructor(t, e, s) {
if (this.dtype = e, this.shape = t.slice(), this.size = G(t), s != null) {
const o = s.length;
I(o === this.size, () => `Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`);
}
if (e === "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 = s || qt(e, this.size), this.strides = lt(t);
}
/**
* 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(t, ...e) {
e.length === 0 && (e = [0]), I(e.length === this.rank, () => `The number of provided coordinates (${e.length}) must match the rank (${this.rank})`);
const s = this.locToIndex(e);
this.values[s] = t;
}
/**
* Returns the value in the buffer at the provided location.
*
* @param locs The location indices.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
get(...t) {
t.length === 0 && (t = [0]);
let e = 0;
for (const o of t) {
if (o < 0 || o >= this.shape[e]) {
const r = `Requested out of range element at ${t}. Buffer shape=${this.shape}`;
throw new Error(r);
}
e++;
}
let s = t[t.length - 1];
for (let o = 0; o < t.length - 1; ++o)
s += this.strides[o] * t[o];
return this.values[s];
}
locToIndex(t) {
if (this.rank === 0)
return 0;
if (this.rank === 1)
return t[0];
let e = t[t.length - 1];
for (let s = 0; s < t.length - 1; ++s)
e += this.strides[s] * t[s];
return e;
}
indexToLoc(t) {
if (this.rank === 0)
return [];
if (this.rank === 1)
return [t];
const e = new Array(this.shape.length);
for (let s = 0; s < e.length - 1; ++s)
e[s] = Math.floor(t / this.strides[s]), t -= e[s] * this.strides[s];
return e[e.length - 1] = t, e;
}
get rank() {
return this.shape.length;
}
/**
* Creates an immutable `tf.Tensor` object from the buffer.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
toTensor() {
return fn().makeTensor(this.values, this.shape, this.dtype);
}
}
let fn = null, bo = null;
function pw(n) {
fn = n;
}
function fw(n) {
bo = n;
}
class se {
constructor(t, e, s, o) {
this.kept = !1, this.isDisposedInternal = !1, this.shape = t.slice(), this.dtype = e || "float32", this.size = G(t), this.strides = lt(t), this.dataId = s, this.id = o, 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 t = await this.data();
return bo.buffer(this.shape, this.dtype, t);
}
/**
* Returns a `tf.TensorBuffer` that holds the underlying data.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
bufferSync() {
return bo.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 t = await this.data();
return xn(this.shape, t, 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 xn(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 t = fn().read(this.dataId);
if (this.dtype === "string") {
const e = await t;
try {
return e.map((s) => ps(s));
} catch {
throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
}
}
return t;
}
/**
* 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(t) {
return this.throwIfDisposed(), fn().readToGPU(this.dataId, t);
}
/**
* 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 t = fn().readSync(this.dataId);
if (this.dtype === "string")
try {
return t.map((e) => ps(e));
} catch {
throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
}
return t;
}
/** Returns the underlying bytes of the tensor's data. */
async bytes() {
this.throwIfDisposed();
const t = await fn().read(this.dataId);
return this.dtype === "string" ? t : new Uint8Array(t.buffer);
}
/**
* Disposes `tf.Tensor` from memory.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
dispose() {
this.isDisposed || (this.kerasMask && this.kerasMask.dispose(), fn().disposeTensor(this), this.isDisposedInternal = !0);
}
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(t = !1) {
return bo.print(this, t);
}
/**
* Returns a copy of the tensor. See `tf.clone` for details.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
clone() {
return this.throwIfDisposed(), bo.clone(this);
}
/**
* Returns a human-readable description of the tensor. Useful for logging.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
toString(t = !1) {
const e = this.dataSync();
return hw(e, this.shape, this.dtype, t);
}
cast(t) {
return this.throwIfDisposed(), bo.cast(this, t);
}
variable(t = !0, e, s) {
return this.throwIfDisposed(), fn().makeVariable(this, t, e, s);
}
}
Object.defineProperty(se, Symbol.hasInstance, {
value: (n) => !!n && n.data != null && n.dataSync != null && n.throwIfDisposed != null
});
function W() {
return vu("Tensor", () => se);
}
W();
class ca extends se {
constructor(t, e, s, o) {
super(t.shape, t.dtype, t.dataId, o), this.trainable = e, this.name = s;
}
/**
* 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(t) {
if (t.dtype !== this.dtype)
throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);
if (!Et(t.shape, this.shape))
throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);
fn().disposeTensor(this), this.dataId = t.dataId, fn().incRef(
this,
null
/* backend */
);
}
dispose() {
fn().disposeVariable(this), this.isDisposedInternal = !0;
}
}
Object.defineProperty(ca, Symbol.hasInstance, {
value: (n) => n instanceof se && n.assign != null && n.assign instanceof Function
});
/**
* @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 lp;
(function(n) {
n.R0 = "R0", n.R1 = "R1", n.R2 = "R2", n.R3 = "R3", n.R4 = "R4", n.R5 = "R5", n.R6 = "R6";
})(lp || (lp = {}));
var Mc;
(function(n) {
n.float32 = "float32", n.int32 = "int32", n.bool = "int32", n.complex64 = "complex64";
})(Mc || (Mc = {}));
var Pc;
(function(n) {
n.float32 = "float32", n.int32 = "int32", n.bool = "bool", n.complex64 = "complex64";
})(Pc || (Pc = {}));
var zc;
(function(n) {
n.float32 = "float32", n.int32 = "float32", n.bool = "float32", n.complex64 = "complex64";
})(zc || (zc = {}));
var Bc;
(function(n) {
n.float32 = "complex64", n.int32 = "complex64", n.bool = "complex64", n.complex64 = "complex64";
})(Bc || (Bc = {}));
const mw = {
float32: zc,
int32: Mc,
bool: Pc,
complex64: Bc
};
function Ue(n, t) {
if (n === "string" || t === "string") {
if (n === "string" && t === "string")
return "string";
throw new Error(`Can not upcast ${n} with ${t}`);
}
return mw[n][t];
}
function ph(n) {
return Ue(n, "int32");
}
function mm(n) {
return n != null && typeof n == "object" && "texture" in n && n.texture instanceof WebGLTexture;
}
function gm(n) {
return typeof GPUBuffer < "u" && n != null && typeof n == "object" && "buffer" in n && n.buffer instanceof GPUBuffer;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Jt(n, t) {
if (n.dtype === t.dtype)
return [n, t];
const e = Ue(n.dtype, t.dtype);
return [n.cast(e), t.cast(e)];
}
function xm(n) {
const t = [];
return bm(n, t, /* @__PURE__ */ new Set()), t;
}
function bm(n, t, e) {
if (n == null)
return;
if (n instanceof se) {
t.push(n);
return;
}
if (!gw(n))
return;
const s = n;
for (const o in s) {
const r = s[o];
e.has(r) || (e.add(r), bm(r, t, e));
}
}
function gw(n) {
return Array.isArray(n) || typeof n == "object";
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function pc(n) {
return n.kernelName != null;
}
class cp {
constructor() {
this.registeredVariables = {}, this.nextTapeNodeId = 0, this.numBytes = 0, this.numTensors = 0, this.numStringTensors = 0, this.numDataBuffers = 0, this.gradientDepth = 0, this.kernelDepth = 0, this.scopeStack = [], this.numDataMovesStack = [], this.nextScopeId = 0, this.tensorInfo = /* @__PURE__ */ new WeakMap(), this.profiling = !1, this.activeProfile = {
newBytes: 0,
newTensors: 0,
peakBytes: 0,
kernels: [],
result: null,
get kernelNames() {
return Array.from(new Set(this.kernels.map((t) => t.name)));
}
};
}
dispose() {
for (const t in this.registeredVariables)
this.registeredVariables[t].dispose();
}
}
class So {
constructor(t) {
this.ENV = t, this.registry = {}, this.registryFactory = {}, this.pendingBackendInitId = 0, this.state = new cp();
}
async ready() {
if (this.pendingBackendInit != null)
return this.pendingBackendInit.then(() => {
});
if (this.backendInstance != null)
return;
const t = this.getSortedBackends();
for (let e = 0; e < t.length; e++) {
const s = t[e];
if (await this.initializeBackend(s).success) {
await this.setBackend(s);
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: t, asyncInit: e } = this.initializeBackendsAndReturnBest();
if (e)
throw new Error(`The highest priority backend '${t}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);
this.setBackend(t);
}
return this.backendInstance;
}
backendNames() {
return Object.keys(this.registryFactory);
}
findBackend(t) {
if (!(t in this.registry))
if (t in this.registryFactory) {
const { asyncInit: e } = this.initializeBackend(t);
if (e)
return null;
} else
return null;
return this.registry[t];
}
findBackendFactory(t) {
return t in this.registryFactory ? this.registryFactory[t].factory : null;
}
registerBackend(t, e, s = 1) {
return t in this.registryFactory ? (je(`${t} backend was already registered. Reusing existing backend factory.`), !1) : (this.registryFactory[t] = { factory: e, priority: s }, !0);
}
async setBackend(t) {
if (this.registryFactory[t] == null)
throw new Error(`Backend name '${t}' not found in registry`);
if (this.backendName = t, this.registry[t] == null) {
this.backendInstance = null;
const { success: e, asyncInit: s } = this.initializeBackend(t);
if (!(s ? await e : e))
return !1;
}
return this.backendInstance = this.registry[t], this.setupRegisteredKernels(), this.profiler = new iw(this.backendInstance), !0;
}
setupRegisteredKernels() {
rp(this.backendName).forEach((e) => {
e.setupFunc != null && e.setupFunc(this.backendInstance);
});
}
disposeRegisteredKernels(t) {
rp(t).forEach((s) => {
s.disposeFunc != null && s.disposeFunc(this.registry[t]);
});
}
/**
* 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 succeeded. Throws an error if
* there is no backend in the factory registry.
*/
initializeBackend(t) {
const e = this.registryFactory[t];
if (e == null)
throw new Error(`Cannot initialize backend ${t}, no registration found.`);
try {
const s = e.factory();
if (s && !(s instanceof wu) && typeof s.then == "function") {
const o = ++this.pendingBackendInitId, r = s.then((i) => o < this.pendingBackendInitId ? !1 : (this.registry[t] = i, this.pendingBackendInit = null, !0)).catch((i) => (o < this.pendingBackendInitId || (this.pendingBackendInit = null, je(`Initialization of backend ${t} failed`), je(i.stack || i.message)), !1));
return this.pendingBackendInit = r, { success: r, asyncInit: !0 };
} else
return this.registry[t] = s, { success: !0, asyncInit: !1 };
} catch (s) {
return je(`Initialization of backend ${t} failed`), je(s.stack || s.message), { success: !1, asyncInit: !1 };
}
}
removeBackend(t) {
if (!(t in this.registryFactory))
throw new Error(`${t} backend not found in registry`);
this.backendName === t && this.pendingBackendInit != null && this.pendingBackendInitId++, t in this.registry && (this.disposeRegisteredKernels(t), this.registry[t].dispose(), delete this.registry[t]), delete this.registryFactory[t], this.backendName === t && (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((t, e) => this.registryFactory[e].priority - this.registryFactory[t].priority);
}
initializeBackendsAndReturnBest() {
const t = this.getSortedBackends();
for (let e = 0; e < t.length; e++) {
const s = t[e], { success: o, asyncInit: r } = this.initializeBackend(s);
if (r || o)
return { name: s, asyncInit: r };
}
throw new Error("Could not initialize any backends, all backend initializations failed.");
}
moveData(t, e) {
const s = this.state.tensorInfo.get(e), o = s.backend, r = this.readSync(e), i = o.refCount(e);
o.disposeData(e, !0), s.backend = t, t.move(e, r, s.shape, s.dtype, i), this.shouldCheckForMemLeaks() && this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
}
tidy(t, e) {
let s = null;
if (e == null) {
if (typeof t != "function")
throw new Error("Please provide a function to tidy()");
e = t;
} else {
if (typeof t != "string" && !(t instanceof String))
throw new Error("When calling with two arguments, the first argument to tidy() must be a string");
if (typeof e != "function")
throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");
s = t;
}
let o;
return this.scopedRun(() => this.startScope(s), () => this.endScope(o), () => (o = e(), o instanceof Promise && console.error("Cannot return a Promise inside of tidy."), o));
}
scopedRun(t, e, s) {
t();
try {
const o = s();
return e(), o;
} catch (o) {
throw e(), o;
}
}
nextTensorId() {
return So.nextTensorId++;
}
nextVariableId() {
return So.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(t) {
const e = D.runKernel(Kr, { x: t }), s = { x: t }, o = (i) => ({
x: () => {
const a = "float32", l = { x: i }, c = { dtype: a };
return D.runKernel(
Fr,
l,
// tslint:disable-next-line: no-unnecessary-type-assertion
c
);
}
}), r = [];
return this.addTapeNode(this.state.activeScope.name, s, [e], o, r, {}), e;
}
/**
* 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(t, e, s) {
if (this.backendName == null && this.backend, !(sp(t, this.backendName) != null))
throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);
return this.runKernelFunc({ kernelName: t, inputs: e, attrs: s });
}
shouldCheckForMemLeaks() {
return this.ENV.getBool("IS_TEST");
}
checkKernelForMemLeak(t, e, s) {
const o = this.backend.numDataIds();
let r = 0;
s.forEach((l) => {
r += l.dtype === "complex64" ? 3 : 1;
});
const i = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1], a = o - e - r - i;
if (a > 0)
throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${t}'`);
}
/**
* Internal helper method to execute a kernel Func
*
* Use `runKernel` to execute kernels from outside of engine.
*/
runKernelFunc(t) {
let e, s = [];
const o = this.isTapeOn(), r = this.state.numBytes, i = this.state.numTensors;
this.shouldCheckForMemLeaks() && this.state.numDataMovesStack.push(0);
let a;
this.backendName == null && this.backend;
let l;
const c = pc(t) ? t.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
if (pc(t)) {
const { kernelName: f, inputs: m, attrs: g } = t;
this.backendName == null && this.backend;
const x = sp(f, this.backendName);
I(x != null, () => `Cannot find registered kernel '${f}' for backend '${this.backendName}'`), a = () => {
const b = this.backend.numDataIds();
l = x.kernelFunc({ inputs: m, attrs: g, backend: this.backend });
const w = Array.isArray(l) ? l : [l];
this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(f, b, w);
const y = w.map((C) => C.rank != null ? C : this.makeTensorFromTensorInfo(C));
if (o) {
const C = this.getTensorsForGradient(f, m, y);
s = this.saveTensorsForBackwardMode(C);
}
return y;
};
} else {
const { forwardFunc: f } = t, m = (g) => {
o && (s = g.map((x) => this.keep(this.clone(x))));
};
a = () => {
const g = this.backend.numDataIds();
l = this.tidy(() => f(this.backend, m));
const x = Array.isArray(l) ? l : [l];
return this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(c, g, x), x;
};
}
const { inputs: u, attrs: h } = t, d = pc(t) ? null : t.backwardsFunc;
let p;
return this.scopedRun(
// Stop recording to a tape when running a kernel.
() => this.state.kernelDepth++,
() => this.state.kernelDepth--,
() => {
!this.ENV.getBool("DEBUG") && !this.state.profiling ? e = a() : (p = this.profiler.profileKernel(c, u, () => a()), this.ENV.getBool("DEBUG") && this.profiler.logKernelProfile(p), e = p.outputs);
}
), o && this.addTapeNode(c, u, e, d, s, h), this.state.profiling && this.state.activeProfile.kernels.push({
name: c,
bytesAdded: this.state.numBytes - r,
totalBytesSnapshot: this.state.numBytes,
tensorsAdded: this.state.numTensors - i,
totalTensorsSnapshot: this.state.numTensors,
inputShapes: Object.keys(u).map((f) => u[f] != null ? u[f].shape : null),
outputShapes: e.map((f) => f.shape),
kernelTimeMs: p.timeMs,
extraInfo: p.extraInfo
}), Array.isArray(l) ? e : e[0];
}
/**
* Saves tensors used in forward mode for use in backward mode.
*
* @param tensors the list of tensors to save.
*/
saveTensorsForBackwardMode(t) {
return t.map((s) => this.keep(this.clone(s)));
}
/**
* 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(t, e, s) {
const o = op(t);
if (o != null) {
const r = o.inputsToSave || [], i = o.outputsToSave || [];
let a;
o.saveAllInputs ? (I(Array.isArray(e), () => "saveAllInputs is true, expected inputs to be an array."), a = Object.keys(e).map((c) => e[c])) : a = r.map((c) => e[c]);
const l = s.filter((c, u) => i[u]);
return a.concat(l);
}
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(t, e, s, o) {
if (t == null)
throw new Error("Values passed to engine.makeTensor() are null");
s = s || "float32", o = o || this.backend;
let r = t;
s === "string" && vr(t[0]) && (r = t.map((l) => us(l)));
const i = o.write(r, e, s), a = new se(e, s, i, this.nextTensorId());
if (this.trackTensor(a, o), s === "string") {
const l = this.state.tensorInfo.get(i), c = z1(r);
this.state.numBytes += c - l.bytes, l.bytes = c;
}
return a;
}
/**
* 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(t, e, s, o) {
s = s || "float32";
const r = { dataId: t, shape: e, dtype: s };
return this.makeTensorFromTensorInfo(r, o);
}
/**
* 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(t, e) {
const { dataId: s, shape: o, dtype: r } = t, i = new se(o, r, s, this.nextTensorId());
return this.trackTensor(i, e), i;
}
makeVariable(t, e = !0, s, o) {
s = s || this.nextVariableId().toString(), o != null && o !== t.dtype && (t = t.cast(o));
const r = new ca(t, e, s, this.nextTensorId());
if (this.state.registeredVariables[r.name] != null)
throw new Error(`Variable with name ${r.name} was already registered`);
return this.state.registeredVariables[r.name] = r, this.incRef(r, this.backend), r;
}
trackTensor(t, e) {
this.state.numTensors++, t.dtype === "string" && this.state.numStringTensors++;
let s = 0;
t.dtype !== "complex64" && t.dtype !== "string" && (s = t.size * ra(t.dtype)), this.state.numBytes += s, this.state.tensorInfo.has(t.dataId) || (this.state.numDataBuffers++, this.state.tensorInfo.set(t.dataId, {
backend: e || this.backend,
dtype: t.dtype,
shape: t.shape,
bytes: s
})), t instanceof ca || this.track(t);
}
// 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(t, e) {
this.trackTensor(t, e), this.backend.incRef(t.dataId);
}
removeDataId(t, e) {
this.state.tensorInfo.has(t) && this.state.tensorInfo.get(t).backend === e && (this.state.tensorInfo.delete(t), this.state.numDataBuffers--);
}
disposeTensor(t) {
if (!this.state.tensorInfo.has(t.dataId))
return;
const e = this.state.tensorInfo.get(t.dataId);
if (this.state.numTensors--, t.dtype === "string" && (this.state.numStringTensors--, this.state.numBytes -= e.bytes), t.dtype !== "complex64" && t.dtype !== "string") {
const s = t.size * ra(t.dtype);
this.state.numBytes -= s;
}
e.backend.disposeData(t.dataId) && this.removeDataId(t.dataId, e.backend);
}
disposeVariables() {
for (const t in this.state.registeredVariables) {
const e = this.state.registeredVariables[t];
this.disposeVariable(e);
}
}
disposeVariable(t) {
this.disposeTensor(t), this.state.registeredVariables[t.name] != null && delete this.state.registeredVariables[t.name];
}
memory() {
const t = this.backend.memory();
return t.numTensors = this.state.numTensors, t.numDataBuffers = this.state.numDataBuffers, t.numBytes = this.state.numBytes, this.state.numStringTensors > 0 && (t.unreliable = !0, t.reasons == null && (t.reasons = []), t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")), t;
}
async profile(t) {
this.state.profiling = !0;
const e = this.state.numBytes, s = this.state.numTensors;
this.state.activeProfile.kernels = [], this.state.activeProfile.result = await t(), this.state.profiling = !1, this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map((o) => o.totalBytesSnapshot)), this.state.activeProfile.newBytes = this.state.numBytes - e, this.state.activeProfile.newTensors = this.state.numTensors - s;
for (const o of this.state.activeProfile.kernels)
o.kernelTimeMs = await o.kernelTimeMs, o.extraInfo = await o.extraInfo;
return this.state.activeProfile;
}
isTapeOn() {
return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
}
addTapeNode(t, e, s, o, r, i) {
const a = { id: this.state.nextTapeNodeId++, kernelName: t, inputs: e, outputs: s, saved: r }, l = op(t);
l != null && (o = l.gradFunc), o != null && (a.gradient = (c) => (c = c.map((u, h) => {
if (u == null) {
const d = s[h], p = Ce(d.size, d.dtype);
return this.makeTensor(p, d.shape, d.dtype);
}
return u;
}), o(c.length > 1 ? c : c[0], r, i))), this.state.activeTape.push(a);
}
keep(t) {
return t.kept = !0, t;
}
startTape() {
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(t) {
const e = {
track: [],
name: "unnamed scope",
id: this.state.nextScopeId++
};
t && (e.name = t), this.state.scopeStack.push(e), this.state.activeScope = e;
}
/**
* End a scope. Use this with startScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
endScope(t) {
const e = xm(t), s = new Set(e.map((r) => r.id));
for (let r = 0; r < this.state.activeScope.track.length; r++) {
const i = this.state.activeScope.track[r];
!i.kept && !s.has(i.id) && i.dispose();
}
const o = this.state.scopeStack.pop();
this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1], e.forEach((r) => {
!r.kept && r.scopeId === o.id && this.track(r);
});
}
/**
* 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(t, e, s, o = !1) {
if (I(e.length > 0, () => "gradients() received an empty list of xs."), s != null && s.dtype !== "float32")
throw new Error(`dy must have 'float32' dtype, but has '${s.dtype}'`);
const r = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy("forward", t));
I(r instanceof se, () => "The result y returned by f() must be a tensor.");
const i = cw(this.state.activeTape, e, r);
if (!o && i.length === 0 && e.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 a = {};
a[r.id] = s ?? xw(r.shape), uw(
a,
i,
// Pass the tidy function to avoid circular dep with `tape.ts`.
(c) => this.tidy(c),
// Pass an add function to avoide a circular dep with `tape.ts`.
bw
);
const l = e.map((c) => a[c.id]);
return this.state.gradientDepth === 0 && (this.state.activeTape.forEach((c) => {
for (const u of c.saved)
u.dispose();
}), this.state.activeTape = null), { value: r, grads: l };
});
}
customGrad(t) {
return I(Dc(t), () => "The f passed in customGrad(f) must be a function."), (...e) => {
I(e.every((a) => a instanceof se), () => "The args passed in customGrad(f)(x1, x2,...) must all be tensors");
let s;
const o = {};
e.forEach((a, l) => {
o[l] = a;
});
const r = (a, l) => (s = t(...e, l), I(s.value instanceof se, () => "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"), I(Dc(s.gradFunc), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."), s.value), i = (a, l) => {
const c = s.gradFunc(a, l), u = Array.isArray(c) ? c : [c];
I(u.length === e.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(...)."), I(u.every((d) => d instanceof se), () => "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 h = {};
return u.forEach((d, p) => {
h[p] = () => d;
}), h;
};
return this.runKernelFunc({
forwardFunc: r,
backwardsFunc: i,
inputs: o
});
};
}
readSync(t) {
return this.state.tensorInfo.get(t).backend.readSync(t);
}
read(t) {
return this.state.tensorInfo.get(t).backend.read(t);
}
readToGPU(t, e) {
return this.state.tensorInfo.get(t).backend.readToGPU(t, e);
}
async time(t) {
const e = Fe(), s = await this.backend.time(t);
return s.wallMs = Fe() - e, s;
}
/**
* 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(t) {
return this.state.activeScope != null && (t.scopeId = this.state.activeScope.id, this.state.activeScope.track.push(t)), t;
}
get registeredVariables() {
return this.state.registeredVariables;
}
/**
* Resets the engine state. Removes all backends but does not remove
* registered backend factories.
*/
reset() {
this.pendingBackendInitId++, this.state.dispose(), this.ENV.reset(), this.state = new cp();
for (const t in this.registry)
this.disposeRegisteredKernels(t), this.registry[t].dispose(), delete this.registry[t];
this.backendName = null, this.backendInstance = null, this.pendingBackendInit = null;
}
}
So.nextTensorId = 0;
So.nextVariableId = 0;
function xw(n) {
const t = Iu(G(n), "float32");
return D.makeTensor(t, n, "float32");
}
function ym() {
const n = Vf();
if (n._tfengine == null) {
const t = new W1(n);
n._tfengine = new So(t);
}
return K1(n._tfengine.ENV), pw(() => n._tfengine), n._tfengine;
}
const D = ym();
function bw(n, t) {
const e = { a: n, b: t };
return D.runKernel(Po, e);
}
/**
* @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.
* =============================================================================
*/
function yw() {
return typeof navigator < "u" && navigator != null;
}
function wm(n) {
if (n || yw()) {
if (n || (n = navigator), n.product === "ReactNative")
return !0;
const t = n.userAgent || n.vendor || // tslint:disable-next-line:no-any
(typeof window < "u" ? window.opera : "");
if (!t) {
const e = n;
return e.userAgentData && e.userAgentData.mobile;
}
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(t) || // 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(t.substr(0, 4));
}
return !1;
}
function Cm() {
return typeof window < "u" && window.document != null || //@ts-ignore
typeof WorkerGlobalScope < "u";
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Me = P();
Me.registerFlag("DEBUG", () => !1, (n) => {
n && 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.");
});
Me.registerFlag("IS_BROWSER", () => Cm());
Me.registerFlag("IS_NODE", () => typeof process < "u" && typeof process.versions < "u" && typeof process.versions.node < "u");
Me.registerFlag("IS_CHROME", () => typeof navigator < "u" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor));
Me.registerFlag("IS_SAFARI", () => typeof navigator < "u" && navigator != null && navigator.userAgent != null && /Safari/.test(navigator.userAgent) && /Apple/.test(navigator.vendor));
Me.registerFlag("PROD", () => !1);
Me.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => Me.getBool("DEBUG"));
Me.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => !0);
Me.registerFlag("IS_TEST", () => !1);
Me.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => Me.getBool("DEBUG"));
Me.registerFlag("WRAP_TO_IMAGEBITMAP", () => !1);
Me.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU", () => !1);
Me.registerFlag("USE_SETTIMEOUTCUSTOM", () => !1);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ol(n, t) {
let e = n;
if (rn(n))
return t === "string" ? [] : [n.length];
if (mm(n)) {
const o = n.channels || "RGBA";
return [n.height, n.width * o.length];
} else if (gm(n))
return [n.buffer.size / (t == null ? 4 : ra(t))];
if (!Array.isArray(n))
return [];
const s = [];
for (; Array.isArray(e) || rn(e) && t !== "string"; )
s.push(e.length), e = e[0];
return Array.isArray(n) && P().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY") && $m(n, s, []), s;
}
function $m(n, t, e) {
if (e = e || [], !Array.isArray(n) && !rn(n)) {
I(t.length === 0, () => `Element arr[${e.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);
return;
}
I(t.length > 0, () => `Element arr[${e.join("][")}] should be a primitive, but is an array of ${n.length} elements`), I(n.length === t[0], () => `Element arr[${e.join("][")}] should have ${t[0]} elements, but has ${n.length} elements`);
const s = t.slice(1);
for (let o = 0; o < n.length; ++o)
$m(n[o], s, e.concat(o));
}
function up(n, t, e, s) {
if (n !== "string_or_numeric") {
if (n == null)
throw new Error("Expected dtype cannot be null.");
if (n !== "numeric" && n !== t || n === "numeric" && t === "string")
throw new Error(`Argument '${e}' passed to '${s}' must be ${n} tensor, but got ${t} tensor`);
}
}
function N(n, t, e, s = "numeric") {
if (n instanceof W())
return up(s, n.dtype, t, e), n;
let o = Lo(n);
if (o !== "string" && ["bool", "int32", "float32"].indexOf(s) >= 0 && (o = s), up(s, o, t, e), n == null || !rn(n) && !Array.isArray(n) && typeof n != "number" && typeof n != "boolean" && typeof n != "string") {
const l = n == null ? "null" : n.constructor.name;
throw new Error(`Argument '${t}' passed to '${e}' must be a Tensor or TensorLike, but got '${l}'`);
}
const r = Ol(n, o);
!rn(n) && !Array.isArray(n) && (n = [n]);
const a = o !== "string" ? so(n, o) : Ws(n, [], !0);
return D.makeTensor(a, r, o);
}
function Im(n, t, e, s = "numeric") {
if (!Array.isArray(n))
throw new Error(`Argument ${t} passed to ${e} must be a \`Tensor[]\` or \`TensorLike[]\``);
return n.map((r, i) => N(r, `${t}[${i}]`, e, s));
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ww = "__op";
function O(n) {
const t = Object.keys(n);
if (t.length !== 1)
throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);
let e = t[0];
const s = n[e];
e.endsWith("_") && (e = e.substring(0, e.length - 1)), e = e + ww;
const o = (...r) => {
D.startScope(e);
try {
const i = s(...r);
return ku(i) && console.error("Cannot return a Promise inside of tidy."), D.endScope(i), i;
} catch (i) {
throw D.endScope(null), i;
}
};
return Object.defineProperty(o, "name", { value: e, configurable: !0 }), o;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Cw(n, t) {
const e = N(n, "real", "complex"), s = N(t, "imag", "complex");
$u(e.shape, s.shape, `real and imag shapes, ${e.shape} and ${s.shape}, must match in call to tf.complex().`);
const o = { real: e, imag: s };
return D.runKernel(Fu, o);
}
const No = /* @__PURE__ */ O({ complex_: Cw });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _l(n, t, e, s) {
if (s == null)
s = Lo(n);
else if (s === "complex64")
throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
if (gm(n) || mm(n)) {
if (s !== "float32" && s !== "int32")
throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);
return D.backend.createTensorFromGPUData(n, t || e, s);
}
if (!rn(n) && !Array.isArray(n) && typeof n != "number" && typeof n != "boolean" && typeof n != "string")
throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");
if (t != null) {
Jn(t);
const o = G(t), r = G(e);
I(o === r, () => `Based on the provided shape, [${t}], the tensor should have ${o} values but has ${r}`);
for (let i = 0; i < e.length; ++i) {
const a = e[i], l = i === e.length - 1 ? a !== G(t.slice(i)) : !0;
I(e[i] === t[i] || !l, () => `Error creating a new Tensor. Inferred shape (${e}) does not match the provided shape (${t}). `);
}
}
return !rn(n) && !Array.isArray(n) && (n = [n]), t = t || e, n = s !== "string" ? so(n, s) : Ws(n, [], !0), D.makeTensor(n, t, s);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function km(n, t, e) {
const s = Ol(n, e);
return _l(n, t, s, e);
}
class zo {
/**
* 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(t) {
return new zo(t).slice();
}
constructor(t) {
if (this.shards = [], this.previousShardIndex = 0, t == null || (t instanceof Array || (t = [t]), t = t.map((s) => rn(s) ? s.buffer : s), t.length === 0))
return;
this.bufferUniformSize = t[0].byteLength;
let e = 0;
for (let s = 0; s < t.length; s++) {
const o = t[s];
s !== t.length - 1 && o.byteLength !== this.bufferUniformSize && (this.bufferUniformSize = void 0);
const r = e + o.byteLength;
this.shards.push({ buffer: o, start: e, end: r }), e = r;
}
this.shards.length === 0 && (this.byteLength = 0), this.byteLength = this.shards[this.shards.length - 1].end;
}
slice(t = 0, e = this.byteLength) {
if (this.shards.length === 0)
return new ArrayBuffer(0);
if (t = isNaN(Number(t)) ? 0 : t, e = isNaN(Number(e)) ? 0 : e, t = Math.max(0, t), e = Math.min(this.byteLength, e), e <= t)
return new ArrayBuffer(0);
const s = this.findShardForByte(t);
if (s === -1)
throw new Error(`Could not find start shard for byte ${t}`);
const o = e - t, r = new ArrayBuffer(o), i = new Uint8Array(r);
let a = 0;
for (let l = s; l < this.shards.length; l++) {
const c = this.shards[l], h = t + a - c.start, d = a, f = Math.min(e, c.end) - c.start, m = new Uint8Array(c.buffer, h, f - h);
if (i.set(m, d), a += m.length, e < c.end)
break;
}
return r;
}
/**
* Get the index of the shard that contains the byte at `byteIndex`.
*/
findShardForByte(t) {
if (this.shards.length === 0 || t < 0 || t >= this.byteLength)
return -1;
if (this.bufferUniformSize != null)
return this.previousShardIndex = Math.floor(t / this.bufferUniformSize), this.previousShardIndex;
function e(o) {
return t < o.start ? -1 : t >= o.end ? 1 : 0;
}
if (e(this.shards[this.previousShardIndex]) === 0)
return this.previousShardIndex;
const s = $w(this.shards, e);
return s === -1 ? -1 : (this.previousShardIndex = s, this.previousShardIndex);
}
}
function $w(n, t) {
let e = 0, s = n.length;
for (; e <= s; ) {
const o = Math.floor((s - e) / 2) + e, r = t(n[o]);
if (r === 0)
return o;
r < 0 ? s = o : e = o + 1;
}
return -1;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kn() {
return D;
}
function Vc() {
return D.memory();
}
function _(n, t) {
return D.tidy(n, t);
}
function $t(n) {
xm(n).forEach((e) => e.dispose());
}
function Dn(n) {
return D.keep(n);
}
function bH(n) {
return D.setBackend(n);
}
function yH() {
return D.ready();
}
function vm(n, t, e = 1) {
return D.registerBackend(n, t, e);
}
function Iw() {
return D.backend;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const hp = 4;
async function dp(n, t) {
const e = [], s = [], o = Array.isArray(n) ? n.map((i) => i.name) : Object.keys(n);
for (let i = 0; i < o.length; ++i) {
const a = o[i], l = Array.isArray(n) ? n[i].tensor : n[a];
if (l.dtype !== "float32" && l.dtype !== "int32" && l.dtype !== "bool" && l.dtype !== "string" && l.dtype !== "complex64")
throw new Error(`Unsupported dtype in weight '${a}': ${l.dtype}`);
const c = { name: a, shape: l.shape, dtype: l.dtype };
if (l.dtype === "string") {
const u = new Promise(async (h) => {
const d = await l.bytes(), p = d.reduce((g, x) => g + x.length, 0) + hp * d.length, f = new Uint8Array(p);
let m = 0;
for (let g = 0; g < d.length; g++) {
const x = d[g], b = new Uint8Array(new Uint32Array([x.length]).buffer);
f.set(b, m), m += hp, f.set(x, m), m += x.length;
}
h(f);
});
s.push(u);
} else
s.push(l.data());
t != null && (c.group = t), e.push(c);
}
const r = await Promise.all(s);
return { data: kw(r), specs: e };
}
function kw(n) {
if (n === null)
throw new Error(`Invalid input value: ${JSON.stringify(n)}`);
let t = 0;
const e = [];
n.forEach((r) => {
if (t += r.byteLength, e.push(r.byteLength === r.buffer.byteLength ? r : new r.constructor(r)), !(r instanceof Float32Array || r instanceof Int32Array || r instanceof Uint8Array))
throw new Error(`Unsupported TypedArray subtype: ${r.constructor.name}`);
});
const s = new Uint8Array(t);
let o = 0;
return e.forEach((r) => {
s.set(new Uint8Array(r.buffer), o), o += r.byteLength;
}), s.buffer;
}
const fh = typeof Buffer < "u" && (typeof Blob > "u" || typeof atob > "u" || typeof btoa > "u");
function pp(n) {
return fh ? Buffer.byteLength(n, "utf8") : new Blob([n]).size;
}
function vw(n) {
if (fh)
return Buffer.from(n).toString("base64");
const t = new Uint8Array(n);
let e = "";
for (let s = 0, o = t.length; s < o; s++)
e += String.fromCharCode(t[s]);
return btoa(e);
}
function Sw(n) {
if (fh) {
const s = Buffer.from(n, "base64");
return s.buffer.slice(s.byteOffset, s.byteOffset + s.byteLength);
}
const t = atob(n), e = new Uint8Array(t.length);
for (let s = 0; s < t.length; ++s)
e.set([t.charCodeAt(s)], s);
return e.buffer;
}
function Nw(n) {
return zo.join(n);
}
function Sm(n) {
if (n.modelTopology instanceof ArrayBuffer)
throw new Error("Expected JSON model topology, received ArrayBuffer.");
return {
dateSaved: /* @__PURE__ */ new Date(),
modelTopologyType: "JSON",
modelTopologyBytes: n.modelTopology == null ? 0 : pp(JSON.stringify(n.modelTopology)),
weightSpecsBytes: n.weightSpecs == null ? 0 : pp(JSON.stringify(n.weightSpecs)),
weightDataBytes: n.weightData == null ? 0 : new zo(n.weightData).byteLength
};
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Se {
constructor() {
this.saveRouters = [], this.loadRouters = [];
}
static getInstance() {
return Se.instance == null && (Se.instance = new Se()), Se.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(t) {
Se.getInstance().saveRouters.push(t);
}
/**
* 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(t) {
Se.getInstance().loadRouters.push(t);
}
/**
* 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(t) {
return Se.getHandlers(t, "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(t, e) {
return Se.getHandlers(t, "load", e);
}
static getHandlers(t, e, s) {
const o = [];
return (e === "load" ? Se.getInstance().loadRouters : Se.getInstance().saveRouters).forEach((i) => {
const a = i(t, s);
a !== null && o.push(a);
}), o;
}
}
const Tw = (n) => Se.getSaveHandlers(n);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Wc = "tensorflowjs", Uc = 1, Ls = "models_store", is = "model_info_store";
function Nm() {
if (!P().getBool("IS_BROWSER"))
throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");
const n = typeof window > "u" ? self : window, t = n.indexedDB || n.mozIndexedDB || n.webkitIndexedDB || n.msIndexedDB || n.shimIndexedDB;
if (t == null)
throw new Error("The current browser does not appear to support IndexedDB.");
return t;
}
function Gc(n) {
const t = n.result;
t.createObjectStore(Ls, { keyPath: "modelPath" }), t.createObjectStore(is, { keyPath: "modelPath" });
}
class Us {
constructor(t) {
if (this.indexedDB = Nm(), t == null || !t)
throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");
this.modelPath = t;
}
async save(t) {
if (t.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
return this.databaseAction(this.modelPath, t);
}
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(t, e) {
return new Promise((s, o) => {
const r = this.indexedDB.open(Wc, Uc);
r.onupgradeneeded = () => Gc(r), r.onsuccess = () => {
const i = r.result;
if (e == null) {
const a = i.transaction(Ls, "readonly"), c = a.objectStore(Ls).get(this.modelPath);
c.onsuccess = () => {
if (c.result == null)
return i.close(), o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));
s(c.result.modelArtifacts);
}, c.onerror = (u) => (i.close(), o(c.error)), a.oncomplete = () => i.close();
} else {
e.weightData = zo.join(e.weightData);
const a = Sm(e), l = i.transaction(is, "readwrite");
let c = l.objectStore(is), u;
try {
u = c.put({ modelPath: this.modelPath, modelArtifactsInfo: a });
} catch (d) {
return o(d);
}
let h;
u.onsuccess = () => {
h = i.transaction(Ls, "readwrite");
const d = h.objectStore(Ls);
let p;
try {
p = d.put({
modelPath: this.modelPath,
modelArtifacts: e,
modelArtifactsInfo: a
});
} catch (f) {
return o(f);
}
p.onsuccess = () => s({ modelArtifactsInfo: a }), p.onerror = (f) => {
c = l.objectStore(is);
const m = c.delete(this.modelPath);
m.onsuccess = () => (i.close(), o(p.error)), m.onerror = (g) => (i.close(), o(p.error));
};
}, u.onerror = (d) => (i.close(), o(u.error)), l.oncomplete = () => {
h == null ? i.close() : h.oncomplete = () => i.close();
};
}
}, r.onerror = (i) => o(r.error);
});
}
}
Us.URL_SCHEME = "indexeddb://";
const Tm = (n) => P().getBool("IS_BROWSER") && !Array.isArray(n) && n.startsWith(Us.URL_SCHEME) ? Ew(n.slice(Us.URL_SCHEME.length)) : null;
Se.registerSaveRouter(Tm);
Se.registerLoadRouter(Tm);
function Ew(n) {
return new Us(n);
}
function Rw(n) {
return n.startsWith(Us.URL_SCHEME) ? n.slice(Us.URL_SCHEME.length) : n;
}
class Dw {
constructor() {
this.indexedDB = Nm();
}
async listModels() {
return new Promise((t, e) => {
const s = this.indexedDB.open(Wc, Uc);
s.onupgradeneeded = () => Gc(s), s.onsuccess = () => {
const o = s.result, r = o.transaction(is, "readonly"), a = r.objectStore(is).getAll();
a.onsuccess = () => {
const l = {};
for (const c of a.result)
l[c.modelPath] = c.modelArtifactsInfo;
t(l);
}, a.onerror = (l) => (o.close(), e(a.error)), r.oncomplete = () => o.close();
}, s.onerror = (o) => e(s.error);
});
}
async removeModel(t) {
return t = Rw(t), new Promise((e, s) => {
const o = this.indexedDB.open(Wc, Uc);
o.onupgradeneeded = () => Gc(o), o.onsuccess = () => {
const r = o.result, i = r.transaction(is, "readwrite"), a = i.objectStore(is), l = a.get(t);
let c;
l.onsuccess = () => {
if (l.result == null)
return r.close(), s(new Error(`Cannot find model with path '${t}' in IndexedDB.`));
{
const u = a.delete(t), h = () => {
c = r.transaction(Ls, "readwrite");
const p = c.objectStore(Ls).delete(t);
p.onsuccess = () => e(l.result.modelArtifactsInfo), p.onerror = (f) => s(l.error);
};
u.onsuccess = h, u.onerror = (d) => (h(), r.close(), s(l.error));
}
}, l.onerror = (u) => (r.close(), s(l.error)), i.oncomplete = () => {
c == null ? r.close() : c.oncomplete = () => r.close();
};
}, o.onerror = (r) => s(o.error);
});
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Gn = "/", yo = "tensorflowjs_models", Em = "info", Aw = "model_topology", Fw = "weight_specs", Ow = "weight_data", _w = "model_metadata";
function Rm(n) {
return {
info: [yo, n, Em].join(Gn),
topology: [yo, n, Aw].join(Gn),
weightSpecs: [yo, n, Fw].join(Gn),
weightData: [yo, n, Ow].join(Gn),
modelMetadata: [yo, n, _w].join(Gn)
};
}
function Dm(n) {
for (const t of Object.values(n))
window.localStorage.removeItem(t);
}
function Lw(n) {
const t = n.split(Gn);
if (t.length < 3)
throw new Error(`Invalid key format: ${n}`);
return t.slice(1, t.length - 1).join(Gn);
}
function Mw(n) {
return n.startsWith(Gs.URL_SCHEME) ? n.slice(Gs.URL_SCHEME.length) : n;
}
class Gs {
constructor(t) {
if (!P().getBool("IS_BROWSER") || typeof window > "u" || typeof window.localStorage > "u")
throw new Error("The current environment does not support local storage.");
if (this.LS = window.localStorage, t == null || !t)
throw new Error("For local storage, modelPath must not be null, undefined or empty.");
this.modelPath = t, this.keys = Rm(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(t) {
if (t.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
{
const e = JSON.stringify(t.modelTopology), s = JSON.stringify(t.weightSpecs), o = Sm(t), r = zo.join(t.weightData);
try {
this.LS.setItem(this.keys.info, JSON.stringify(o)), this.LS.setItem(this.keys.topology, e), this.LS.setItem(this.keys.weightSpecs, s), this.LS.setItem(this.keys.weightData, vw(r));
const i = {
format: t.format,
generatedBy: t.generatedBy,
convertedBy: t.convertedBy,
signature: t.signature != null ? t.signature : void 0,
userDefinedMetadata: t.userDefinedMetadata != null ? t.userDefinedMetadata : void 0,
modelInitializer: t.modelInitializer != null ? t.modelInitializer : void 0,
initializerSignature: t.initializerSignature != null ? t.initializerSignature : void 0,
trainingConfig: t.trainingConfig != null ? t.trainingConfig : void 0
};
return this.LS.setItem(this.keys.modelMetadata, JSON.stringify(i)), { modelArtifactsInfo: o };
} catch {
throw Dm(this.keys), new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${o.modelTopologyBytes}, weightSpecsBytes=${o.weightSpecsBytes}, weightDataBytes=${o.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 t = JSON.parse(this.LS.getItem(this.keys.info));
if (t == null)
throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);
if (t.modelTopologyType !== "JSON")
throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");
const e = {}, s = JSON.parse(this.LS.getItem(this.keys.topology));
if (s == null)
throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);
e.modelTopology = s;
const o = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
if (o == null)
throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);
e.weightSpecs = o;
const r = this.LS.getItem(this.keys.modelMetadata);
if (r != null) {
const a = JSON.parse(r);
e.format = a.format, e.generatedBy = a.generatedBy, e.convertedBy = a.convertedBy, a.signature != null && (e.signature = a.signature), a.userDefinedMetadata != null && (e.userDefinedMetadata = a.userDefinedMetadata), a.modelInitializer != null && (e.modelInitializer = a.modelInitializer), a.initializerSignature != null && (e.initializerSignature = a.initializerSignature), a.trainingConfig != null && (e.trainingConfig = a.trainingConfig);
}
const i = this.LS.getItem(this.keys.weightData);
if (i == null)
throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);
return e.weightData = Sw(i), e;
}
}
Gs.URL_SCHEME = "localstorage://";
const Am = (n) => P().getBool("IS_BROWSER") && !Array.isArray(n) && n.startsWith(Gs.URL_SCHEME) ? Pw(n.slice(Gs.URL_SCHEME.length)) : null;
Se.registerSaveRouter(Am);
Se.registerLoadRouter(Am);
function Pw(n) {
return new Gs(n);
}
class zw {
constructor() {
I(P().getBool("IS_BROWSER"), () => "Current environment is not a web browser"), I(typeof window > "u" || typeof window.localStorage < "u", () => "Current browser does not appear to support localStorage"), this.LS = window.localStorage;
}
async listModels() {
const t = {}, e = yo + Gn, s = Gn + Em;
for (let o = 0; o < this.LS.length; ++o) {
const r = this.LS.key(o);
if (r.startsWith(e) && r.endsWith(s)) {
const i = Lw(r);
t[i] = JSON.parse(this.LS.getItem(r));
}
}
return t;
}
async removeModel(t) {
t = Mw(t);
const e = Rm(t);
if (this.LS.getItem(e.info) == null)
throw new Error(`Cannot find model at path '${t}'`);
const s = JSON.parse(this.LS.getItem(e.info));
return Dm(e), s;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const fp = "://";
class vn {
constructor() {
this.managers = {};
}
static getInstance() {
return vn.instance == null && (vn.instance = new vn()), vn.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(t, e) {
I(t != null, () => "scheme must not be undefined or null."), t.endsWith(fp) && (t = t.slice(0, t.indexOf(fp))), I(t.length > 0, () => "scheme must not be an empty string.");
const s = vn.getInstance();
I(s.managers[t] == null, () => `A model store manager is already registered for scheme '${t}'.`), s.managers[t] = e;
}
static getManager(t) {
const e = vn.getInstance().managers[t];
if (e == null)
throw new Error(`Cannot find model manager for scheme '${t}'`);
return e;
}
static getSchemes() {
return Object.keys(vn.getInstance().managers);
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Bw {
constructor() {
this.messageName = "setTimeoutCustom", this.functionRefs = [], this.handledMessageCount = 0, this.hasEventListener = !1;
}
fetch(t, e) {
return fetch(t, e);
}
now() {
return performance.now();
}
encode(t, e) {
if (e !== "utf-8" && e !== "utf8")
throw new Error(`Browser's encoder only supports utf-8, but got ${e}`);
return this.textEncoder == null && (this.textEncoder = new TextEncoder()), this.textEncoder.encode(t);
}
decode(t, e) {
return new TextDecoder(e).decode(t);
}
// 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(t, e) {
if (typeof window > "u" || !P().getBool("USE_SETTIMEOUTCUSTOM")) {
setTimeout(t, e);
return;
}
this.functionRefs.push(t), setTimeout(() => {
window.postMessage({ name: this.messageName, index: this.functionRefs.length - 1 }, "*");
}, e), this.hasEventListener || (this.hasEventListener = !0, window.addEventListener("message", (s) => {
if (s.source === window && s.data.name === this.messageName) {
s.stopPropagation();
const o = this.functionRefs[s.data.index];
o(), this.handledMessageCount++, this.handledMessageCount === this.functionRefs.length && (this.functionRefs = [], this.handledMessageCount = 0);
}
}, !0));
}
isTypedArray(t) {
return hm(t);
}
}
if (P().get("IS_BROWSER")) {
P().setPlatform("browser", new Bw());
try {
vn.registerManager(Gs.URL_SCHEME, new zw());
} catch {
}
try {
vn.registerManager(Us.URL_SCHEME, new Dw());
} catch {
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Vw = {
// tslint:disable-next-line:no-require-imports
importFetch: () => require("node-fetch")
};
let fc;
class Ww {
constructor() {
this.util = require("util"), this.textEncoder = new this.util.TextEncoder();
}
fetch(t, e) {
return P().global.fetch != null ? P().global.fetch(t, e) : (fc == null && (fc = Vw.importFetch()), fc(t, e));
}
now() {
const t = process.hrtime();
return t[0] * 1e3 + t[1] / 1e6;
}
encode(t, e) {
if (e !== "utf-8" && e !== "utf8")
throw new Error(`Node built-in encoder only supports utf-8, but got ${e}`);
return this.textEncoder.encode(t);
}
decode(t, e) {
return t.length === 0 ? "" : new this.util.TextDecoder(e).decode(t);
}
isTypedArray(t) {
return this.util.types.isFloat32Array(t) || this.util.types.isInt32Array(t) || this.util.types.isUint8Array(t) || this.util.types.isUint8ClampedArray(t);
}
}
P().get("IS_NODE") && !P().get("IS_BROWSER") && P().setPlatform("node", new Ww());
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yt(n, t = "float32", e) {
return t = t || "float32", Jn(n), new ge(n, t, e);
}
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Uw(n, t) {
const e = N(n, "x", "cast");
if (!P1(t))
throw new Error(`Failed to cast to unknown dtype ${t}`);
if (t === "string" && e.dtype !== "string" || t !== "string" && e.dtype === "string")
throw new Error("Only strings can be casted to strings");
const s = { x: e }, o = { dtype: t };
return D.runKernel(Fr, s, o);
}
const st = /* @__PURE__ */ O({ cast_: Uw });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Gw(n) {
const e = { x: N(n, "x", "clone", "string_or_numeric") };
return D.runKernel(Kr, e);
}
const Ps = /* @__PURE__ */ O({ clone_: Gw });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Hw(n, t = !1) {
console.log(n.toString(t));
}
/**
* @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.
* =============================================================================
*/
ym();
const Kw = {
buffer: yt,
cast: st,
clone: Ps,
print: Hw
};
fw(Kw);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function jw(n, t) {
let e = N(n, "a", "add"), s = N(t, "b", "add");
[e, s] = Jt(e, s);
const o = { a: e, b: s };
return D.runKernel(Po, o);
}
const Y = /* @__PURE__ */ O({ add_: jw });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Xw(n, t) {
let e = N(n, "a", "floorDiv"), s = N(t, "b", "floorDiv");
[e, s] = Jt(e, s);
const o = { a: e, b: s };
return D.runKernel(Gr, o);
}
const Fm = /* @__PURE__ */ O({ floorDiv_: Xw });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function qw(n, t) {
let e = N(n, "a", "div"), s = N(t, "b", "div");
if ([e, s] = Jt(e, s), e.dtype === "int32" && s.dtype === "int32")
return Fm(e, s);
const o = { a: e, b: s }, r = {};
return D.runKernel(Pr, o, r);
}
const ut = /* @__PURE__ */ O({ div_: qw });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Yw(n, t) {
let e = N(n, "a", "mul"), s = N(t, "b", "mul");
[e, s] = Jt(e, s);
const o = { a: e, b: s };
return D.runKernel(ei, o);
}
const R = /* @__PURE__ */ O({ mul_: Yw });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Jw(n) {
const t = N(n, "x", "abs");
if (t.dtype === "complex64") {
const e = { x: t };
return D.runKernel(Ba, e);
} else {
const e = { x: t };
return D.runKernel(Fa, e);
}
}
const Ne = /* @__PURE__ */ O({ abs_: Jw });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Zw(n) {
const e = { x: N(n, "x", "acos") };
return D.runKernel(Sr, e);
}
const Qw = /* @__PURE__ */ O({ acos_: Zw });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function tC(n) {
const e = { x: N(n, "x", "acosh") };
return D.runKernel(Nr, e);
}
const eC = /* @__PURE__ */ O({ acosh_: tC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nC(n, t = null, e = !1) {
const o = { x: N(n, "x", "all", "bool") }, r = { axis: t, keepDims: e };
return D.runKernel(Nu, o, r);
}
const Om = /* @__PURE__ */ O({ all_: nC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sC(n, t = null, e = !1) {
const o = { x: N(n, "x", "any", "bool") }, r = { axis: t, keepDims: e };
return D.runKernel(Tu, o, r);
}
const Hc = /* @__PURE__ */ O({ any_: sC });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function oC(n, t = 0) {
const s = { x: N(n, "x", "argMax") }, o = { axis: t };
return D.runKernel(Oa, s, o);
}
const dr = /* @__PURE__ */ O({ argMax_: oC });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function rC(n, t = 0) {
const s = { x: N(n, "x", "argMin") }, o = { axis: t };
return D.runKernel(_a, s, o);
}
const iC = /* @__PURE__ */ O({ argMin_: rC });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function aC(n) {
const e = { x: N(n, "x", "asin") };
return D.runKernel(Tr, e);
}
const lC = /* @__PURE__ */ O({ asin_: aC });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function cC(n) {
const e = { x: N(n, "x", "asinh") };
return D.runKernel(Er, e);
}
const uC = /* @__PURE__ */ O({ asinh_: cC });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function hC(n) {
const e = { x: N(n, "x", "atan") };
return D.runKernel(Rr, e);
}
const dC = /* @__PURE__ */ O({ atan_: hC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function pC(n, t) {
let e = N(n, "a", "atan2"), s = N(t, "b", "atan2");
[e, s] = Jt(e, s);
const o = { a: e, b: s };
return D.runKernel(Ar, o);
}
const fC = /* @__PURE__ */ O({ atan2_: pC });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function mC(n) {
const e = { x: N(n, "x", "atanh") };
return D.runKernel(Dr, e);
}
const gC = /* @__PURE__ */ O({ atanh_: mC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ci(n, t, e, s, o = "NHWC", r) {
const i = n[3], a = [...t, i], l = Qn(o);
return xe(n, a, e, r, s, null, null, l);
}
function ln(n, t, e, s, o, r, i = "channelsLast") {
const [a, l] = pr(t);
let c;
if (i === "channelsLast")
c = [a, l, n[3], n[3]];
else if (i === "channelsFirst")
c = [a, l, n[1], n[1]];
else
throw new Error(`Unknown dataFormat ${i}`);
return xe(n, c, e, s, o, r, !1, i);
}
function Zn(n, t, e, s, o, r, i = "NDHWC") {
const [a, l, c] = Kc(t);
let u, h;
if (i === "NDHWC")
h = "channelsLast", u = [a, l, c, n[4], n[4]];
else if (i === "NCDHW")
h = "channelsFirst", u = [a, l, c, n[1], n[1]];
else
throw new Error(`Unknown dataFormat ${i}`);
return Cs(n, u, e, s, o, !1, h, r);
}
function xe(n, t, e, s, o, r, i = !1, a = "channelsLast") {
let [l, c, u, h] = [-1, -1, -1, -1];
if (a === "channelsLast")
[l, c, u, h] = n;
else if (a === "channelsFirst")
[l, h, c, u] = n;
else
throw new Error(`Unknown dataFormat ${a}`);
const [d, p, , f] = t, [m, g] = pr(e), [x, b] = pr(s), w = $o(d, x), y = $o(p, b), { padInfo: C, outHeight: $, outWidth: k } = yC(o, c, u, m, g, w, y, r, a), v = i ? f * h : f;
let S;
return a === "channelsFirst" ? S = [l, v, $, k] : a === "channelsLast" && (S = [l, $, k, v]), {
batchSize: l,
dataFormat: a,
inHeight: c,
inWidth: u,
inChannels: h,
outHeight: $,
outWidth: k,
outChannels: v,
padInfo: C,
strideHeight: m,
strideWidth: g,
filterHeight: d,
filterWidth: p,
effectiveFilterHeight: w,
effectiveFilterWidth: y,
dilationHeight: x,
dilationWidth: b,
inShape: n,
outShape: S,
filterShape: t
};
}
function Cs(n, t, e, s, o, r = !1, i = "channelsLast", a) {
let [l, c, u, h, d] = [-1, -1, -1, -1, -1];
if (i === "channelsLast")
[l, c, u, h, d] = n;
else if (i === "channelsFirst")
[l, d, c, u, h] = n;
else
throw new Error(`Unknown dataFormat ${i}`);
const [p, f, m, , g] = t, [x, b, w] = Kc(e), [y, C, $] = Kc(s), k = $o(p, y), v = $o(f, C), S = $o(m, $), { padInfo: T, outDepth: F, outHeight: L, outWidth: M } = wC(o, c, u, h, x, b, w, k, v, S, a), B = r ? g * d : g;
let z;
return i === "channelsFirst" ? z = [l, B, F, L, M] : i === "channelsLast" && (z = [l, F, L, M, B]), {
batchSize: l,
dataFormat: i,
inDepth: c,
inHeight: u,
inWidth: h,
inChannels: d,
outDepth: F,
outHeight: L,
outWidth: M,
outChannels: B,
padInfo: T,
strideDepth: x,
strideHeight: b,
strideWidth: w,
filterDepth: p,
filterHeight: f,
filterWidth: m,
effectiveFilterDepth: k,
effectiveFilterHeight: v,
effectiveFilterWidth: S,
dilationDepth: y,
dilationHeight: C,
dilationWidth: $,
inShape: n,
outShape: z,
filterShape: t
};
}
function xC(n, t, e, s, o) {
s == null && (s = mh(n, t, e));
const r = n[0], i = n[1], a = fr((r - t + 2 * s) / e + 1, o), l = fr((i - t + 2 * s) / e + 1, o);
return [a, l];
}
function bC(n, t, e, s, o, r) {
o == null && (o = mh(n, t[0], s[0]));
const i = [0, 0, 0, e];
for (let a = 0; a < 3; a++)
n[a] + 2 * o >= t[a] && (i[a] = fr((n[a] - t[a] + 2 * o) / s[a] + 1, r));
return i;
}
function mh(n, t, e, s = 1) {
const o = $o(t, s);
return Math.floor((n[0] * (e - 1) - e + o) / 2);
}
function pr(n) {
return typeof n == "number" ? [n, n, n] : n.length === 2 ? [n[0], n[1], 1] : n;
}
function Kc(n) {
return typeof n == "number" ? [n, n, n] : n;
}
function $o(n, t) {
return t <= 1 ? n : n + (n - 1) * (t - 1);
}
function yC(n, t, e, s, o, r, i, a, l) {
let c, u, h;
if (typeof n == "number") {
c = { top: n, bottom: n, left: n, right: n, type: n === 0 ? "VALID" : "NUMBER" };
const p = xC([t, e], r, s, n, a);
u = p[0], h = p[1];
} else if (n === "same") {
u = Math.ceil(t / s), h = Math.ceil(e / o);
const d = Math.max(0, (u - 1) * s + r - t), p = Math.max(0, (h - 1) * o + i - e), f = Math.floor(d / 2), m = d - f, g = Math.floor(p / 2), x = p - g;
c = { top: f, bottom: m, left: g, right: x, type: "SAME" };
} else if (n === "valid")
c = { top: 0, bottom: 0, left: 0, right: 0, type: "VALID" }, u = Math.ceil((t - r + 1) / s), h = Math.ceil((e - i + 1) / o);
else if (typeof n == "object") {
const d = l === "channelsLast" ? n[1][0] : n[2][0], p = l === "channelsLast" ? n[1][1] : n[2][1], f = l === "channelsLast" ? n[2][0] : n[3][0], m = l === "channelsLast" ? n[2][1] : n[3][1];
c = { top: d, bottom: p, left: f, right: m, type: d === 0 && p === 0 && f === 0 && m === 0 ? "VALID" : "EXPLICIT" }, u = fr((t - r + d + p) / s + 1, a), h = fr((e - i + f + m) / o + 1, a);
} else
throw Error(`Unknown padding parameter: ${n}`);
return { padInfo: c, outHeight: u, outWidth: h };
}
function wC(n, t, e, s, o, r, i, a, l, c, u) {
let h, d, p, f;
if (n === "valid" && (n = 0), typeof n == "number") {
h = {
top: n,
bottom: n,
left: n,
right: n,
front: n,
back: n,
type: n === 0 ? "VALID" : "NUMBER"
};
const g = bC([t, e, s, 1], [a, l, c], 1, [o, r, i], n, u);
d = g[0], p = g[1], f = g[2];
} else if (n === "same") {
d = Math.ceil(t / o), p = Math.ceil(e / r), f = Math.ceil(s / i);
const m = (d - 1) * o + a - t, g = (p - 1) * r + l - e, x = (f - 1) * i + c - s, b = Math.floor(m / 2), w = m - b, y = Math.floor(g / 2), C = g - y, $ = Math.floor(x / 2), k = x - $;
h = { top: y, bottom: C, left: $, right: k, front: b, back: w, type: "SAME" };
} else
throw Error(`Unknown padding parameter: ${n}`);
return { padInfo: h, outDepth: d, outHeight: p, outWidth: f };
}
function fr(n, t) {
if (!t)
return Math.trunc(n);
switch (t) {
case "round":
return Math.round(n);
case "ceil":
return Math.ceil(n);
case "floor":
return Math.floor(n);
default:
throw new Error(`Unknown roundingMode ${t}`);
}
}
function Hs(n) {
const [t, e, s] = pr(n);
return t === 1 && e === 1 && s === 1;
}
function Ie(n, t) {
return Hs(n) || Hs(t);
}
function Ks(n) {
return pr(n).every((t) => t > 0);
}
function Qn(n) {
if (n === "NHWC")
return "channelsLast";
if (n === "NCHW")
return "channelsFirst";
throw new Error(`Unknown dataFormat ${n}`);
}
function ze(n, t, e) {
if (e != null) {
if (typeof t == "string")
throw Error(`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);
if (typeof t == "number")
I(vo(t), () => `Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);
else if (typeof t == "object")
t.forEach((s) => {
s.forEach((o) => {
I(vo(o), () => `Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${o}.`);
});
});
else
throw Error(`Error in ${n}: Unknown padding parameter: ${t}`);
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function CC(n, t) {
const s = { x: N(n, "x", "reshape", "string_or_numeric") }, o = { shape: t };
return D.runKernel(wl, s, o);
}
const A = /* @__PURE__ */ O({ reshape_: CC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function $C(n, t, e, s, o) {
const r = N(n, "x", "avgPool", "float32"), i = 1;
I(Ie(e, i), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`);
let a = r, l = !1;
r.rank === 3 && (l = !0, a = A(r, [1, r.shape[0], r.shape[1], r.shape[2]])), I(a.rank === 4, () => `Error in avgPool: x must be rank 4 but got rank ${a.rank}.`), ze("avgPool", s, o);
const c = { x: a }, u = { filterSize: t, strides: e, pad: s, dimRoundingMode: o };
let h = D.runKernel(La, c, u);
return h = st(h, r.dtype), l ? A(h, [h.shape[1], h.shape[2], h.shape[3]]) : h;
}
const gh = /* @__PURE__ */ O({ avgPool_: $C });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function IC(n, t, e, s, o, r = "NDHWC") {
const i = N(n, "x", "avgPool3d", "float32");
let a = i, l = !1;
i.rank === 4 && (l = !0, a = A(i, [1, i.shape[0], i.shape[1], i.shape[2], i.shape[3]])), I(a.rank === 5, () => `Error in avgPool3d: x must be rank 5 but got rank ${a.rank}.`), I(r === "NDHWC", () => `Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`), I(typeof e == "number" && e > 0 || Array.isArray(e) && e[0] > 0 && e[1] > 0 && e[2] > 0, () => `Error in avgPool3d: Stride must be > 0, but got '${e}'`), ze("avgPool3d", s, o);
const c = { x: a }, u = { filterSize: t, strides: e, pad: s, dimRoundingMode: o, dataFormat: r };
let h = D.runKernel(Ma, c, u);
return h = st(h, a.dtype), l ? A(h, [h.shape[1], h.shape[2], h.shape[3], h.shape[4]]) : h;
}
const kC = /* @__PURE__ */ O({ avgPool3d_: IC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function vC(n, t = 0) {
I(n.length >= 1, () => "Pass at least one tensor to concat");
const e = Im(n, "tensors", "concat", "string_or_numeric");
if (e[0].dtype === "complex64" && e.forEach((r) => {
if (r.dtype !== "complex64")
throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${r.dtype}. `);
}), e.length === 1)
return Ps(e[0]);
const s = e, o = { axis: t };
return D.runKernel(Va, s, o);
}
const Le = /* @__PURE__ */ O({ concat_: vC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function SC(n, t, e = !1, s = !1) {
let o = N(n, "a", "matMul"), r = N(t, "b", "matMul");
[o, r] = Jt(o, r);
const i = { a: o, b: r }, a = { transposeA: e, transposeB: s };
return D.runKernel(Pa, i, a);
}
const Nt = /* @__PURE__ */ O({ matMul_: SC });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function NC(n) {
const e = { x: N(n, "x", "sigmoid", "float32") };
return D.runKernel(di, e);
}
const Bo = /* @__PURE__ */ O({ sigmoid_: NC });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function TC(n, t, e) {
const s = N(n, "x", "slice", "string_or_numeric");
if (s.rank === 0)
throw new Error("Slicing scalar is not possible");
const o = { x: s }, r = { begin: t, size: e };
return D.runKernel(vl, o, r);
}
const zt = /* @__PURE__ */ O({ slice_: TC });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function EC(n) {
const e = { x: N(n, "x", "tanh", "float32") };
return D.runKernel(bi, e);
}
const Ll = /* @__PURE__ */ O({ tanh_: EC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function RC(n, t, e) {
const s = N(n, "x", "batchToSpaceND"), o = t.reduce((a, l) => a * l);
I(s.rank >= 1 + t.length, () => `input rank is ${s.rank} but should be > than blockShape.length ${t.length}`), I(e.length === t.length, () => `crops.length is ${e.length} but should be equal to blockShape.length ${t.length}`), I(s.shape[0] % o === 0, () => `input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${o}`);
const r = { x: s }, i = { blockShape: t, crops: e };
return D.runKernel(za, r, i);
}
const xh = /* @__PURE__ */ O({ batchToSpaceND_: RC });
function DC(n) {
let t;
return n.rank === 0 || n.rank === 1 ? t = A(n, [1, 1, 1, n.size]) : n.rank === 2 ? t = A(n, [1, 1, n.shape[0], n.shape[1]]) : n.rank === 3 ? t = A(n, [1, n.shape[0], n.shape[1], n.shape[2]]) : t = n, t;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function AC(n, t, e, s, o, r) {
r == null && (r = 1e-3);
const i = N(n, "x", "batchNorm"), a = N(t, "mean", "batchNorm"), l = N(e, "variance", "batchNorm");
let c;
o != null && (c = N(o, "scale", "batchNorm"));
let u;
s != null && (u = N(s, "offset", "batchNorm")), I(a.rank === l.rank, () => "Batch normalization gradient requires mean and variance to have equal ranks."), I(u == null || a.rank === u.rank, () => "Batch normalization gradient requires mean and offset to have equal ranks."), I(c == null || a.rank === c.rank, () => "Batch normalization gradient requires mean and scale to have equal ranks.");
const d = {
x: DC(i),
scale: c,
offset: u,
mean: a,
variance: l
}, p = { varianceEpsilon: r }, f = D.runKernel(Ya, d, p);
return A(f, i.shape);
}
const Ml = /* @__PURE__ */ O({ batchNorm_: AC });
function FC(n, t, e, s, o, r) {
const i = N(n, "x", "batchNorm"), a = N(t, "mean", "batchNorm"), l = N(e, "variance", "batchNorm");
let c;
o != null && (c = N(o, "scale", "batchNorm"));
let u;
return s != null && (u = N(s, "offset", "batchNorm")), I(i.rank === 2, () => `Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`), I(a.rank === 2 || a.rank === 1, () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`), I(l.rank === 2 || l.rank === 1, () => `Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`), c != null && I(c.rank === 2 || c.rank === 1, () => `Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`), u != null && I(u.rank === 2 || u.rank === 1, () => `Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`), Ml(i, a, l, u, c, r);
}
const OC = /* @__PURE__ */ O({ batchNorm2d_: FC });
function _C(n, t, e, s, o, r) {
const i = N(n, "x", "batchNorm"), a = N(t, "mean", "batchNorm"), l = N(e, "variance", "batchNorm");
let c;
o != null && (c = N(o, "scale", "batchNorm"));
let u;
return s != null && (u = N(s, "offset", "batchNorm")), I(i.rank === 3, () => `Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`), I(a.rank === 3 || a.rank === 1, () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`), I(l.rank === 3 || l.rank === 1, () => `Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`), c != null && I(c.rank === 3 || c.rank === 1, () => `Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`), u != null && I(u.rank === 3 || u.rank === 1, () => `Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`), Ml(i, a, l, u, c, r);
}
const LC = /* @__PURE__ */ O({ batchNorm3d_: _C });
function MC(n, t, e, s, o, r) {
const i = N(n, "x", "batchNorm"), a = N(t, "mean", "batchNorm"), l = N(e, "variance", "batchNorm");
let c;
o != null && (c = N(o, "scale", "batchNorm"));
let u;
return s != null && (u = N(s, "offset", "batchNorm")), I(i.rank === 4, () => `Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`), I(a.rank === 4 || a.rank === 1, () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`), I(l.rank === 4 || l.rank === 1, () => `Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`), c != null && I(c.rank === 4 || c.rank === 1, () => `Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`), u != null && I(u.rank === 4 || u.rank === 1, () => `Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`), Ml(i, a, l, u, c, r);
}
const PC = /* @__PURE__ */ O({ batchNorm4d_: MC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function zC(n, t, e) {
const s = N(n, "x", "bincount"), o = N(t, "weights", "bincount");
I(s.dtype === "int32", () => `Error in bincount: input dtype must be int32, but got ${s.dtype}`), I(e >= 0, () => `size must be non-negative, but got ${e}.`), I(o.size === s.size || o.size === 0, () => `Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${o.shape}.`);
const r = { x: s, weights: o }, i = { size: e };
return D.runKernel(Du, r, i);
}
const BC = /* @__PURE__ */ O({ bincount_: zC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function VC(n, t) {
let e = N(n, "broadcastTo", "x");
const s = e.shape;
if (Jn(t), t.length < e.rank)
throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${e.rank}.`);
if (t.length > e.rank) {
const c = e.shape.slice();
for (; c.length < t.length; )
c.unshift(1);
e = A(e, c);
}
const o = e.shape, r = Array.from(t);
for (let c = t.length - 1; c >= 0; c--)
if (o[c] === t[c])
r[c] = 1;
else if (e.shape[c] !== 1)
throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);
if (r.map((c, u) => c > 1 ? u : -1).filter((c) => c >= 0).length === 0)
return Ps(e);
const a = { x: e }, l = { reps: r };
return D.runKernel(yi, a, l);
}
const ur = /* @__PURE__ */ O({ broadcastTo_: VC });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function WC(n) {
const e = { x: N(n, "x", "ceil", "float32") };
return D.runKernel(Or, e);
}
const UC = /* @__PURE__ */ O({ ceil_: WC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Pl(n, t, e) {
Jn(n), e = e || Lo(t);
const s = { shape: n, value: t, dtype: e };
return D.runKernel(Ku, {}, s);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function GC(n, t, e) {
const s = N(n, "x", "clipByValue");
if (I(t <= e, () => `Error in clip: min (${t}) must be less than or equal to max (${e}).`), t === e)
return Pl(s.shape, t, s.dtype);
const o = { x: s }, r = { clipValueMin: t, clipValueMax: e };
return D.runKernel(_r, o, r);
}
const Ye = /* @__PURE__ */ O({ clipByValue_: GC });
function HC(n) {
return Le(
n,
0
/* axis */
);
}
const KC = /* @__PURE__ */ O({ concat1d_: HC });
function jC(n, t) {
return Le(n, t);
}
const XC = /* @__PURE__ */ O({ concat2d_: jC });
function qC(n, t) {
return Le(n, t);
}
const YC = /* @__PURE__ */ O({ concat3d_: qC });
function JC(n, t) {
return Le(n, t);
}
const ZC = /* @__PURE__ */ O({ concat4d_: JC });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function QC(n, t, e, s, o = "NHWC", r = [1, 1], i) {
const a = N(n, "x", "conv2d", "float32"), l = N(t, "filter", "conv2d", "float32");
let c = a, u = !1;
a.rank === 3 && (u = !0, c = A(a, [1, a.shape[0], a.shape[1], a.shape[2]])), I(c.rank === 4, () => `Error in conv2d: input must be rank 4, but got rank ${c.rank}.`), I(l.rank === 4, () => `Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`), ze("conv2d", s, i);
const h = o === "NHWC" ? c.shape[3] : c.shape[1];
I(h === l.shape[2], () => `Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`), I(Ie(e, r), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`), I(Ks(r), () => "Error in conv2D: Dilated rates should be larger than 0."), I(Ks(e), () => "Error in conv2D: Strides should be larger than 0.");
const d = { x: c, filter: l }, p = { strides: e, pad: s, dataFormat: o, dilations: r, dimRoundingMode: i }, f = D.runKernel(Wa, d, p);
return u ? A(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
const js = /* @__PURE__ */ O({ conv2d_: QC });
function t$(n, t, e, s, o = "NWC", r = 1, i) {
const a = N(n, "x", "conv1d"), l = N(t, "filter", "conv1d");
let c = a, u = !1;
a.rank === 2 && (u = !0, c = A(a, [1, a.shape[0], a.shape[1]])), I(c.rank === 3, () => `Error in conv1d: input must be rank 3, but got rank ${c.rank}.`), I(l.rank === 3, () => `Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`), ze("conv1d", s, i), I(c.shape[2] === l.shape[1], () => `Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`), I(Ie(e, r), () => `Error in conv1D: Either stride or dilation must be 1. Got stride ${e} and dilation '${r}'`), I(Ks(r), () => "Error in conv1D: Dilated rates should be larger than 0."), I(Ks(e), () => "Error in conv1D: Stride should be larger than 0."), I(o === "NWC", () => `Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);
const h = A(l, [1, l.shape[0], l.shape[1], l.shape[2]]), d = A(c, [c.shape[0], 1, c.shape[1], c.shape[2]]), g = js(d, h, [1, e], s, "NHWC", [1, r], i);
return u ? A(g, [g.shape[2], g.shape[3]]) : A(g, [g.shape[0], g.shape[2], g.shape[3]]);
}
const _m = /* @__PURE__ */ O({ conv1d_: t$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function e$(n, t, e, s, o, r = "NHWC", i) {
I(n.length === t.rank, () => `Length of inShape (${n.length}) and rank of dy (${t.rank}) must match`);
let a = n, l = t, c = !1;
t.rank === 3 && (c = !0, l = A(t, [1, t.shape[0], t.shape[1], t.shape[2]]), a = [1, n[0], n[1], n[2]]), I(a.length === 4, () => `Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`), I(l.rank === 4, () => `Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`), I(e.rank === 4, () => `Error in conv2dDerInput: filter must be rank 4, but got rank ${e.rank}`);
const u = r === "NHWC" ? a[3] : a[1], h = r === "NHWC" ? l.shape[3] : l.shape[1];
I(u === e.shape[2], () => `Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${e.shape[2]}.`), I(h === e.shape[3], () => `Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${e.shape[3]}.`), ze("conv2dDerInput", o, i);
const d = { dy: l, filter: e }, p = { strides: s, pad: o, dataFormat: r, dimRoundingMode: i, inputShape: a }, f = D.runKernel(Ua, d, p);
return c ? A(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
const bh = /* @__PURE__ */ O({ conv2DBackpropInput_: e$ });
function n$(n, t, e, s, o, r) {
const i = N(n, "x", "conv2dTranspose"), a = N(t, "filter", "conv2dTranspose");
return bh(e, i, a, s, o, "NHWC", r);
}
const Lm = /* @__PURE__ */ O({ conv2dTranspose_: n$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function s$(n, t, e, s, o = "NDHWC", r = [1, 1, 1]) {
const i = N(n, "x", "conv3d"), a = N(t, "filter", "conv3d");
let l = i, c = !1;
i.rank === 4 && (c = !0, l = A(i, [1, i.shape[0], i.shape[1], i.shape[2], i.shape[3]])), I(l.rank === 5, () => `Error in conv3d: input must be rank 5, but got rank ${l.rank}.`), I(a.rank === 5, () => `Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`), I(l.shape[4] === a.shape[3], () => `Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${a.shape[3]}.`), I(Ie(e, r), () => `Error in conv3D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`), I(o === "NDHWC", () => `Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`), I(Ks(r), () => "Error in conv3D: Dilated rates should be larger than 0."), I(Ks(e), () => "Error in conv3D: Strides should be larger than 0.");
const u = { x: l, filter: a }, h = { strides: e, pad: s, dataFormat: o, dilations: r }, d = D.runKernel(Ga, u, h);
return c ? A(d, [d.shape[1], d.shape[2], d.shape[3], d.shape[4]]) : d;
}
const o$ = /* @__PURE__ */ O({ conv3d_: s$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function r$(n, t, e, s, o) {
I(n.length === t.rank, () => `Length of inShape (${n.length}) and rank of dy (${t.rank}) must match`);
let r = n, i = t, a = !1;
t.rank === 4 && (a = !0, i = A(t, [1, t.shape[0], t.shape[1], t.shape[2], t.shape[3]]), r = [1, n[0], n[1], n[2], n[3]]);
const l = r[4], c = i.shape[4];
I(r.length === 5, () => `Error in conv3dDerInput: inShape must be length 5, but got length ${r.length}.`), I(i.rank === 5, () => `Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`), I(e.rank === 5, () => `Error in conv3dDerInput: filter must be rank 5, but got rank ${e.rank}`), I(l === e.shape[3], () => `Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${e.shape[3]}.`), I(c === e.shape[4], () => `Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${e.shape[4]}.`);
const u = { dy: i, filter: e }, h = { pad: o, strides: s, inputShape: r }, d = D.runKernel(Lu, u, h);
return a ? A(d, [d.shape[1], d.shape[2], d.shape[3], d.shape[4]]) : d;
}
const Mm = /* @__PURE__ */ O({ conv3DBackpropInput_: r$ });
function i$(n, t, e, s, o) {
const r = N(n, "x", "conv3dTranspose"), i = N(t, "filter", "conv3dTranspose");
return Mm(e, r, i, s, o);
}
const a$ = /* @__PURE__ */ O({ conv3dTranspose_: i$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function l$(n) {
const e = { x: N(n, "x", "cos", "float32") };
return D.runKernel(Lr, e);
}
const yh = /* @__PURE__ */ O({ cos_: l$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function c$(n) {
const e = { x: N(n, "x", "cosh", "float32") };
return D.runKernel(Mr, e);
}
const Pm = /* @__PURE__ */ O({ cosh_: c$ });
/**
* @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.
* =============================================================================
*/
function u$(n, t = 0, e = !1, s = !1) {
const r = { x: N(n, "x", "cumprod") }, i = { axis: t, exclusive: e, reverse: s };
return D.runKernel(Mu, r, i);
}
const jc = /* @__PURE__ */ O({ cumprod_: u$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function h$(n, t = 0, e = !1, s = !1) {
const r = { x: N(n, "x", "cumsum") }, i = { axis: t, exclusive: e, reverse: s };
return D.runKernel(Ha, r, i);
}
const zm = /* @__PURE__ */ O({ cumsum_: h$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function d$(n, t, e, s = !1) {
const o = N(n, "x", "denseBincount"), r = N(t, "weights", "denseBincount");
I(o.dtype === "int32", () => `Error in denseBincount: input dtype must be int32, but got ${o.dtype}`), I(o.rank <= 2, () => `Error in denseBincount: input must be at most rank 2, but got rank ${o.rank}.`), I(e >= 0, () => `size must be non-negative, but got ${e}.`), I(r.size === o.size || r.size === 0, () => `Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${o.shape}, weights shape: ${r.shape}.`);
const i = { x: o, weights: r }, a = { size: e, binaryOutput: s };
return D.runKernel(zu, i, a);
}
const mp = /* @__PURE__ */ O({ denseBincount_: d$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function p$(n, t, e = "NHWC") {
const s = N(n, "x", "depthToSpace", "float32"), o = e === "NHWC" ? s.shape[1] : s.shape[2], r = e === "NHWC" ? s.shape[2] : s.shape[3], i = e === "NHWC" ? s.shape[3] : s.shape[1];
I(t > 1, () => `blockSize should be > 1 for depthToSpace, but was: ${t}`), I(o * t >= 0, () => `Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
${s.shape}`), I(r * t >= 0, () => `Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${s.shape}`), I(i % (t * t) === 0, () => `Dimension size must be evenly divisible by ${t * t} but is ${i} for depthToSpace with input shape ${s.shape}`);
const a = { x: s }, l = { blockSize: t, dataFormat: e };
return D.runKernel(Bu, a, l);
}
const f$ = /* @__PURE__ */ O({ depthToSpace_: p$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function m$(n, t, e, s, o = "NHWC", r = [1, 1], i) {
const a = N(n, "x", "depthwiseConv2d", "float32"), l = N(t, "filter", "depthwiseConv2d", "float32");
let c = a, u = !1;
a.rank === 3 && (u = !0, c = A(a, [1, a.shape[0], a.shape[1], a.shape[2]])), I(c.rank === 4, () => `Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`), I(l.rank === 4, () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);
const h = o === "NHWC" ? c.shape[3] : c.shape[1];
I(h === l.shape[2], () => `Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`), ze("depthwiseConv2d", s, i);
const d = { x: c, filter: l }, p = { strides: e, pad: s, dataFormat: o, dilations: r, dimRoundingMode: i }, f = D.runKernel(Ka, d, p);
return u ? A(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
const wh = /* @__PURE__ */ O({ depthwiseConv2d_: m$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function g$(n, t, e, s, o = [1, 1], r = "NHWC") {
const i = N(n, "x", "dilation2d"), a = N(t, "filter", "dilation2d");
I(i.rank === 3 || i.rank === 4, () => `Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`), I(a.rank === 3, () => `Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`), I(r === "NHWC", () => `Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${r}`);
let l = i, c = !1;
i.rank === 3 && (l = A(i, [1, i.shape[0], i.shape[1], i.shape[2]]), c = !0), I(l.shape[3] === a.shape[2], () => `Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${a.shape[2]}`);
const u = { x: l, filter: a }, h = { strides: e, pad: s, dilations: o }, d = D.runKernel(ja, u, h);
return c ? A(d, [d.shape[1], d.shape[2], d.shape[3]]) : d;
}
const x$ = /* @__PURE__ */ O({ dilation2d_: g$ });
/**
* @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.
* =============================================================================
*/
function To(n, t) {
const e = n.length, s = [];
for (let o = 0; o < e; o++) {
const r = e - 1 - o, i = n[r] || 1;
(t[t.length - 1 - o] || 1) > 1 && i === 1 && s.unshift(r);
}
return s;
}
function le(n, t) {
const e = [];
for (let s = 0; s < t.length; s++) {
const o = n[n.length - s - 1], r = t.length - s - 1, i = t[r];
(o == null || o === 1 && i > 1) && e.unshift(r);
}
return e;
}
function mt(n, t) {
const e = Math.max(n.length, t.length), s = new Array(e);
for (let o = 0; o < e; o++) {
let r = n[n.length - o - 1];
r == null && (r = 1);
let i = t[t.length - o - 1];
if (i == null && (i = 1), r === 1)
s[e - o - 1] = i;
else if (i === 1)
s[e - o - 1] = r;
else if (r !== i) {
const a = `Operands could not be broadcast together with shapes ${n} and ${t}.`;
throw Error(a);
} else
s[e - o - 1] = r;
}
return s;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function b$(n, t) {
let e = N(n, "a", "equal", "string_or_numeric"), s = N(t, "b", "equal", "string_or_numeric");
[e, s] = Jt(e, s), mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(Xa, o);
}
const _n = /* @__PURE__ */ O({ equal_: b$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function y$(n, t, e) {
const s = N(t, "a", "where"), o = N(e, "b", "where"), r = N(n, "condition", "where", "bool"), i = mt(mt(r.shape, s.shape), o.shape), a = ur(r, i), l = ur(s, i), c = ur(o, i), u = {
condition: a,
t: l,
e: c
};
return D.runKernel(kl, u);
}
const Re = /* @__PURE__ */ O({ where_: y$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function w$(n) {
const e = { x: N(n, "x", "zerosLike") };
return D.runKernel(Al, e);
}
const kt = /* @__PURE__ */ O({ zerosLike_: w$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function C$(n, t) {
let e = N(n, "a", "div"), s = N(t, "b", "div");
[e, s] = Jt(e, s);
const o = ut(e, s), r = kt(o), i = _n(s, r);
return Re(i, r, o);
}
const $$ = /* @__PURE__ */ O({ divNoNan_: C$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function I$(n, t) {
const e = N(n, "t1", "dot"), s = N(t, "t2", "dot");
I((e.rank === 1 || e.rank === 2) && (s.rank === 1 || s.rank === 2), () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ${e.rank} and ${s.rank}.`);
const o = e.rank === 1 ? e.size : e.shape[1], r = s.rank === 1 ? s.size : s.shape[0];
if (I(o === r, () => `Error in dot: inner dimensions of inputs must match, but got ${o} and ${r}.`), e.rank === 1 && s.rank === 1) {
const i = A(e, [1, -1]), a = A(s, [-1, 1]), l = Nt(i, a);
return A(l, []);
} else if (e.rank === 1 && s.rank === 2) {
const i = A(e, [1, -1]), a = A(s, [s.shape[0], s.shape[1]]), l = Nt(i, a);
return A(l, [l.size]);
} else if (e.rank === 2 && s.rank === 1) {
const i = A(s, [-1, 1]), a = Nt(e, i);
return A(a, [a.size]);
} else {
const i = A(s, [s.shape[0], s.shape[1]]);
return Nt(e, i);
}
}
const k$ = /* @__PURE__ */ O({ dot_: I$ });
/**
* @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.
* =============================================================================
*/
function v$(n, ...t) {
const e = t.map((o, r) => N(o, `tensors${r}`, "einsum")), s = { equation: n };
return D.runKernel(Uu, e, s);
}
const er = /* @__PURE__ */ O({ einsum_: v$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function S$(n) {
const e = { x: N(n, "x", "elu", "float32") };
return D.runKernel(zr, e);
}
const zl = /* @__PURE__ */ O({ elu_: S$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function N$(n) {
let t = N(n, "x", "erf");
I(t.dtype === "int32" || t.dtype === "float32", () => "Input dtype must be `int32` or `float32`."), t.dtype === "int32" && (t = st(t, "float32"));
const e = { x: t };
return D.runKernel(Br, e);
}
const Bm = /* @__PURE__ */ O({ erf_: N$ });
/**
* @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.
* =============================================================================
*/
function Ch(n, t) {
for (let e = 0; e < n.length; ++e)
if (n[n.length - e - 1] !== t - 1 - e)
return !1;
return !0;
}
function Vm(n, t, e) {
const s = n.length + t.length, o = [];
let r = 0, i = 0;
for (let a = 0; a < s; a++)
e.indexOf(a) === -1 ? o.push(n[r++]) : o.push(t[i++]);
return o;
}
function pe(n, t) {
const e = [], s = n.length;
for (let r = 0; r < s; r++)
t.indexOf(r) === -1 && e.push(n[r]);
const o = t.map((r) => n[r]);
return [e, o];
}
function ne(n, t) {
const e = t.map((s) => 1);
return Vm(n, e, t);
}
function be(n, t, e) {
I(Ch(t, e), () => `${n} supports only inner-most axes for now. Got axes ${t} and rank-${e} input.`);
}
function jt(n, t) {
if (Ch(n, t))
return null;
const e = [];
for (let s = 0; s < t; ++s)
n.indexOf(s) === -1 && e.push(s);
return n.forEach((s) => e.push(s)), e;
}
function $s(n) {
return n.map((t, e) => [e, t]).sort((t, e) => t[1] - e[1]).map((t) => t[0]);
}
function Zt(n, t) {
const e = [];
for (let s = t - n; s < t; ++s)
e.push(s);
return e;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function T$(n, t = null, e = !1) {
const o = { x: N(n, "x", "max") }, r = { reductionIndices: t, keepDims: e };
return D.runKernel(il, o, r);
}
const bn = /* @__PURE__ */ O({ max_: T$ });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function E$(n, t = null, e = !1) {
const o = { x: N(n, "x", "min") }, r = { axis: t, keepDims: e };
return D.runKernel(ul, o, r);
}
const ua = /* @__PURE__ */ O({ min_: E$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function R$(n, t) {
let e = N(n, "base", "pow"), s = N(t, "exp", "pow");
[e, s] = Jt(e, s);
const o = { a: e, b: s };
return D.runKernel(ni, o);
}
const Xs = /* @__PURE__ */ O({ pow_: R$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Tt(n, t) {
if ((rn(n) && t !== "string" || Array.isArray(n)) && t !== "complex64")
throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");
if (t === "string" && rn(n) && !(n instanceof Uint8Array))
throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");
return _l(n, [], [], t);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function D$(n) {
const e = { x: N(n, "x", "sqrt", "float32") };
return D.runKernel(fi, e);
}
const $e = /* @__PURE__ */ O({ sqrt_: D$ });
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function A$(n) {
const t = N(n, "x", "square"), e = {};
return D.runKernel("Square", { x: t }, e);
}
const Vt = /* @__PURE__ */ O({ square_: A$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function F$(n, t = null, e = !1) {
let s = N(n, "x", "sum");
s.dtype === "bool" && (s = st(s, "int32"));
const o = { x: s }, r = { axis: t, keepDims: e };
return D.runKernel(Sl, o, r);
}
const ct = /* @__PURE__ */ O({ sum_: F$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function O$(n, t = "euclidean", e = null, s = !1) {
n = N(n, "x", "norm");
const o = Wm(n, t, e);
let r = o.shape;
if (s) {
const i = wt(e, n.shape);
r = ne(o.shape, i);
}
return A(o, r);
}
function Wm(n, t, e = null) {
if (n.rank === 0)
return Ne(n);
if (n.rank !== 1 && e === null)
return Wm(A(n, [-1]), t, e);
if (n.rank === 1 || typeof e == "number" || Array.isArray(e) && e.length === 1) {
if (t === 1)
return ct(Ne(n), e);
if (t === 1 / 0)
return bn(Ne(n), e);
if (t === -1 / 0)
return ua(Ne(n), e);
if (t === "euclidean" || t === 2)
return $e(ct(Xs(Ne(n), Tt(2, "int32")), e));
throw new Error(`Error in norm: invalid ord value: ${t}`);
}
if (Array.isArray(e) && e.length === 2) {
if (t === 1)
return bn(ct(Ne(n), e[0]), e[1] - 1);
if (t === 1 / 0)
return bn(ct(Ne(n), e[1]), e[0]);
if (t === -1 / 0)
return ua(ct(Ne(n), e[1]), e[0]);
if (t === "fro" || t === "euclidean")
return $e(ct(Vt(n), e));
throw new Error(`Error in norm: invalid ord value: ${t}`);
}
throw new Error(`Error in norm: invalid axis: ${e}`);
}
const Bl = /* @__PURE__ */ O({ norm_: O$ });
/**
* @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.
* =============================================================================
*/
function _$(n, t = null, e = !1) {
return Bl(n, "euclidean", t, e);
}
const L$ = /* @__PURE__ */ O({ euclideanNorm_: _$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function M$(n) {
const e = { x: N(n, "x", "exp") };
return D.runKernel(Vr, e);
}
const Ln = /* @__PURE__ */ O({ exp_: M$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function P$(n, t = 0) {
const e = N(n, "x", "expandDims", "string_or_numeric");
I(t <= e.rank, () => "Axis must be <= rank of the tensor");
const s = { input: e }, o = { dim: t };
return D.runKernel(qa, s, o);
}
const Oe = /* @__PURE__ */ O({ expandDims_: P$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function z$(n) {
const e = { x: N(n, "x", "expm1") };
return D.runKernel(Wr, e);
}
const B$ = /* @__PURE__ */ O({ expm1_: z$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function V$(n, t) {
const e = N(n, "x", "tile", "string_or_numeric");
I(e.rank === t.length, () => `Error in transpose: rank of input ${e.rank} must match length of reps ${t}.`);
const s = { x: e }, o = { reps: t };
return D.runKernel(yi, s, o);
}
const gn = /* @__PURE__ */ O({ tile_: V$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function W$(n, t, e, s = "float32") {
t == null && (t = n);
const o = yt([n, t], s), r = n <= t ? n : t;
for (let a = 0; a < r; ++a)
o.set(1, a, a);
const i = A(o.toTensor(), [n, t]);
if (e == null)
return i;
if (e.length === 1)
return gn(Oe(i, 0), [e[0], 1, 1]);
if (e.length === 2)
return gn(Oe(Oe(i, 0), 0), [e[0], e[1], 1, 1]);
if (e.length === 3)
return gn(Oe(Oe(Oe(i, 0), 0), 0), [
e[0],
e[1],
e[2],
1,
1
]);
throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${e.length}D.`);
}
const Um = /* @__PURE__ */ O({ eye_: W$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function U$(n) {
const e = { x: N(n, "x", "floor", "float32") };
return D.runKernel(Ur, e);
}
const Vl = /* @__PURE__ */ O({ floor_: U$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function G$(n, t, e = 0, s = 0) {
const o = N(n, "x", "gather"), r = N(t, "indices", "gather", "int32"), i = { x: o, indices: r }, a = { axis: e, batchDims: s };
return D.runKernel(Ja, i, a);
}
const $h = /* @__PURE__ */ O({ gather_: G$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function H$(n, t) {
let e = N(n, "a", "greater", "string_or_numeric"), s = N(t, "b", "greater", "string_or_numeric");
[e, s] = Jt(e, s), mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(Za, o);
}
const Je = /* @__PURE__ */ O({ greater_: H$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function K$(n, t) {
let e = N(n, "a", "greaterEqual", "string_or_numeric"), s = N(t, "b", "greaterEqual", "string_or_numeric");
[e, s] = Jt(e, s), mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(Hr, o);
}
const oo = /* @__PURE__ */ O({ greaterEqual_: K$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function j$(n) {
const e = { input: N(n, "input", "imag") };
return D.runKernel(qu, e);
}
const Ih = /* @__PURE__ */ O({ imag_: j$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function X$(n) {
const e = { x: N(n, "x", "isFinite") };
return D.runKernel(jr, e);
}
const q$ = /* @__PURE__ */ O({ isFinite_: X$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Y$(n) {
const e = { x: N(n, "x", "isInf") };
return D.runKernel(Xr, e);
}
const J$ = /* @__PURE__ */ O({ isInf_: Y$ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Z$(n) {
const e = { x: N(n, "x", "isNaN") };
return D.runKernel(qr, e);
}
const Q$ = /* @__PURE__ */ O({ isNaN_: Z$ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function tI(n, t = 0.2) {
const s = { x: N(n, "x", "leakyRelu") }, o = { alpha: t };
return D.runKernel(Qa, s, o);
}
const kh = /* @__PURE__ */ O({ leakyRelu_: tI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function eI(n, t) {
let e = N(n, "a", "less", "string_or_numeric"), s = N(t, "b", "less", "string_or_numeric");
[e, s] = Jt(e, s), mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(tl, o);
}
const ha = /* @__PURE__ */ O({ less_: eI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nI(n, t) {
let e = N(n, "a", "lessEqual", "string_or_numeric"), s = N(t, "b", "lessEqual", "string_or_numeric");
[e, s] = Jt(e, s), mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(el, o);
}
const Vo = /* @__PURE__ */ O({ lessEqual_: nI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sI(n, t = 5, e = 1, s = 1, o = 0.5) {
const r = N(n, "x", "localResponseNormalization");
I(r.rank === 4 || r.rank === 3, () => `Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${r.rank}.`), I(vo(t), () => `Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);
let i = r, a = !1;
r.rank === 3 && (a = !0, i = A(r, [1, r.shape[0], r.shape[1], r.shape[2]]));
const l = { x: i }, c = { depthRadius: t, bias: e, alpha: s, beta: o }, u = D.runKernel(rl, l, c);
return a ? A(u, [u.shape[1], u.shape[2], u.shape[3]]) : u;
}
const oI = /* @__PURE__ */ O({ localResponseNormalization_: sI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function rI(n) {
const e = { x: N(n, "x", "log", "float32") };
return D.runKernel(Yr, e);
}
const Mn = /* @__PURE__ */ O({ log_: rI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function iI(n) {
const e = { x: N(n, "x", "log1p") };
return D.runKernel(Jr, e);
}
const Gm = /* @__PURE__ */ O({ log1p_: iI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function aI(n, t) {
I(Dc(n), () => "The f passed in variableGrads(f) must be a function"), I(t == null || Array.isArray(t) && t.every((c) => c instanceof ca), () => "The varList passed in variableGrads(f, varList) must be an array of variables");
const e = t != null;
if (!e) {
t = [];
for (const c in D.registeredVariables)
t.push(D.registeredVariables[c]);
}
const s = e ? t.filter((c) => !c.trainable) : null, o = t.length;
t = t.filter((c) => c.trainable), I(t.length > 0, () => `variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);
const r = !0, { value: i, grads: a } = D.gradients(n, t, null, r);
I(a.some((c) => c != 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()."), I(i.rank === 0, () => `The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);
const l = {};
return t.forEach((c, u) => {
a[u] != null && (l[c.name] = a[u]);
}), s?.forEach((c) => l[c.name] = null), { value: i, grads: l };
}
function Eo(n) {
return D.customGrad(n);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function lI(n) {
const e = { x: N(n, "x", "neg") };
return D.runKernel(dl, e);
}
const Yt = /* @__PURE__ */ O({ neg_: lI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function cI(n) {
const e = { x: N(n, "x", "softplus") };
return D.runKernel(pi, e);
}
const $i = /* @__PURE__ */ O({ softplus_: cI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function uI(n) {
const t = N(n, "x", "logSigmoid");
return Eo((s) => ({ value: Yt($i(Yt(s))), gradFunc: (i) => R(i, Bo(Yt(s))) }))(t);
}
const hI = /* @__PURE__ */ O({ logSigmoid_: uI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function dI(n, t) {
let e = N(n, "a", "sub"), s = N(t, "b", "sub");
[e, s] = Jt(e, s);
const o = { a: e, b: s };
return D.runKernel(gi, o);
}
const pt = /* @__PURE__ */ O({ sub_: dI });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function pI(n, t = -1) {
const e = N(n, "logits", "logSoftmax");
if (t === -1 && (t = e.rank - 1), t !== e.rank - 1)
throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and axis was ${t}`);
return Eo((o, r) => {
const a = bn(o, t, !0), l = pt(o, a), c = pt(st(l, "float32"), Mn(ct(Ln(l), t, !0)));
return r([c]), { value: c, gradFunc: (h, d) => {
const [p] = d, f = !0, m = Ln(p);
return pt(h, R(ct(h, t, f), m));
} };
})(e);
}
const Hm = /* @__PURE__ */ O({ logSoftmax_: pI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function fI(n, t = null, e = !1) {
const s = N(n, "x", "logSumExp"), o = wt(t, s.shape), r = bn(
s,
o,
!0
/* keepDims */
), i = pt(s, r), a = Ln(i), l = ct(a, o), c = Mn(l), u = Y(A(r, c.shape), c);
if (e) {
const h = ne(u.shape, o);
return A(u, h);
}
return u;
}
const Km = /* @__PURE__ */ O({ logSumExp_: fI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function mI(n, t) {
const e = N(n, "a", "logicalAnd", "bool"), s = N(t, "b", "logicalAnd", "bool");
mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(nl, o);
}
const jn = /* @__PURE__ */ O({ logicalAnd_: mI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function gI(n) {
const e = { x: N(n, "x", "logicalNot", "bool") };
return D.runKernel(sl, e);
}
const vh = /* @__PURE__ */ O({ logicalNot_: gI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function xI(n, t) {
const e = N(n, "a", "logicalOr", "bool"), s = N(t, "b", "logicalOr", "bool");
mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(ol, o);
}
const jm = /* @__PURE__ */ O({ logicalOr_: xI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function bI(n, t) {
const e = N(n, "a", "logicalXor", "bool"), s = N(t, "b", "logicalXor", "bool");
return mt(e.shape, s.shape), jn(jm(n, t), vh(jn(n, t)));
}
const yI = /* @__PURE__ */ O({ logicalXor_: bI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function wI(n, t, e, s, o) {
const r = N(n, "x", "maxPool"), i = 1;
let a = r, l = !1;
r.rank === 3 && (l = !0, a = A(r, [1, r.shape[0], r.shape[1], r.shape[2]])), I(a.rank === 4, () => `Error in maxPool: input must be rank 4 but got rank ${a.rank}.`), I(Ie(e, i), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`), ze("maxPool", s, o);
const c = { x: a }, u = { filterSize: t, strides: e, pad: s, dimRoundingMode: o }, h = D.runKernel(al, c, u);
return l ? A(h, [h.shape[1], h.shape[2], h.shape[3]]) : h;
}
const Sh = /* @__PURE__ */ O({ maxPool_: wI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function CI(n, t = [1, 1, 1], e, s, o, r = "NDHWC") {
const i = N(n, "x", "maxPool3d");
let a = i, l = !1;
i.rank === 4 && (l = !0, a = A(i, [1, i.shape[0], i.shape[1], i.shape[2], i.shape[3]])), I(a.rank === 5, () => `Error in maxPool3d: x must be rank 5 but got rank ${a.rank}.`), I(r === "NDHWC", () => `Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`), ze("maxPool3d", s, o);
const c = { x: a }, u = { filterSize: t, strides: e, pad: s, dimRoundingMode: o, dataFormat: r }, h = D.runKernel(ll, c, u);
return l ? A(h, [h.shape[1], h.shape[2], h.shape[3], h.shape[4]]) : h;
}
const $I = /* @__PURE__ */ O({ maxPool3d_: CI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function II(n, t) {
let e = N(n, "a", "maximum"), s = N(t, "b", "maximum");
[e, s] = Jt(e, s), e.dtype === "bool" && (e = st(e, "int32"), s = st(s, "int32")), mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(Zr, o);
}
const Is = /* @__PURE__ */ O({ maximum_: II });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kI(n, t = null, e = !1) {
const o = { x: N(n, "x", "mean") }, r = { axis: t, keepDims: e };
return D.runKernel(cl, o, r);
}
const ee = /* @__PURE__ */ O({ mean_: kI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function he(n, t = "float32") {
if (Jn(n), t === "complex64") {
const s = he(n, "float32"), o = he(n, "float32");
return No(s, o);
}
const e = Ce(G(n), t);
return D.makeTensor(e, n, t);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ks(n, t = "float32") {
if (Jn(n), t === "complex64") {
const s = ks(n, "float32"), o = he(n, "float32");
return No(s, o);
}
const e = Iu(G(n), t);
return D.makeTensor(e, n, t);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function vI(n, t) {
let e = N(n, "a", "minimum"), s = N(t, "b", "minimum");
[e, s] = Jt(e, s), e.dtype === "bool" && (e = st(e, "int32"), s = st(s, "int32")), mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(Qr, o);
}
const mr = /* @__PURE__ */ O({ minimum_: vI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function SI(n, t, e) {
I(e === "reflect" || e === "symmetric", () => `Invalid mode. Mode must be either reflect or symmetric. Got ${e}.`);
const s = N(n, "x", "mirrorPad");
if (s.rank === 0)
throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");
I(t.length === s.rank, () => `Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);
const o = e === "reflect" ? 1 : 0;
for (let a = 0; a < s.rank; a++)
I(t[a].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), I(t[a][0] >= 0 && t[a][0] <= s.shape[a] - o && t[a][1] >= 0 && t[a][1] <= s.shape[a] - o, () => `Padding in dimension ${a} cannot be greater than or equal to ${s.shape[a] - o} or less than 0 for input of shape ${s.shape}`);
const r = { paddings: t, mode: e }, i = { x: s };
return D.runKernel(hl, i, r);
}
const NI = /* @__PURE__ */ O({ mirrorPad_: SI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function TI(n, t) {
let e = N(n, "a", "mod"), s = N(t, "b", "mod");
[e, s] = Jt(e, s);
const o = { a: e, b: s };
return D.runKernel(ti, o);
}
const EI = /* @__PURE__ */ O({ mod_: TI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function RI(n, t = null, e = !1) {
n = N(n, "x", "moments");
const s = wt(t, n.shape), o = ee(n, s, e);
let r = o.shape;
e || (r = ne(o.shape, s));
const i = Vt(pt(st(n, "float32"), A(o, r))), a = ee(i, s, e);
return { mean: o, variance: a };
}
const Nh = /* @__PURE__ */ O({ moments_: RI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function DI(n, t) {
let e = N(n, "a", "notEqual", "string_or_numeric"), s = N(t, "b", "notEqual", "string_or_numeric");
[e, s] = Jt(e, s), mt(e.shape, s.shape);
const o = { a: e, b: s };
return D.runKernel(pl, o);
}
const da = /* @__PURE__ */ O({ notEqual_: DI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function AI(n, t, e = 1, s = 0, o = "int32") {
if (t < 2)
throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);
const i = { indices: N(n, "indices", "oneHot", "int32") }, a = { dtype: o, depth: t, onValue: e, offValue: s };
return D.runKernel(ml, i, a);
}
const Xm = /* @__PURE__ */ O({ oneHot_: AI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function FI(n) {
const e = { x: N(n, "x", "onesLike") };
return D.runKernel(fl, e);
}
const an = /* @__PURE__ */ O({ onesLike_: FI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function OI(n, t, e = 0) {
const s = N(n, "x", "pad");
if (s.rank === 0)
throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
const o = { paddings: t, constantValue: e }, r = { x: s };
return D.runKernel(xl, r, o);
}
const Th = /* @__PURE__ */ O({ pad_: OI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _I(n, t, e) {
const s = N(n, "x", "spaceToBatchND");
I(s.rank >= 1 + t.length, () => `input rank ${s.rank} should be > than [blockShape] ${t.length}`), I(e.length === t.length, () => `paddings.shape[0] ${e.length} must be equal to [blockShape] ${t.length}`), I(s.shape.reduce((i, a, l) => l > 0 && l <= t.length ? i && (a + e[l - 1][0] + e[l - 1][1]) % t[l - 1] === 0 : i, !0), () => `input spatial dimensions ${s.shape.slice(1)} with paddings ${e.toString()} must be divisible by blockShapes ${t.toString()}`);
const o = { x: s }, r = { blockShape: t, paddings: e };
return D.runKernel(Nl, o, r);
}
const Eh = /* @__PURE__ */ O({ spaceToBatchND_: _I });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function LI(n, t, e, s, o, r, i) {
o == null && (o = [1, 1]), r == null && (r = 1), s === 0 && (s = "valid");
const a = N(n, "x", "maxPool");
let l = a, c = !1;
a.rank === 3 && (c = !0, l = A(a, [1, a.shape[0], a.shape[1], a.shape[2]])), I(Ie(r, o), () => `Error in pool: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'`);
const u = ln(l.shape, t, r, o, s), h = [u.dilationHeight, u.dilationWidth];
let d;
s === "same" ? d = PI([u.filterHeight, u.filterWidth], h) : d = [[0, 0], [0, 0]];
const p = h[0] === 1 && h[1] === 1, [f, m] = MI([u.inHeight, u.inWidth], h, d), g = p ? s : "valid", x = p ? l : Eh(l, h, f), w = (e === "avg" ? () => gh(x, t, r, g, i) : () => Sh(x, t, r, g, i))(), y = p ? w : xh(w, h, m);
return c ? A(y, [y.shape[1], y.shape[2], y.shape[3]]) : y;
}
function MI(n, t, e) {
const s = e.map((u) => u[0]), o = e.map((u) => u[1]), r = n.concat(s, o), i = t.map((u, h) => (u - r[h] % u) % u), a = o.map((u, h) => u + i[h]), l = t.map((u, h) => [s[h], a[h]]), c = t.map((u, h) => [0, i[h]]);
return [l, c];
}
function PI(n, t) {
const s = n.map((i, a) => i + (i - 1) * (t[a] - 1)).map((i) => i - 1), o = s.map((i) => Math.floor(i / 2)), r = s.map((i, a) => i - o[a]);
return s.map((i, a) => [o[a], r[a]]);
}
const zI = /* @__PURE__ */ O({ pool_: LI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function BI(n, t) {
const e = N(n, "x", "prelu"), s = N(t, "alpha", "prelu"), o = { x: e, alpha: s };
return D.runKernel(bl, o);
}
const Rh = /* @__PURE__ */ O({ prelu_: BI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function VI(n, t = null, e = !1) {
let s = N(n, "x", "prod");
s.dtype === "bool" && (s = st(s, "int32"));
const o = { x: s }, r = { axis: t, keepDims: e };
return D.runKernel(yl, o, r);
}
const WI = /* @__PURE__ */ O({ prod_: VI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class qm {
constructor(t, e, s, o, r) {
this.mean = t, this.stdDev = e, this.dtype = s, this.nextVal = NaN, this.truncated = o, this.truncated && (this.upper = this.mean + this.stdDev * 2, this.lower = this.mean - this.stdDev * 2);
const i = r || Math.random();
this.random = yu.alea(i.toString());
}
/** Returns next sample from a Gaussian distribution. */
nextValue() {
if (!isNaN(this.nextVal)) {
const o = this.nextVal;
return this.nextVal = NaN, o;
}
let t, e, s = !1;
for (; !s; ) {
let o, r, i;
do
o = 2 * this.random() - 1, r = 2 * this.random() - 1, i = o * o + r * r;
while (i >= 1 || i === 0);
const a = Math.sqrt(-2 * Math.log(i) / i);
t = this.mean + this.stdDev * o * a, e = this.mean + this.stdDev * r * a, (!this.truncated || this.isValidTruncated(t)) && (s = !0);
}
return (!this.truncated || this.isValidTruncated(e)) && (this.nextVal = this.convertValue(e)), this.convertValue(t);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(t) {
return this.dtype == null || this.dtype === "float32" ? t : Math.round(t);
}
/** Returns true if less than 2-standard-deviations from the mean. */
isValidTruncated(t) {
return t <= this.upper && t >= this.lower;
}
}
class UI {
constructor(t = 0, e = 1, s, o) {
if (this.canReturnFloat = () => this.dtype == null || this.dtype === "float32", this.min = t, this.range = e - t, this.dtype = s, o == null && (o = Math.random()), typeof o == "number" && (o = o.toString()), !this.canReturnFloat() && this.range <= 1)
throw new Error(`The difference between ${t} - ${e} <= 1 and dtype is not float`);
this.random = yu.alea(o);
}
convertValue(t) {
return this.canReturnFloat() ? t : Math.round(t);
}
nextValue() {
return this.convertValue(this.min + this.range * this.random());
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function GI(n, t = 0, e = 1, s, o) {
if (Jn(n), s != null && s === "bool")
throw new Error(`Unsupported data type ${s}`);
const r = new qm(t, e, s, !1, o), i = yt(n, s);
for (let a = 0; a < i.values.length; a++)
i.values[a] = r.nextValue();
return i.toTensor();
}
const HI = /* @__PURE__ */ O({ randomNormal_: GI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function KI(n, t = 0, e = 1, s = "float32", o) {
Jn(n);
const r = yt(n, s), i = new UI(t, e, null, o);
for (let a = 0; a < r.values.length; a++)
r.values[a] = i.nextValue();
return r.toTensor();
}
const Ii = /* @__PURE__ */ O({ randomUniform_: KI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function gr(n, t, e = 1, s = "float32") {
if (e === 0)
throw new Error("Cannot have a step of zero");
const o = { start: n, stop: t, step: e, dtype: s };
return D.runKernel(nh, {}, o);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function jI(n) {
const e = { input: N(n, "input", "real") };
return D.runKernel(sh, e);
}
const pa = /* @__PURE__ */ O({ real_: jI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function XI(n) {
const e = { x: N(n, "x", "reciprocal") };
return D.runKernel(si, e);
}
const qI = /* @__PURE__ */ O({ reciprocal_: XI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function YI(n) {
const e = { x: N(n, "x", "relu") };
return D.runKernel(oi, e);
}
const ro = /* @__PURE__ */ O({ relu_: YI });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function JI(n) {
const e = { x: N(n, "x", "relu6") };
return D.runKernel(ri, e);
}
const Ym = /* @__PURE__ */ O({ relu6_: JI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ZI(n, t) {
const s = { x: N(n, "x", "reverse") }, o = { dims: t };
return D.runKernel(Il, s, o);
}
const qs = /* @__PURE__ */ O({ reverse_: ZI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function QI(n) {
const e = { x: N(n, "x", "round") };
return D.runKernel(ii, e);
}
const Jm = /* @__PURE__ */ O({ round_: QI });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function tk(n) {
const e = { x: N(n, "x", "rsqrt", "float32") };
return D.runKernel(ai, e);
}
const Zm = /* @__PURE__ */ O({ rsqrt_: tk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ek(n) {
const e = { x: N(n, "x", "selu") };
return D.runKernel(li, e);
}
const Qm = /* @__PURE__ */ O({ selu_: ek });
function nk(n, t, e, s, o, r = [1, 1], i = "NHWC") {
const a = N(n, "x", "separableConv2d"), l = N(t, "depthwiseFilter", "separableConv2d"), c = N(e, "pointwiseFilter", "separableConv2d");
let u = a, h = !1;
if (a.rank === 3 && (h = !0, u = A(a, [1, a.shape[0], a.shape[1], a.shape[2]])), i === "NCHW")
throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");
I(u.rank === 4, () => `Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`), I(l.rank === 4, () => `Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`), I(c.rank === 4, () => `Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`), I(c.shape[0] === 1, () => `Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`), I(c.shape[1] === 1, () => `Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);
const d = l.shape[2], p = l.shape[3];
I(c.shape[2] === d * p, () => `Error in separableConv2d: the third dimension of pointwise filter must be ${d * p}, but got ${c.shape[2]}.`);
const f = wh(u, l, s, o, i, r), g = js(f, c, 1, "valid", i);
return h ? A(g, [g.shape[1], g.shape[2], g.shape[3]]) : g;
}
const tg = /* @__PURE__ */ O({ separableConv2d_: nk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sk(n) {
const e = { x: N(n, "x", "sign") };
return D.runKernel(hi, e);
}
const ok = /* @__PURE__ */ O({ sign_: sk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function rk(n) {
const e = { x: N(n, "x", "sin", "float32") };
return D.runKernel(ci, e);
}
const eg = /* @__PURE__ */ O({ sin_: rk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ik(n) {
const e = { x: N(n, "x", "sinh") };
return D.runKernel(ui, e);
}
const ng = /* @__PURE__ */ O({ sinh_: ik });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ak(n, t, e) {
const s = N(n, "x", "slice1d");
return I(s.rank === 1, () => `slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`), zt(s, [t], [e]);
}
const Dh = /* @__PURE__ */ O({ slice1d_: ak });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function lk(n, t, e) {
const s = N(n, "x", "slice2d");
return I(s.rank === 2, () => `slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`), zt(s, t, e);
}
const sg = /* @__PURE__ */ O({ slice2d_: lk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ck(n, t, e) {
const s = N(n, "x", "slice3d");
return I(s.rank === 3, () => `slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`), zt(s, t, e);
}
const Ah = /* @__PURE__ */ O({ slice3d_: ck });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function uk(n, t, e) {
const s = N(n, "x", "slice4d");
return I(s.rank === 4, () => `slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`), zt(s, t, e);
}
const fa = /* @__PURE__ */ O({ slice4d_: uk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function hk(n, t = -1) {
const e = N(n, "logits", "softmax", "float32");
if (t === -1 && (t = e.rank - 1), t !== e.rank - 1)
throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and dim was ${t}`);
const s = { logits: e }, o = { dim: t };
return D.runKernel(El, s, o);
}
const Fh = /* @__PURE__ */ O({ softmax_: hk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function dk(n) {
I(n.dtype === "complex64", () => `The dtype for tf.spectral.fft() must be complex64 but got ${n.dtype}.`);
const t = { input: n };
return D.runKernel(Hu, t);
}
const og = /* @__PURE__ */ O({ fft_: dk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function pk(n) {
I(n.dtype === "complex64", () => `The dtype for tf.spectral.ifft() must be complex64 but got ${n.dtype}.`);
const t = { input: n };
return D.runKernel(Xu, t);
}
const Xc = /* @__PURE__ */ O({ ifft_: pk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function fk(n) {
const t = n.shape[n.shape.length - 1], e = n.size / t;
let s;
if (t <= 2) {
const o = A(n, [e, t]);
s = Xc(o);
} else {
const o = [e, 2 * (t - 1)], r = A(pa(n), [e, t]), i = A(Ih(n), [e, t]), a = qs(zt(r, [0, 1], [e, t - 2]), 1), l = R(qs(zt(i, [0, 1], [e, t - 2]), 1), Tt(-1)), c = Le([r, a], 1), u = Le([i, l], 1), h = A(No(c, u), [o[0], o[1]]);
s = Xc(h);
}
if (s = pa(s), n.rank === 3 && n.shape[0] !== 0) {
const o = s, r = n.shape[0];
s = A(s, [r, s.shape[0] / r, s.shape[1]]), o.dispose();
}
return s;
}
const mk = /* @__PURE__ */ O({ irfft_: fk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function gk(n, t, e = 0) {
const o = { x: N(n, "x", "split") }, r = { numOrSizeSplits: t, axis: e };
return D.runKernel(Tl, o, r);
}
const qe = /* @__PURE__ */ O({ split_: gk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function xk(n, t) {
I(n.dtype === "float32", () => `The dtype for rfft() must be real value but got ${n.dtype}`);
let e = n.shape[n.shape.length - 1];
const s = n.size / e;
let o;
if (t != null && t < e) {
const f = n.shape.map((g) => 0), m = n.shape.map((g) => g);
m[n.shape.length - 1] = t, o = zt(n, f, m), e = t;
} else if (t != null && t > e) {
const f = n.shape.map((m) => m);
f[n.shape.length - 1] = t - e, o = Le([n, he(f)], n.shape.length - 1), e = t;
} else
o = n;
const r = kt(o), i = A(No(o, r), [s, e]), a = og(i), l = Math.floor(e / 2) + 1, c = pa(a), u = Ih(a), h = qe(c, [l, e - l], c.shape.length - 1), d = qe(u, [l, e - l], u.shape.length - 1), p = o.shape.slice();
return p[o.shape.length - 1] = l, A(No(h[0], d[0]), p);
}
const bk = /* @__PURE__ */ O({ rfft_: xk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yk(n, t) {
let e = N(n, "a", "squaredDifference"), s = N(t, "b", "squaredDifference");
[e, s] = Jt(e, s), mt(e.shape, s.shape);
const o = { a: e, b: s }, r = {};
return D.runKernel(mi, o, r);
}
const wk = /* @__PURE__ */ O({ squaredDifference_: yk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ck(n, t) {
const e = N(n, "x", "squeeze", "string_or_numeric");
return A(e, ys(e.shape, t).newShape);
}
const ki = /* @__PURE__ */ O({ squeeze_: Ck });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function $k(n, t = 0) {
const e = Im(n, "tensors", "stack", "string_or_numeric");
I(e.length >= 1, () => "Pass at least one tensor to tf.stack"), e.length > 0 && I(t <= e[0].rank, () => "Axis must be <= rank of the tensor");
const s = e, o = { axis: t };
return D.runKernel(gl, s, o);
}
const Xn = /* @__PURE__ */ O({ stack_: $k });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ik(n, t = 0) {
const s = { x: N(n, "x", "step") }, o = { alpha: t };
return D.runKernel(wi, s, o);
}
const vi = /* @__PURE__ */ O({ step_: Ik });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kk(n, t, e, s, o = 0, r = 0, i = 0, a = 0, l = 0) {
const u = { x: N(n, "x", "stridedSlice", "string_or_numeric") }, h = {
begin: t,
end: e,
strides: s,
beginMask: o,
endMask: r,
ellipsisMask: i,
newAxisMask: a,
shrinkAxisMask: l
};
return D.runKernel(lh, u, h);
}
const vk = /* @__PURE__ */ O({ stridedSlice_: kk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Sk(n) {
const e = { x: N(n, "x", "tan", "float32") };
return D.runKernel(xi, e);
}
const Nk = /* @__PURE__ */ O({ tan_: Sk });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function We(n, t) {
_f(n);
const e = Ol(n, t);
if (e.length !== 1)
throw new Error("tensor1d() requires values to be a flat/TypedArray");
return _l(n, null, e, t);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function mc(n, t, e) {
if (_f(n), t != null && t.length !== 2)
throw new Error("tensor2d() requires shape to have two numbers");
const s = Ol(n, e);
if (s.length !== 2 && s.length !== 1)
throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");
if (s.length === 1 && t == null)
throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");
return _l(n, t, s, e);
}
function rg(n, t, e) {
const s = t.rank > 1 ? t.shape[t.rank - 1] : 1, o = t.rank > 1 ? t.rank - 1 : 1, r = `Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${e.shape}, indices.shape: ${t.shape}, shape: ${n}, sliceDim: ${s}, and batchDim: ${o}.`;
if (e.rank < o)
throw new Error(r + ` update.rank < ${o}. `);
if (n.length < s + (e.rank - o))
throw new Error(r + ` Output shape length < ${s + (e.rank - o)}`);
if (e.rank !== o + n.length - s)
throw new Error(r + ` update.rank != ${o + n.length - s}`);
for (let i = 0; i < o; ++i)
if (e.shape[i] !== t.shape[i])
throw new Error(r + ` updates.shape[${i}] (${e.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);
for (let i = 0; i < e.rank - o; ++i)
if (e.shape[i + o] !== n[i + s])
throw new Error(r + ` updates.shape[${i + o}] (${e.shape[i + o]}) != shape[${i + o}] (${n[i + o]})`);
}
function Tk(n, t, e) {
if (t.rank < 1)
throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);
if (n.rank < 1)
throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${n.rank}.`);
if (t.dtype !== "int32")
throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);
if (e.length < 1)
throw new Error(`Output rank must be greater or equal to 1, but got shape: ${e}`);
if (e.length === 0) {
if (t.size === 0)
throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);
if (n.size === 0)
throw new Error(`Updates specified for empty output. updates shape: ${n.shape}`);
}
rg(e, t, n);
}
function io(n, t, e) {
const s = t.shape.length, o = s > 1 ? t.shape[s - 1] : 1, r = e.length;
let i = 1;
for (let h = o; h < r; ++h)
i *= e[h];
const a = o < 1 ? 1 : o, l = G(t.shape) / a, c = [...lt(e.slice(0, o)), 1], u = G(e);
return { sliceRank: o, numUpdates: l, sliceSize: i, strides: c, outputSize: u };
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ek(n, t = 1, e = !0) {
const s = N(n, "x", "topk");
if (s.rank === 0)
throw new Error("topk() expects the input to be of rank 1 or higher");
const o = s.shape[s.shape.length - 1];
if (t < 0)
throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);
if (t > o)
throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${t}`);
const r = { x: s }, i = { k: t, sorted: e }, [a, l] = D.runKernel(ch, r, i);
return { values: a, indices: l };
}
const Rk = /* @__PURE__ */ O({ topk_: Ek });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Dk(n, t = 0, e = 1, s, o) {
if (Jn(n), s != null && s === "bool")
throw new Error("Unsupported data type $ { dtype }");
const r = new qm(t, e, s, !0, o), i = yt(n, s);
for (let a = 0; a < i.values.length; a++)
i.values[a] = r.nextValue();
return i.toTensor();
}
const ig = /* @__PURE__ */ O({ truncatedNormal_: Dk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ak(n, t = 0) {
const e = N(n, "x", "unique", "string_or_numeric");
I(e.rank > 0, () => "The input tensor must be at least 1D");
const s = { x: e }, o = { axis: t }, [r, i] = D.runKernel(hh, s, o);
return { values: r, indices: i };
}
const Fk = /* @__PURE__ */ O({ unique_: Ak });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ok(n, t, e) {
const s = N(n, "x", "unsortedSegmentSum"), o = N(t, "segmentIds", "unsortedSegmentSum", "int32");
I(vo(e), () => "numSegments must be of dtype int");
const r = { x: s, segmentIds: o }, i = { numSegments: e };
return D.runKernel(Dl, r, i);
}
const ag = /* @__PURE__ */ O({ unsortedSegmentSum_: Ok });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _k(n, t = 0) {
const e = N(n, "x", "unstack", "string_or_numeric");
I(t >= -e.shape.length && t < e.shape.length, () => `Axis = ${t} is not in [-${e.shape.length}, ${e.shape.length})`);
const s = { value: e }, o = { axis: t };
return D.runKernel(Rl, s, o);
}
const Ys = /* @__PURE__ */ O({ unstack_: _k });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Lk(n, t = !0, e, s) {
return D.makeVariable(n, t, e, s);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function lg(n, t) {
const e = [];
for (let r = 0; r < t.length; r++)
t[r] && e.push(r);
const s = yt(n, "int32"), o = yt([e.length, n.length], "int32");
for (let r = 0; r < e.length; r++) {
const i = s.indexToLoc(e[r]), a = r * n.length;
o.values.set(i, a);
}
return o.toTensor();
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Mk(n, t, e) {
const s = N(n, "x", "transpose");
if (t == null && (t = s.shape.map((i, a) => a).reverse()), I(s.rank === t.length, () => `Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`), t.forEach((i) => {
I(i >= 0 && i < s.rank, () => `All entries in 'perm' must be between 0 and ${s.rank - 1} but got ${t}`);
}), s.rank <= 1)
return s.clone();
const o = { x: s }, r = { perm: t };
return s.dtype === "complex64" ? _(() => {
let i = pa(s), a = Ih(s);
return i = D.runKernel(Co, { x: i }, r), a = D.runKernel(Co, { x: a }, r), e && (a = Yt(a)), No(i, a);
}) : D.runKernel(Co, o, r);
}
const It = /* @__PURE__ */ O({ transpose_: Mk });
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Pk(n, t) {
if (t == null)
return n.shape.slice();
if (Et(n.shape, t))
return t;
if (n.shape.length === t.length) {
const e = [];
for (let s = 0; s < n.shape.length; s++)
t[s] == null && n.shape[s] != null ? e.push(n.shape[s]) : e.push(t[s]);
return e;
}
return t;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function zk(n, t, e, s) {
const o = N(n, "x", "dropout");
if (I(o.dtype === "float32", () => `x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`), I(t >= 0 && t < 1, () => `rate must be a float in the range [0, 1), but got ${t}.`), t === 0)
return n instanceof se ? o.clone() : o;
const r = Pk(o, e), i = 1 - t, a = ut(Vl(Y(Ii(r, 0, 1, "float32", s), i)), i);
return R(o, a);
}
const Bk = /* @__PURE__ */ O({ dropout_: zk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Vk(n, t, e, s, o, r = "NHWC", i) {
let a = n;
n.rank === 3 && (a = A(n, [1, n.shape[0], n.shape[1], n.shape[2]]));
let l = t;
l.rank === 3 && (l = A(t, [1, t.shape[0], t.shape[1], t.shape[2]])), I(a.rank === 4, () => `Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`), I(l.rank === 4, () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`), I(e.length === 4, () => `Error in conv2dDerFilter: filterShape must be length 4, but got ${e}.`);
const c = r === "NHWC" ? a.shape[3] : a.shape[1], u = r === "NHWC" ? l.shape[3] : l.shape[1];
I(c === e[2], () => `Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${e[2]}.`), I(u === e[3], () => `Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${e[3]}).`), ze("conv2dDerFilter", o, i);
const h = { x: a, dy: l }, d = { strides: s, pad: o, dataFormat: r, dimRoundingMode: i, filterShape: e };
return D.runKernel(Ou, h, d);
}
const Oh = /* @__PURE__ */ O({ conv2DBackpropFilter_: Vk });
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _h(n, t, e) {
if (e == null || e === "linear")
return n;
if (e === "relu")
return R(n, vi(t));
throw new Error(`Cannot compute gradient for fused activation ${e}.`);
}
function Lh(n, t) {
let e = t;
const s = le(n.shape, t.shape);
return s.length > 0 && (e = ct(e, s)), A(e, n.shape);
}
function Mh(n, t, e, s) {
if (t === "linear")
return n;
if (t === "relu")
return ro(n);
if (t === "elu")
return zl(n);
if (t === "relu6")
return Ym(n);
if (t === "prelu")
return Rh(n, e);
if (t === "leakyrelu")
return kh(n, s);
if (t === "sigmoid")
return Bo(n);
throw new Error(`Unknown fused activation ${t}.`);
}
const Ph = (n, t) => !(n > 0) || t === "linear";
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Wk({ x: n, filter: t, strides: e, pad: s, dataFormat: o = "NHWC", dilations: r = [1, 1], dimRoundingMode: i, bias: a, activation: l = "linear", preluActivationWeights: c, leakyreluAlpha: u }) {
if (l = l || "linear", Ph(D.state.gradientDepth, l) === !1) {
I(o === "NHWC", () => `Error in fused conv2d: got dataFormat of ${o} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);
let $ = js(n, t, e, s, o, r, i);
return a != null && ($ = Y($, a)), Mh($, l, c, u);
}
const h = N(n, "x", "conv2d", "float32"), d = N(t, "filter", "conv2d", "float32");
let p = h, f = !1;
h.rank === 3 && (f = !0, p = A(h, [1, h.shape[0], h.shape[1], h.shape[2]])), I(p.rank === 4, () => `Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`), I(d.rank === 4, () => `Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`), ze("fused conv2d", s, i);
const m = o === "NHWC" ? p.shape[3] : p.shape[1];
I(d.shape[2] === m, () => `Error in conv2d: depth of input (${m}) must match input depth for filter ${d.shape[2]}.`), I(Ie(e, r), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`);
const g = xe(p.shape, d.shape, e, r, s, i);
let x;
a != null && (x = N(a, "bias", "fused conv2d"), [x] = Jt(x, h), o === "NHWC" ? mt(g.outShape, x.shape) : (I(x.shape.length <= 1, () => `Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${x.shape.length}.`), I(x.shape.length === 0 || x.shape[0] === g.outChannels || x.shape[0] === 1, () => `Error in fused conv2d: bias shape (${x.shape}) is not compatible with the number of output channels (${g.outChannels})`)));
let b;
if (c != null) {
const $ = c.shape;
if (I($.length <= 1 || $.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-${$.length}.`), $.length === 1)
I($[0] === 1 || $[0] === g.outChannels, () => `Error in fused conv2d: PReLU activation weights (${$}) is not compatible with the number of output channels (${g.outChannels}).`);
else if ($.length === 3)
try {
mt($, g.outShape);
} catch {
const v = `Error in fused conv2d: PReLU activation weights (${$}) is not compatible with the output shape of the conv2d (${g.outShape}).`;
throw Error(v);
}
b = N(c, "prelu weights", "fused conv2d");
}
const w = ($, k) => {
I(o === "NHWC", () => `Error in gradient of fused conv2D: got dataFormat of ${o} but only NHWC is currently supported.`);
const [v, S, T, F] = k, L = _h($, T, l);
I(Hs(r), () => `Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);
const M = bh(S.shape, L, v, e, s), B = Oh(S, L, v.shape, e, s), z = [M, B];
if (F != null) {
const V = Lh(F, L);
z.push(V);
}
return z;
}, y = {
x: p,
filter: d,
bias: x,
preluActivationWeights: b
}, C = {
strides: e,
pad: s,
dataFormat: o,
dilations: r,
dimRoundingMode: i,
activation: l,
leakyreluAlpha: u
};
return a == null ? Eo((k, v, S) => {
let T = (
// tslint:disable-next-line: no-unnecessary-type-assertion
D.runKernel(aa, y, C)
);
return S([v, k, T]), f && (T = A(T, [T.shape[1], T.shape[2], T.shape[3]])), { value: T, gradFunc: w };
})(p, d) : Eo((k, v, S, T) => {
let F = D.runKernel(aa, y, C);
return T([v, k, F, S]), f && (F = A(F, [F.shape[1], F.shape[2], F.shape[3]])), { value: F, gradFunc: w };
})(p, d, x);
}
const Uk = /* @__PURE__ */ O({ fusedConv2d_: Wk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Gk(n, t, e, s, o, r = [1, 1], i) {
let a = n;
n.rank === 3 && (a = A(n, [1, n.shape[0], n.shape[1], n.shape[2]]));
let l = t;
l.rank === 3 && (l = A(t, [1, t.shape[0], t.shape[1], t.shape[2]]));
const c = { x: a, dy: l }, u = { strides: s, pad: o, dimRoundingMode: i, dilations: r, filterShape: e };
return D.runKernel(Vu, c, u);
}
const Hk = O({ depthwiseConv2dNativeBackpropFilter_: Gk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Kk(n, t, e, s, o, r = [1, 1], i) {
let a = t, l = !1;
t.rank === 3 && (l = !0, a = A(t, [1, t.shape[0], t.shape[1], t.shape[2]]));
const c = { dy: a, filter: e }, u = { strides: s, pad: o, dimRoundingMode: i, dilations: r, inputShape: n }, h = (
// tslint:disable-next-line: no-unnecessary-type-assertion
D.runKernel(Wu, c, u)
);
return l ? A(h, [h.shape[1], h.shape[2], h.shape[3]]) : h;
}
const jk = O({ depthwiseConv2dNativeBackpropInput_: Kk });
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Xk({ a: n, b: t, transposeA: e = !1, transposeB: s = !1, bias: o, activation: r = "linear", preluActivationWeights: i, leakyreluAlpha: a = 0.2 }) {
if (Ph(D.state.gradientDepth, r) === !1) {
let F = Nt(n, t, e, s);
return o != null && (F = Y(F, o)), Mh(F, r, i, a);
}
let l = N(n, "a", "fused matMul"), c = N(t, "b", "fused matMul");
[l, c] = Jt(l, c);
const u = e ? l.shape[l.rank - 2] : l.shape[l.rank - 1], h = s ? c.shape[c.rank - 1] : c.shape[c.rank - 2], d = e ? l.shape[l.rank - 1] : l.shape[l.rank - 2], p = s ? c.shape[c.rank - 2] : c.shape[c.rank - 1], f = l.shape.slice(0, -2), m = c.shape.slice(0, -2), g = G(f), x = G(m);
I(u === h, () => `Error in fused matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${e} and transposeB=${s} must match.`);
const w = mt(l.shape.slice(0, -2), c.shape.slice(0, -2)).concat([d, p]), y = e ? A(l, [g, u, d]) : A(l, [g, d, u]), C = s ? A(c, [x, p, h]) : A(c, [x, h, p]);
let $;
o != null && ($ = N(o, "bias", "fused matMul"), [$] = Jt($, l), mt(w, $.shape));
let k;
i != null && (k = N(i, "prelu weights", "fused matMul"));
const v = (F, L) => {
const [M, B, z, V] = L, H = _h(A(F, z.shape), z, r);
let U, K;
if (!e && !s ? (U = Nt(H, B, !1, !0), K = Nt(M, H, !0, !1)) : !e && s ? (U = Nt(H, B, !1, !1), K = Nt(H, M, !0, !1)) : e && !s ? (U = Nt(B, H, !1, !0), K = Nt(M, H, !1, !1)) : (U = Nt(B, H, !0, !0), K = Nt(H, M, !0, !0)), o != null) {
const X = Lh(V, H);
return [U, K, X];
} else
return [U, K];
}, S = {
a: y,
b: C,
bias: $,
preluActivationWeights: k
}, T = { transposeA: e, transposeB: s, activation: r, leakyreluAlpha: a };
return o == null ? Eo((L, M, B) => {
const z = (
// tslint:disable-next-line: no-unnecessary-type-assertion
D.runKernel(ia, S, T)
);
return B([L, M, z]), { value: A(z, w), gradFunc: v };
})(y, C) : Eo((L, M, B, z) => {
const V = (
// tslint:disable-next-line: no-unnecessary-type-assertion
D.runKernel(ia, S, T)
);
return z([L, M, V, B]), { value: A(V, w), gradFunc: v };
})(y, C, $);
}
const gp = /* @__PURE__ */ O({ fusedMatMul_: Xk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function qk(n, t, e, s, o = "bilinear", r = 0) {
const i = N(n, "image", "cropAndResize"), a = N(t, "boxes", "cropAndResize", "float32"), l = N(e, "boxInd", "cropAndResize", "int32"), c = a.shape[0];
I(i.rank === 4, () => `Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`), I(a.rank === 2 && a.shape[1] === 4, () => `Error in cropAndResize: boxes must be have size [${c},4] but had shape ${a.shape}.`), I(l.rank === 1 && l.shape[0] === c, () => `Error in cropAndResize: boxInd must be have size [${c}] but had shape ${a.shape}.`), I(s.length === 2, () => `Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`), I(s[0] >= 1 && s[1] >= 1, () => `cropSize must be atleast [1,1], but was ${s}`), I(o === "bilinear" || o === "nearest", () => `method must be bilinear or nearest, but was ${o}`);
const u = { image: i, boxes: a, boxInd: l }, h = { method: o, extrapolationValue: r, cropSize: s };
return D.runKernel(Pu, u, h);
}
const Yk = /* @__PURE__ */ O({ cropAndResize_: qk });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Jk(n) {
const t = N(n, "image", "flipLeftRight", "float32");
I(t.rank === 4, () => `Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);
const e = { image: t };
return D.runKernel(ju, e, {});
}
const Zk = /* @__PURE__ */ O({ flipLeftRight_: Jk });
/**
* @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.
* =============================================================================
*/
function Qk(n) {
const t = N(n, "image", "grayscaleToRGB"), e = t.rank - 1, s = t.shape[e];
I(t.rank >= 2, () => `Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`), I(s === 1, () => `Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);
const o = new Array(t.rank);
return o.fill(1, 0, e), o[e] = 3, gn(t, o);
}
const tv = /* @__PURE__ */ O({ grayscaleToRGB_: Qk });
/**
* @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.
* =============================================================================
*/
function ev(n) {
const t = N(n, "image", "RGBToGrayscale"), e = t.rank - 1, s = t.shape[e];
I(t.rank >= 2, () => `Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`), I(s === 3, () => `Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${s}.`);
const o = t.dtype, r = st(t, "float32"), i = We([0.2989, 0.587, 0.114]);
let a;
switch (t.rank) {
case 2:
a = er("ij,j->i", r, i);
break;
case 3:
a = er("ijk,k->ij", r, i);
break;
case 4:
a = er("ijkl,l->ijk", r, i);
break;
case 5:
a = er("ijklm,m->ijkl", r, i);
break;
case 6:
a = er("ijklmn,n->ijklm", r, i);
break;
default:
throw new Error("Not a valid tensor rank.");
}
return a = Oe(a, -1), st(a, o);
}
const nv = /* @__PURE__ */ O({ rgbToGrayscale_: ev });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sv(n, t, e = 0, s = 0.5) {
const o = N(n, "image", "rotateWithOffset", "float32");
I(o.rank === 4, () => `Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);
const r = { image: o }, i = { radians: t, fillValue: e, center: s };
return D.runKernel(dh, r, i);
}
const ov = /* @__PURE__ */ O({ rotateWithOffset_: sv });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Wo(n, t, e, s, o, r) {
s == null && (s = 0.5), o == null && (o = Number.NEGATIVE_INFINITY), r == null && (r = 0);
const i = n.shape[0];
return e = Math.min(e, i), I(0 <= s && s <= 1, () => `iouThreshold must be in [0, 1], but was '${s}'`), I(n.rank === 2, () => `boxes must be a 2D tensor, but was of rank '${n.rank}'`), I(n.shape[1] === 4, () => `boxes must have 4 columns, but 2nd dimension was ${n.shape[1]}`), I(t.rank === 1, () => "scores must be a 1D tensor"), I(t.shape[0] === i, () => `scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`), I(0 <= r && r <= 1, () => `softNmsSigma must be in [0, 1], but was '${r}'`), { maxOutputSize: e, iouThreshold: s, scoreThreshold: o, softNmsSigma: r };
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function rv(n, t, e, s = 0.5, o = Number.NEGATIVE_INFINITY) {
const r = N(n, "boxes", "nonMaxSuppression", "float32"), i = N(t, "scores", "nonMaxSuppression", "float32"), a = Wo(r, i, e, s, o);
e = a.maxOutputSize, s = a.iouThreshold, o = a.scoreThreshold;
const l = { maxOutputSize: e, iouThreshold: s, scoreThreshold: o };
return D.runKernel(Qu, { boxes: r, scores: i }, l);
}
const iv = /* @__PURE__ */ O({ nonMaxSuppression_: rv });
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function av(n, t, e) {
const s = lv(n, t, e), o = s < 0 ? -(s + 1) : s;
n.splice(o, 0, t);
}
function lv(n, t, e) {
return uv(n, t, e || cv);
}
function cv(n, t) {
return n > t ? 1 : n < t ? -1 : 0;
}
function uv(n, t, e) {
let s = 0, o = n.length, r = 0, i = !1;
for (; s < o; ) {
r = s + (o - s >>> 1);
const a = e(t, n[r]);
a > 0 ? s = r + 1 : (o = r, i = !a);
}
return i ? s : -s - 1;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function zh(n, t, e, s, o) {
return Wh(
n,
t,
e,
s,
o,
0
/* softNmsSigma */
);
}
function Bh(n, t, e, s, o, r) {
return Wh(
n,
t,
e,
s,
o,
0,
!1,
r,
!0
/* returnValidOutputs */
);
}
function Vh(n, t, e, s, o, r) {
return Wh(
n,
t,
e,
s,
o,
r,
!0
/* returnScoresTensor */
);
}
function Wh(n, t, e, s, o, r, i = !1, a = !1, l = !1) {
const c = [];
for (let g = 0; g < t.length; g++)
t[g] > o && c.push({ score: t[g], boxIndex: g, suppressBeginIndex: 0 });
c.sort(xp);
const u = r > 0 ? -0.5 / r : 0, h = [], d = [];
for (; h.length < e && c.length > 0; ) {
const g = c.pop(), { score: x, boxIndex: b, suppressBeginIndex: w } = g;
if (x < o)
break;
let y = !1;
for (let C = h.length - 1; C >= w; --C) {
const $ = hv(n, b, h[C]);
if ($ >= s) {
y = !0;
break;
}
if (g.score = g.score * dv(s, u, $), g.score <= o)
break;
}
g.suppressBeginIndex = h.length, y || (g.score === x ? (h.push(b), d.push(g.score)) : g.score > o && av(c, g, xp));
}
const p = h.length, f = e - p;
a && f > 0 && (h.push(...new Array(f).fill(0)), d.push(...new Array(f).fill(0)));
const m = { selectedIndices: h };
return i && (m.selectedScores = d), l && (m.validOutputs = p), m;
}
function hv(n, t, e) {
const s = n.subarray(t * 4, t * 4 + 4), o = n.subarray(e * 4, e * 4 + 4), r = Math.min(s[0], s[2]), i = Math.min(s[1], s[3]), a = Math.max(s[0], s[2]), l = Math.max(s[1], s[3]), c = Math.min(o[0], o[2]), u = Math.min(o[1], o[3]), h = Math.max(o[0], o[2]), d = Math.max(o[1], o[3]), p = (a - r) * (l - i), f = (h - c) * (d - u);
if (p <= 0 || f <= 0)
return 0;
const m = Math.max(r, c), g = Math.max(i, u), x = Math.min(a, h), b = Math.min(l, d), w = Math.max(x - m, 0) * Math.max(b - g, 0);
return w / (p + f - w);
}
function dv(n, t, e) {
const s = Math.exp(t * e * e);
return e <= n ? s : 0;
}
function xp(n, t) {
return n.score - t.score || n.score === t.score && t.boxIndex - n.boxIndex;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
async function pv(n, t, e, s = 0.5, o = Number.NEGATIVE_INFINITY) {
const r = N(n, "boxes", "nonMaxSuppressionAsync"), i = N(t, "scores", "nonMaxSuppressionAsync"), a = Wo(r, i, e, s, o);
e = a.maxOutputSize, s = a.iouThreshold, o = a.scoreThreshold;
const l = await Promise.all([r.data(), i.data()]), c = l[0], u = l[1], { selectedIndices: h } = zh(c, u, e, s, o);
return r !== n && r.dispose(), i !== t && i.dispose(), We(h, "int32");
}
const fv = pv;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function mv(n, t, e, s = 0.5, o = Number.NEGATIVE_INFINITY, r = 0) {
const i = N(n, "boxes", "nonMaxSuppression"), a = N(t, "scores", "nonMaxSuppression"), l = Wo(i, a, e, s, o, r);
e = l.maxOutputSize, s = l.iouThreshold, o = l.scoreThreshold, r = l.softNmsSigma;
const c = { boxes: i, scores: a }, u = { maxOutputSize: e, iouThreshold: s, scoreThreshold: o, softNmsSigma: r }, h = D.runKernel(eh, c, u);
return { selectedIndices: h[0], selectedScores: h[1] };
}
const gv = /* @__PURE__ */ O({ nonMaxSuppressionWithScore_: mv });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
async function xv(n, t, e, s = 0.5, o = Number.NEGATIVE_INFINITY, r = 0) {
const i = N(n, "boxes", "nonMaxSuppressionAsync"), a = N(t, "scores", "nonMaxSuppressionAsync"), l = Wo(i, a, e, s, o, r);
e = l.maxOutputSize, s = l.iouThreshold, o = l.scoreThreshold, r = l.softNmsSigma;
const c = await Promise.all([i.data(), a.data()]), u = c[0], h = c[1], { selectedIndices: d, selectedScores: p } = Vh(u, h, e, s, o, r);
return i !== n && i.dispose(), a !== t && a.dispose(), {
selectedIndices: We(d, "int32"),
selectedScores: We(p)
};
}
const bv = xv;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yv(n, t, e, s = 0.5, o = Number.NEGATIVE_INFINITY, r = !1) {
const i = N(n, "boxes", "nonMaxSuppression"), a = N(t, "scores", "nonMaxSuppression"), l = Wo(
i,
a,
e,
s,
o,
null
/* softNmsSigma */
), c = l.maxOutputSize, u = l.iouThreshold, h = l.scoreThreshold, d = { boxes: i, scores: a }, p = {
maxOutputSize: c,
iouThreshold: u,
scoreThreshold: h,
padToMaxOutputSize: r
}, f = D.runKernel(th, d, p);
return { selectedIndices: f[0], validOutputs: f[1] };
}
const wv = /* @__PURE__ */ O({ nonMaxSuppressionPadded_: yv });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
async function Cv(n, t, e, s = 0.5, o = Number.NEGATIVE_INFINITY, r = !1) {
const i = N(n, "boxes", "nonMaxSuppressionAsync"), a = N(t, "scores", "nonMaxSuppressionAsync"), l = Wo(
i,
a,
e,
s,
o,
null
/* softNmsSigma */
), c = l.maxOutputSize, u = l.iouThreshold, h = l.scoreThreshold, [d, p] = await Promise.all([i.data(), a.data()]), { selectedIndices: f, validOutputs: m } = Bh(d, p, c, u, h, r);
return i !== n && i.dispose(), a !== t && a.dispose(), {
selectedIndices: We(f, "int32"),
validOutputs: Tt(m, "int32")
};
}
const $v = Cv;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Iv(n, t, e = !1, s = !1) {
const o = N(n, "images", "resizeBilinear");
I(o.rank === 3 || o.rank === 4, () => `Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`), I(t.length === 2, () => `Error in resizeBilinear: new shape must 2D, but got shape ${t}.`), I(s === !1 || e === !1, () => "Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");
let r = o, i = !1;
o.rank === 3 && (i = !0, r = A(o, [1, o.shape[0], o.shape[1], o.shape[2]]));
const a = { images: r }, l = { alignCorners: e, halfPixelCenters: s, size: t }, c = D.runKernel($l, a, l);
return i ? A(c, [c.shape[1], c.shape[2], c.shape[3]]) : c;
}
const cg = /* @__PURE__ */ O({ resizeBilinear_: Iv });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kv(n, t, e = !1, s = !1) {
const o = N(n, "images", "resizeNearestNeighbor");
I(o.rank === 3 || o.rank === 4, () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`), I(t.length === 2, () => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`), I(o.dtype === "float32" || o.dtype === "int32", () => "`images` must have `int32` or `float32` as dtype"), I(s === !1 || e === !1, () => "Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");
let r = o, i = !1;
o.rank === 3 && (i = !0, r = A(o, [1, o.shape[0], o.shape[1], o.shape[2]]));
const a = { images: r }, l = { alignCorners: e, halfPixelCenters: s, size: t }, c = D.runKernel(Cl, a, l);
return i ? A(c, [c.shape[1], c.shape[2], c.shape[3]]) : c;
}
const ug = /* @__PURE__ */ O({ resizeNearestNeighbor_: kv });
/**
* @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.
* =============================================================================
*/
function vv(n, t = "binary", e = !1, s = 0.5) {
const o = N(n, "image", "threshold"), r = 0.2989, i = 0.587, a = 0.114, l = o.shape[0] * o.shape[1];
let c = R(We([s]), 255), u, h, d, p;
if (I(o.rank === 3, () => `Error in threshold: image must be rank 3,but got rank ${o.rank}.`), I(o.shape[2] === 3 || o.shape[2] === 1, () => `Error in threshold: image color channel must be equal to 3 or 1but got ${o.shape[2]}.`), I(o.dtype === "int32" || o.dtype === "float32", () => `Error in dtype: image dtype must be int32 or float32,but got dtype ${o.dtype}.`), I(t === "otsu" || t === "binary", () => `Method must be binary or otsu, but was ${t}`), o.shape[2] === 3) {
[u, h, d] = qe(o, [1, 1, 1], -1);
const g = R(u, r), x = R(h, i), b = R(d, a);
p = Y(Y(g, x), b);
} else
p = n;
if (t === "otsu") {
const g = BC(st(Jm(p), "int32"), km([]), 256);
c = Sv(g, l);
}
const f = e ? Vo(p, c) : Je(p, c);
return st(R(f, 255), "int32");
}
function Sv(n, t) {
let e = We([-1]), s = We([0]), o = We([0]), r, i, a, l, c, u;
for (let h = 0; h < n.size - 1; h++) {
r = zt(n, 0, h + 1), i = zt(n, h + 1), c = ut(ct(r), t), u = ut(ct(i), t);
const d = ct(R(r, gr(0, r.size)));
a = ut(d, ct(r));
const p = Pl(i.shape, r.size), f = Y(gr(0, i.size), p), m = R(i, f);
l = ut(ct(m), ct(i));
const g = pt(a, l), x = pt(a, l), b = R(c, u);
o = R(R(b, g), x);
const w = Je(o, s);
s = Re(w, o, s), e = Re(w, We([h]), e);
}
return e;
}
const Nv = /* @__PURE__ */ O({ threshold_: vv });
/**
* @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.
* =============================================================================
*/
function Tv(n, t, e = "nearest", s = "constant", o = 0, r) {
const i = N(n, "image", "transform", "float32"), a = N(t, "transforms", "transform", "float32");
I(i.rank === 4, () => `Error in transform: image must be rank 4,but got rank ${i.rank}.`), I(a.rank === 2 && (a.shape[0] === i.shape[0] || a.shape[0] === 1) && a.shape[1] === 8, () => "Error in transform: Input transform should be batch x 8 or 1 x 8"), I(r == null || r.length === 2, () => `Error in transform: outputShape must be [height, width] or null, but got ${r}.`);
const l = { image: i, transforms: a }, c = { interpolation: e, fillMode: s, fillValue: o, outputShape: r };
return D.runKernel(uh, l, c);
}
const Ev = /* @__PURE__ */ O({ transform_: Tv });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Rv(n, t, e) {
const s = N(n, "a", "bandPart");
I(s.rank >= 2, () => `bandPart(): Rank must be at least 2, got ${s.rank}.`);
const o = s.shape, [r, i] = s.shape.slice(-2);
let a, l;
typeof t == "number" ? (I(t % 1 === 0, () => `bandPart(): numLower must be an integer, got ${t}.`), I(t <= r, () => `bandPart(): numLower (${t}) must not be greater than the number of rows (${r}).`), a = N(t < 0 ? r : t, "numLower", "bandPart")) : (I(t.dtype === "int32", () => "bandPart(): numLower's dtype must be an int32."), a = Re(ha(t, 0), r, mr(t, r))), typeof e == "number" ? (I(e % 1 === 0, () => `bandPart(): numUpper must be an integer, got ${e}.`), I(e <= i, () => `bandPart(): numUpper (${e}) must not be greater than the number of columns (${i}).`), l = N(e < 0 ? i : e, "numUpper", "bandPart")) : (I(e.dtype === "int32", () => "bandPart(): numUpper's dtype must be an int32."), l = Re(ha(e, 0), i, mr(e, i)));
const c = A(gr(0, r, 1, "int32"), [-1, 1]), u = gr(0, i, 1, "int32"), h = pt(c, u), d = jn(Vo(h, a), oo(h, Yt(l))), p = he([r, i], s.dtype);
return A(Xn(Ys(A(s, [-1, r, i])).map((f) => Re(d, f, p))), o);
}
const Dv = /* @__PURE__ */ O({ bandPart_: Rv });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Av(n) {
let t;
if (Array.isArray(n)) {
t = !1, I(n != null && n.length > 0, () => "Gram-Schmidt process: input must not be null, undefined, or empty");
const o = n[0].shape[0];
for (let r = 1; r < n.length; ++r)
I(n[r].shape[0] === o, () => `Gram-Schmidt: Non-unique lengths found in the input vectors: (${n[r].shape[0]} vs. ${o})`);
} else
t = !0, n = qe(n, n.shape[0], 0).map((o) => ki(o, [0]));
I(n.length <= n[0].shape[0], () => `Gram-Schmidt: Number of vectors (${n.length}) exceeds number of dimensions (${n[0].shape[0]}).`);
const e = [], s = n;
for (let o = 0; o < n.length; ++o)
e.push(D.tidy(() => {
let r = s[o];
if (o > 0)
for (let i = 0; i < o; ++i) {
const a = R(ct(R(e[i], r)), e[i]);
r = pt(r, a);
}
return ut(r, Bl(r, "euclidean"));
}));
return t ? Xn(e, 0) : e;
}
const Fv = /* @__PURE__ */ O({ gramSchmidt_: Av });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ov(n, t = !1) {
if (I(n.rank >= 2, () => `qr() requires input tensor to have a rank >= 2, but got rank ${n.rank}`), n.rank === 2)
return bp(n, t);
{
const e = n.shape.slice(0, n.shape.length - 2).reduce((l, c) => l * c), s = Ys(A(n, [
e,
n.shape[n.shape.length - 2],
n.shape[n.shape.length - 1]
]), 0), o = [], r = [];
s.forEach((l) => {
const [c, u] = bp(l, t);
o.push(c), r.push(u);
});
const i = A(Xn(o, 0), n.shape), a = A(Xn(r, 0), n.shape);
return [i, a];
}
}
function bp(n, t = !1) {
return D.tidy(() => {
I(n.shape.length === 2, () => `qr2d() requires a 2D Tensor, but got a ${n.shape.length}D Tensor.`);
const e = n.shape[0], s = n.shape[1];
let o = Um(e), r = Ps(n);
const i = mc([[1]], [1, 1]);
let a = Ps(i);
const l = e >= s ? s : e;
for (let c = 0; c < l; ++c) {
const u = r, h = a, d = o;
[a, r, o] = D.tidy(() => {
const p = zt(r, [c, c], [e - c, 1]), f = Bl(p), m = zt(r, [c, c], [1, 1]), g = Re(Je(m, 0), mc([[-1]]), mc([[1]])), x = pt(m, R(g, f)), b = ut(p, x);
b.shape[0] === 1 ? a = Ps(i) : a = Le([
i,
zt(b, [1, 0], [b.shape[0] - 1, b.shape[1]])
], 0);
const w = Yt(ut(Nt(g, x), f)), y = zt(r, [c, 0], [e - c, s]), C = R(w, a), $ = It(a);
if (c === 0)
r = pt(y, Nt(C, Nt($, y)));
else {
const S = pt(y, Nt(C, Nt($, y)));
r = Le([zt(r, [0, 0], [c, s]), S], 0);
}
const k = It(C), v = zt(o, [0, c], [e, o.shape[1] - c]);
if (c === 0)
o = pt(v, Nt(Nt(v, a), k));
else {
const S = pt(v, Nt(Nt(v, a), k));
o = Le([zt(o, [0, 0], [e, c]), S], 1);
}
return [a, r, o];
}), $t([u, h, d]);
}
return !t && e > s && (o = zt(o, [0, 0], [e, s]), r = zt(r, [0, 0], [s, s])), [o, r];
});
}
const _v = /* @__PURE__ */ O({ qr_: Ov });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Hn = {
flipLeftRight: Zk,
grayscaleToRGB: tv,
resizeNearestNeighbor: ug,
resizeBilinear: cg,
rgbToGrayscale: nv,
rotateWithOffset: ov,
cropAndResize: Yk,
nonMaxSuppression: iv,
nonMaxSuppressionAsync: fv,
nonMaxSuppressionWithScore: gv,
nonMaxSuppressionWithScoreAsync: bv,
nonMaxSuppressionPadded: wv,
nonMaxSuppressionPaddedAsync: $v,
threshold: Nv,
transform: Ev
}, Lv = {
bandPart: Dv,
gramSchmidt: Fv,
qr: _v
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Mv = /* @__PURE__ */ new Map(), Pv = /* @__PURE__ */ new Map();
class Uo {
/**
* 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(t, e) {
return new t(e);
}
}
class nn {
constructor() {
this.classNameMap = {};
}
/**
* Returns the singleton instance of the map.
*/
static getMap() {
return nn.instance == null && (nn.instance = new nn()), nn.instance;
}
/**
* Registers the class as serializable.
*/
static register(t) {
nn.getMap().classNameMap[t.className] = [t, t.fromConfig];
}
}
function j(n, t, e) {
I(n.className != null, () => "Class being registered does not have the static className property defined."), I(typeof n.className == "string", () => "className is required to be a string, but got type " + typeof n.className), I(n.className.length > 0, () => "Class being registered has an empty-string as its className, which is disallowed."), typeof t > "u" && (t = "Custom"), typeof e > "u" && (e = n.className);
const s = e, o = t + ">" + s;
return nn.register(n), Mv.set(o, n), Pv.set(n, o), n;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class vs extends Uo {
/**
* 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(t, e = !1, s) {
const { value: o, grads: r } = this.computeGradients(t, s);
if (s != null) {
const i = s.map((a) => ({ name: a.name, tensor: r[a.name] }));
this.applyGradients(i);
} else
this.applyGradients(r);
return $t(r), e ? o : (o.dispose(), null);
}
/**
* The number of iterations that this optimizer instance has been invoked for.
*/
get iterations() {
return this.iterations_ == null && (this.iterations_ = 0), 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(t, e) {
return aI(t, e);
}
/**
* Dispose the variables (if any) owned by this optimizer instance.
*/
dispose() {
this.iterations_ != null && $t(this.iterations_);
}
async saveIterations() {
return this.iterations_ == null && (this.iterations_ = 0), {
name: "iter",
// TODO(cais): Use 'int64' type when available.
tensor: Tt(this.iterations_, "int32")
};
}
async getWeights() {
throw new Error("getWeights() is not implemented for this optimizer yet.");
}
async setWeights(t) {
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(t) {
return this.iterations_ = (await t[0].tensor.data())[0], t.slice(1);
}
}
Object.defineProperty(vs, Symbol.hasInstance, {
value: (n) => n.minimize != null && n.computeGradients != null && n.applyGradients != null
});
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class hg extends vs {
/** @nocollapse */
static get className() {
return "Adadelta";
}
constructor(t, e, s = null) {
super(), this.learningRate = t, this.rho = e, this.epsilon = s, this.accumulatedGrads = [], this.accumulatedUpdates = [], s == null && (this.epsilon = D.backend.epsilon());
}
applyGradients(t) {
(Array.isArray(t) ? t.map((s) => s.name) : Object.keys(t)).forEach((s, o) => {
const r = D.registeredVariables[s], i = !1;
this.accumulatedGrads[o] == null && (this.accumulatedGrads[o] = {
originalName: `${s}/accum_grad`,
variable: _(() => kt(r).variable(i))
}), this.accumulatedUpdates[o] == null && (this.accumulatedUpdates[o] = {
originalName: `${s}/accum_var`,
variable: _(() => kt(r).variable(i))
});
const a = Array.isArray(t) ? t[o].tensor : t[s];
if (a == null)
return;
const l = this.accumulatedGrads[o].variable, c = this.accumulatedUpdates[o].variable;
_(() => {
const u = Y(R(l, this.rho), R(Vt(a), 1 - this.rho)), h = R(ut($e(Y(c, this.epsilon)), $e(Y(l, this.epsilon))), a), d = Y(R(c, this.rho), R(Vt(h), 1 - this.rho));
l.assign(u), c.assign(d);
const p = Y(R(h, -this.learningRate), r);
r.assign(p);
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedUpdates != null && ($t(this.accumulatedGrads.map((t) => t.variable)), $t(this.accumulatedUpdates.map((t) => t.variable)));
}
async getWeights() {
const t = [...this.accumulatedGrads, ...this.accumulatedUpdates];
return [await this.saveIterations()].concat(t.map((e) => ({ name: e.originalName, tensor: e.variable })));
}
async setWeights(t) {
t = await this.extractIterations(t);
const e = t.length / 2, s = !1;
this.accumulatedGrads = t.slice(0, e).map((o) => ({
originalName: o.name,
variable: o.tensor.variable(s)
})), this.accumulatedUpdates = t.slice(e, e * 2).map((o) => ({
originalName: o.name,
variable: o.tensor.variable(s)
}));
}
getConfig() {
return {
learningRate: this.learningRate,
rho: this.rho,
epsilon: this.epsilon
};
}
/** @nocollapse */
static fromConfig(t, e) {
return new t(e.learningRate, e.rho, e.epsilon);
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class dg extends vs {
/** @nocollapse */
static get className() {
return "Adagrad";
}
constructor(t, e = 0.1) {
super(), this.learningRate = t, this.initialAccumulatorValue = e, this.accumulatedGrads = [];
}
applyGradients(t) {
(Array.isArray(t) ? t.map((s) => s.name) : Object.keys(t)).forEach((s, o) => {
const r = D.registeredVariables[s];
this.accumulatedGrads[o] == null && (this.accumulatedGrads[o] = {
originalName: `${s}/accumulator`,
variable: _(() => Pl(r.shape, this.initialAccumulatorValue).variable(!1))
});
const i = Array.isArray(t) ? t[o].tensor : t[s];
if (i == null)
return;
const a = this.accumulatedGrads[o].variable;
_(() => {
const l = Y(a, Vt(i));
a.assign(l);
const c = Y(R(ut(i, $e(Y(l, D.backend.epsilon()))), -this.learningRate), r);
r.assign(c);
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedGrads != null && $t(this.accumulatedGrads.map((t) => t.variable));
}
async getWeights() {
return [await this.saveIterations()].concat(this.accumulatedGrads.map((t) => ({ name: t.originalName, tensor: t.variable })));
}
async setWeights(t) {
t = await this.extractIterations(t);
const e = !1;
this.accumulatedGrads = t.map((s) => ({ originalName: s.name, variable: s.tensor.variable(e) }));
}
getConfig() {
return {
learningRate: this.learningRate,
initialAccumulatorValue: this.initialAccumulatorValue
};
}
/** @nocollapse */
static fromConfig(t, e) {
return new t(e.learningRate, e.initialAccumulatorValue);
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class pg extends vs {
/** @nocollapse */
static get className() {
return "Adam";
}
constructor(t, e, s, o = null) {
super(), this.learningRate = t, this.beta1 = e, this.beta2 = s, this.epsilon = o, this.accumulatedFirstMoment = [], this.accumulatedSecondMoment = [], _(() => {
this.accBeta1 = Tt(e).variable(), this.accBeta2 = Tt(s).variable();
}), o == null && (this.epsilon = D.backend.epsilon());
}
applyGradients(t) {
const e = Array.isArray(t) ? t.map((s) => s.name) : Object.keys(t);
_(() => {
const s = pt(1, this.accBeta1), o = pt(1, this.accBeta2);
e.forEach((r, i) => {
const a = D.registeredVariables[r], l = !1;
this.accumulatedFirstMoment[i] == null && (this.accumulatedFirstMoment[i] = {
originalName: `${r}/m`,
variable: _(() => kt(a).variable(l))
}), this.accumulatedSecondMoment[i] == null && (this.accumulatedSecondMoment[i] = {
originalName: `${r}/v`,
variable: _(() => kt(a).variable(l))
});
const c = Array.isArray(t) ? t[i].tensor : t[r];
if (c == null)
return;
const u = this.accumulatedFirstMoment[i].variable, h = this.accumulatedSecondMoment[i].variable, d = Y(R(u, this.beta1), R(c, 1 - this.beta1)), p = Y(R(h, this.beta2), R(Vt(c), 1 - this.beta2)), f = ut(d, s), m = ut(p, o);
u.assign(d), h.assign(p);
const g = Y(R(ut(f, Y($e(m), this.epsilon)), -this.learningRate), a);
a.assign(g);
}), this.accBeta1.assign(R(this.accBeta1, this.beta1)), this.accBeta2.assign(R(this.accBeta2, this.beta2));
}), this.incrementIterations();
}
dispose() {
this.accBeta1.dispose(), this.accBeta2.dispose(), this.accumulatedFirstMoment != null && $t(this.accumulatedFirstMoment.map((t) => t.variable)), this.accumulatedSecondMoment != null && $t(this.accumulatedSecondMoment.map((t) => t.variable));
}
async getWeights() {
const t = [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];
return [await this.saveIterations()].concat(t.map((e) => ({ name: e.originalName, tensor: e.variable })));
}
async setWeights(t) {
t = await this.extractIterations(t), _(() => {
this.accBeta1.assign(Xs(this.beta1, this.iterations_ + 1)), this.accBeta2.assign(Xs(this.beta2, this.iterations_ + 1));
});
const e = t.length / 2, s = !1;
this.accumulatedFirstMoment = t.slice(0, e).map((o) => ({
originalName: o.name,
variable: o.tensor.variable(s)
})), this.accumulatedSecondMoment = t.slice(e, e * 2).map((o) => ({
originalName: o.name,
variable: o.tensor.variable(s)
}));
}
getConfig() {
return {
learningRate: this.learningRate,
beta1: this.beta1,
beta2: this.beta2,
epsilon: this.epsilon
};
}
/** @nocollapse */
static fromConfig(t, e) {
return new t(e.learningRate, e.beta1, e.beta2, e.epsilon);
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class fg extends vs {
/** @nocollapse */
static get className() {
return "Adamax";
}
constructor(t, e, s, o = null, r = 0) {
super(), this.learningRate = t, this.beta1 = e, this.beta2 = s, this.epsilon = o, this.decay = r, this.accumulatedFirstMoment = [], this.accumulatedWeightedInfNorm = [], _(() => {
this.iteration = Tt(0).variable(), this.accBeta1 = Tt(e).variable();
}), o == null && (this.epsilon = D.backend.epsilon());
}
applyGradients(t) {
const e = Array.isArray(t) ? t.map((s) => s.name) : Object.keys(t);
_(() => {
const s = pt(1, this.accBeta1), o = ut(-this.learningRate, Y(R(this.iteration, this.decay), 1));
e.forEach((r, i) => {
const a = D.registeredVariables[r], l = !1;
this.accumulatedFirstMoment[i] == null && (this.accumulatedFirstMoment[i] = {
originalName: `${r}/m`,
variable: kt(a).variable(l)
}), this.accumulatedWeightedInfNorm[i] == null && (this.accumulatedWeightedInfNorm[i] = {
originalName: `${r}/v`,
variable: kt(a).variable(l)
});
const c = Array.isArray(t) ? t[i].tensor : t[r];
if (c == null)
return;
const u = this.accumulatedFirstMoment[i].variable, h = this.accumulatedWeightedInfNorm[i].variable, d = Y(R(u, this.beta1), R(c, 1 - this.beta1)), p = R(h, this.beta2), f = Ne(c), m = Is(p, f);
u.assign(d), h.assign(m);
const g = Y(R(ut(o, s), ut(d, Y(m, this.epsilon))), a);
a.assign(g);
}), this.iteration.assign(Y(this.iteration, 1)), this.accBeta1.assign(R(this.accBeta1, this.beta1));
}), this.incrementIterations();
}
dispose() {
this.accBeta1.dispose(), this.iteration.dispose(), this.accumulatedFirstMoment != null && $t(this.accumulatedFirstMoment.map((t) => t.variable)), this.accumulatedWeightedInfNorm != null && $t(this.accumulatedWeightedInfNorm.map((t) => t.variable));
}
async getWeights() {
throw new Error("getWeights() is not implemented for Adamax yet.");
}
async setWeights(t) {
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(t, e) {
return new t(e.learningRate, e.beta1, e.beta2, e.epsilon, e.decay);
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Uh extends vs {
/** @nocollapse */
static get className() {
return "SGD";
}
constructor(t) {
super(), this.learningRate = t, this.setLearningRate(t);
}
applyGradients(t) {
(Array.isArray(t) ? t.map((s) => s.name) : Object.keys(t)).forEach((s, o) => {
const r = Array.isArray(t) ? t[o].tensor : t[s];
if (r == null)
return;
const i = D.registeredVariables[s];
_(() => {
const a = Y(R(this.c, r), i);
i.assign(a);
});
}), this.incrementIterations();
}
/**
* Sets the learning rate of the optimizer.
*/
setLearningRate(t) {
this.learningRate = t, this.c != null && this.c.dispose(), this.c = Dn(Tt(-t));
}
dispose() {
this.c.dispose();
}
async getWeights() {
return [await this.saveIterations()];
}
async setWeights(t) {
if (t = await this.extractIterations(t), t.length !== 0)
throw new Error("SGD optimizer does not have settable weights.");
}
getConfig() {
return { learningRate: this.learningRate };
}
/** @nocollapse */
static fromConfig(t, e) {
return new t(e.learningRate);
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class mg extends Uh {
/** @nocollapse */
// Name matters for Python compatibility.
static get className() {
return "Momentum";
}
constructor(t, e, s = !1) {
super(t), this.learningRate = t, this.momentum = e, this.useNesterov = s, this.accumulations = [], this.m = Tt(this.momentum);
}
applyGradients(t) {
(Array.isArray(t) ? t.map((s) => s.name) : Object.keys(t)).forEach((s, o) => {
const r = D.registeredVariables[s];
this.accumulations[o] == null && (this.accumulations[o] = {
originalName: `${s}/momentum`,
variable: _(() => kt(r).variable(!1))
});
const i = this.accumulations[o].variable, a = Array.isArray(t) ? t[o].tensor : t[s];
a != null && _(() => {
let l;
const c = Y(R(this.m, i), a);
this.useNesterov ? l = Y(R(this.c, Y(a, R(c, this.m))), r) : l = Y(R(this.c, c), r), i.assign(c), r.assign(l);
});
}), this.incrementIterations();
}
dispose() {
this.m.dispose(), this.accumulations != null && $t(this.accumulations.map((t) => t.variable));
}
/**
* Sets the momentum of the optimizer.
*
* @param momentum
*/
setMomentum(t) {
this.momentum = t;
}
async getWeights() {
return [await this.saveIterations()].concat(this.accumulations.map((t) => ({ name: t.originalName, tensor: t.variable })));
}
async setWeights(t) {
t = await this.extractIterations(t);
const e = !1;
this.accumulations = t.map((s) => ({ originalName: s.name, variable: s.tensor.variable(e) }));
}
getConfig() {
return {
learningRate: this.learningRate,
momentum: this.momentum,
useNesterov: this.useNesterov
};
}
/** @nocollapse */
static fromConfig(t, e) {
return new t(e.learningRate, e.momentum, e.useNesterov);
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class gg extends vs {
/** @nocollapse */
static get className() {
return "RMSProp";
}
constructor(t, e = 0.9, s = 0, o = null, r = !1) {
if (super(), this.learningRate = t, this.decay = e, this.momentum = s, this.epsilon = o, this.accumulatedMeanSquares = [], this.accumulatedMoments = [], this.accumulatedMeanGrads = [], this.centered = r, o == null && (this.epsilon = D.backend.epsilon()), t == null)
throw new Error("learningRate for RMSPropOptimizer must be defined.");
}
applyGradients(t) {
(Array.isArray(t) ? t.map((s) => s.name) : Object.keys(t)).forEach((s, o) => {
const r = D.registeredVariables[s], i = !1;
this.accumulatedMeanSquares[o] == null && (this.accumulatedMeanSquares[o] = {
originalName: `${s}/rms`,
variable: _(() => kt(r).variable(i))
}), this.accumulatedMoments[o] == null && (this.accumulatedMoments[o] = {
originalName: `${s}/momentum`,
variable: _(() => kt(r).variable(i))
}), this.accumulatedMeanGrads[o] == null && this.centered && (this.accumulatedMeanGrads[o] = {
originalName: `${s}/mg`,
variable: _(() => kt(r).variable(i))
});
const a = Array.isArray(t) ? t[o].tensor : t[s];
if (a == null)
return;
const l = this.accumulatedMeanSquares[o].variable, c = this.accumulatedMoments[o].variable;
_(() => {
const u = Y(R(l, this.decay), R(Vt(a), 1 - this.decay));
if (this.centered) {
const h = this.accumulatedMeanGrads[o].variable, d = Y(R(h, this.decay), R(a, 1 - this.decay)), p = ut(R(a, this.learningRate), $e(pt(u, Y(Vt(d), this.epsilon)))), f = Y(R(c, this.momentum), p);
l.assign(u), h.assign(d), c.assign(f);
const m = pt(r, f);
r.assign(m);
} else {
const h = Y(R(l, this.decay), R(Vt(a), 1 - this.decay)), d = Y(R(c, this.momentum), ut(R(a, this.learningRate), $e(Y(h, this.epsilon))));
l.assign(h), c.assign(d);
const p = pt(r, d);
r.assign(p);
}
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedMeanSquares != null && $t(this.accumulatedMeanSquares.map((t) => t.variable)), this.accumulatedMeanGrads != null && this.centered && $t(this.accumulatedMeanGrads.map((t) => t.variable)), this.accumulatedMoments != null && $t(this.accumulatedMoments.map((t) => t.variable));
}
async getWeights() {
const t = [...this.accumulatedMeanSquares, ...this.accumulatedMoments];
return this.centered && t.push(...this.accumulatedMeanGrads), [await this.saveIterations()].concat(t.map((e) => ({ name: e.originalName, tensor: e.variable })));
}
async setWeights(t) {
t = await this.extractIterations(t);
const e = this.centered ? t.length / 3 : t.length / 2, s = !1;
this.accumulatedMeanSquares = t.slice(0, e).map((o) => ({
originalName: o.name,
variable: o.tensor.variable(s)
})), this.accumulatedMoments = t.slice(e, e * 2).map((o) => ({
originalName: o.name,
variable: o.tensor.variable(s)
})), this.centered && (this.accumulatedMeanGrads = t.slice(e * 2, e * 3).map((o) => ({
originalName: o.name,
variable: o.tensor.variable(s)
})));
}
getConfig() {
return {
learningRate: this.learningRate,
decay: this.decay,
momentum: this.momentum,
epsilon: this.epsilon,
centered: this.centered
};
}
/** @nocollapse */
static fromConfig(t, e) {
return new t(e.learningRate, e.decay, e.momentum, e.epsilon, e.centered);
}
}
/**
* @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.
* =============================================================================
*/
const zv = [
hg,
dg,
pg,
fg,
mg,
gg,
Uh
];
function Bv() {
for (const n of zv)
j(n);
}
function Gh(n, t) {
const e = n.shape.length, s = t.shape.length;
if (e < 1)
throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e}.`);
if (s < 1)
throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);
if (t.dtype !== "int32")
throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);
if (t.shape[s - 1] > e)
throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s - 1]} vs. ${e}`);
if (G(n.shape) === 0)
throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${n.shape}.`);
const o = t.shape, r = o[o.length - 1];
let i = 1;
for (let h = 0; h < o.length - 1; ++h)
i *= o[h];
const a = n.shape, l = o.slice();
l.pop();
let c = 1;
for (let h = r; h < e; ++h)
c *= a[h], l.push(a[h]);
const u = [
...lt(n.shape).map((h) => h / c),
1
].slice(0, r);
return [l, i, c, u];
}
/**
* @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.
* =============================================================================
*/
const qc = -2, Vv = -1;
function Hh(n, t, e) {
const s = n.shape.length;
I(s === t.length, () => `Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`), I(s === e.length, () => `Error in slice${s}D: Length of size ${e} must match the rank of the array (${s}).`);
for (let o = 0; o < s; ++o)
I(t[o] + e[o] <= n.shape[o], () => `Error in slice${s}D: begin[${o}] + size[${o}] (${t[o] + e[o]}) would overflow input.shape[${o}] (${n.shape[o]})`);
}
function Wv(n) {
const t = [];
let e = 0;
for (; n > 0; )
n & 1 && t.push(e), n /= 2, e++;
return t;
}
function Kh(n, t, e) {
const s = [];
for (let o = 0; o < n.length; o++)
s[o] = Math.ceil((t[o] - n[o]) / e[o]);
return s;
}
function xg(n, t, e, s) {
const o = [...n];
for (let r = o.length; r < s.length; r++)
o.push(1);
for (let r = 0; r < e; r++)
r === 0 ? o[t] = 1 : (o.splice(
t,
0,
1
/* element to add */
), o.pop());
return o;
}
function bg(n, t, e) {
return e <= n ? e : e - (t - 1);
}
function yg(n, t) {
const e = [];
for (let s = 0; s < n; s++)
e.push(t + s);
return e;
}
function Uv(n, t, e, s, o, r, i, a, l) {
const c = n.length;
let u = new Array(c), h = new Array(c), d = new Array(c);
if (t.length && e > 0) {
const p = t[0], f = e + 1;
u = wg(i, p, f, s, n), h = Cg(a, p, f, o, n), d = xg(r, p, f, n);
} else
for (let p = 0; p < c; p++)
u[p] = Ig(i, s, r, n, p, l), h[p] = kg(a, o, r, n, p, l), d[p] = $g(r, p, l);
return {
begin: u,
end: h,
strides: d
};
}
function wg(n, t, e, s, o) {
const r = [...o], i = yg(e, t);
for (let a = 0; a < r.length; a++)
if (i.indexOf(a) > -1)
r[a] = 0;
else {
const l = bg(t, e, a);
let c = s[l];
n & 1 << l && (c = 0), r[a] = c;
}
return r;
}
function Cg(n, t, e, s, o) {
const r = [...o], i = yg(e, t);
for (let a = 0; a < r.length; a++)
if (i.indexOf(a) > -1)
r[a] = Number.MAX_SAFE_INTEGER;
else {
const l = bg(t, e, a);
let c = s[l];
n & 1 << l && (c = Number.MAX_SAFE_INTEGER), r[a] = c;
}
for (let a = 0; a < r.length; a++) {
const l = o[a];
r[a] < 0 && (r[a] += l), r[a] = Vs(0, r[a], o[a]);
}
return r;
}
function $g(n, t, e) {
let s = n[t];
return (e & 1 << t || s == null) && (s = 1), s;
}
function Ig(n, t, e, s, o, r) {
let i = t[o];
const a = e[o] || 1;
(n & 1 << o || r & 1 << o || i == null) && (a > 0 ? i = Number.MIN_SAFE_INTEGER : i = Number.MAX_SAFE_INTEGER);
const l = s[o];
return i < 0 && (i += l), i = Vs(0, i, l - 1), i;
}
function kg(n, t, e, s, o, r) {
let i = t[o];
const a = e[o] || 1;
(n & 1 << o || r & 1 << o || i == null) && (a > 0 ? i = Number.MAX_SAFE_INTEGER : i = Number.MIN_SAFE_INTEGER);
const l = s[o];
return i < 0 && (i += l), a > 0 ? i = Vs(0, i, l) : i = Vs(-1, i, l - 1), i;
}
function jh(n, t, e) {
let s = e.length;
for (let o = 0; o < e.length; o++)
if (e[o] > 1) {
s = o;
break;
}
for (let o = s + 1; o < e.length; o++)
if (t[o] > 0 || e[o] !== n[o])
return !1;
return !0;
}
function Xh(n, t) {
let e = n.length > 0 ? n[n.length - 1] : 1;
for (let s = 0; s < n.length - 1; s++)
e += n[s] * t[s];
return e;
}
function Wl(n, t, e) {
let s;
const o = n.shape.length;
typeof t == "number" ? s = [t, ...new Array(o - 1).fill(0)] : t.length < o ? s = t.concat(new Array(o - t.length).fill(0)) : s = t.slice(), s.forEach((i) => {
I(i !== -1, () => "slice() does not support negative begin indexing.");
});
let r;
return e == null ? r = new Array(o).fill(-1) : typeof e == "number" ? r = [e, ...new Array(o - 1).fill(-1)] : e.length < o ? r = e.concat(new Array(o - e.length).fill(-1)) : r = e, r = r.map((i, a) => i >= 0 ? i : (I(i === -1, () => `Negative size values should be exactly -1 but got ${i} for the slice() size at index ${a}.`), n.shape[a] - s[a])), [s, r];
}
function qh(n, t, e, s, o, r, i, a, l) {
let c;
if (s == null ? (c = new Array(t.length), c.fill(1)) : c = s, i != null && i & i - 1)
throw new Error("Multiple ellipses in slice is not allowed.");
let u = !1;
const h = {
dims: c.length,
numAddAxisAfterEllipsis: 0,
begin: t.slice(),
end: e.slice(),
strides: c.slice(),
beginMask: o,
endMask: r,
ellipsisMask: i,
newAxisMask: a,
shrinkAxisMask: l
};
for (let w = 0; w < h.dims; w++)
u && 1 << w & a && h.numAddAxisAfterEllipsis++, 1 << w & i && (u = !0);
u || (h.ellipsisMask |= 1 << h.dims, h.dims++);
const d = {
dims: n.length,
beginMask: 0,
endMask: 0,
beginValid: !1,
endValid: !1
};
Gv(h, d);
let p = !0, f = !0, m = !0;
const g = [], x = [];
for (let w = 0; w < n.length; ++w) {
if (d.strides[w] === 0)
throw Error(`strides[${w}] must be non-zero`);
const y = !!(d.shrinkAxisMask & 1 << w), C = n[w];
if (C === -1) {
g.push(y ? 1 : -1);
continue;
}
const $ = [d.beginMask & 1 << w, d.endMask & 1 << w], k = [
d.strides[w] > 0 ? 0 : -1,
d.strides[w] > 0 ? C : C - 1
];
if (y && d.strides[w] <= 0)
throw Error("only stride 1 allowed on non-range indexing.");
m = m && d.strides[w] === 1;
const v = !!(d.beginMask & 1 << w && d.endMask & 1 << w);
if (d.beginValid && d.endValid) {
if (y) {
const L = d.begin[w] < 0 ? C + d.begin[w] : d.begin[w];
if (d.begin[w] = L, d.end[w] = d.begin[w] + 1, L < 0 || L >= C)
throw Error(`slice index ${d.begin[w]} of dimension ${w} out of bounds.`);
} else
d.begin[w] = yp(d.begin[w], 0, d.strides[w], C, $, k), d.end[w] = yp(d.end[w], 1, d.strides[w], C, $, k);
const F = d.strides[w] === 1 && d.begin[w] === 0 && d.end[w] === C;
p = p && F, f = f && (w === 0 && d.strides[w] === 1 || F);
} else
p = p && d.strides[w] === 1 && v, f = f && (w === 0 && d.strides[w] === 1 || v);
let S, T = !1;
if (d.beginValid && d.endValid ? (S = d.end[w] - d.begin[w], T = !0) : y ? (S = 1, T = !0) : v && C >= 0 && (d.strides[w] < 0 ? S = -C : S = C, T = !0), T) {
let F;
S === 0 || S < 0 != d.strides[w] < 0 ? F = 0 : F = Math.trunc(S / d.strides[w]) + (S % d.strides[w] !== 0 ? 1 : 0), g.push(F);
} else
g.push(-1);
}
for (let w = 0; w < d.finalShapeGatherIndices.length; ++w) {
const y = d.finalShapeGatherIndices[w];
y >= 0 ? x.push(g[y]) : y === qc && x.push(1);
}
return {
finalShapeSparse: x.filter((w, y) => d.finalShapeGatherIndices[y] !== qc),
finalShape: x,
isIdentity: p,
sliceDim0: f,
isSimpleSlice: m,
begin: d.begin,
end: d.end,
strides: d.strides
};
}
function Gv(n, t) {
t.beginMask = 0, t.endMask = 0, t.shrinkAxisMask = 0;
let e = 0;
t.beginValid = n.begin != null, t.endValid = n.end != null, t.begin = new Array(t.dims), t.end = new Array(t.dims), t.strides = new Array(t.dims), t.finalShapeGatherIndices = [], t.finalShapeGatherIndicesSparse = [], t.inputShapeGatherIndicesSparse = new Array(t.dims);
for (let s = 0; s < n.dims; s++)
if (1 << s & n.ellipsisMask) {
const o = Math.min(t.dims - (n.dims - s) + 1 + n.numAddAxisAfterEllipsis, t.dims);
for (; e < o; e++)
t.begin[e] = 0, t.end[e] = 0, t.strides[e] = 1, t.beginMask |= 1 << e, t.endMask |= 1 << e, t.finalShapeGatherIndices.push(e), t.finalShapeGatherIndicesSparse.push(-1), t.inputShapeGatherIndicesSparse[e] = s;
} else if (1 << s & n.newAxisMask)
t.finalShapeGatherIndices.push(qc), t.finalShapeGatherIndicesSparse.push(-1);
else {
if (e === t.begin.length)
throw Error(`Index out of range using input dim ${e}; input has only ${t.dims} dims, ${t.begin.length}.`);
n.begin != null && (t.begin[e] = n.begin[s]), n.end != null && (t.end[e] = n.end[s]), t.strides[e] = n.strides[s], n.beginMask & 1 << s && (t.beginMask |= 1 << e), n.endMask & 1 << s && (t.endMask |= 1 << e), n.shrinkAxisMask & 1 << s ? (t.finalShapeGatherIndices.push(Vv), t.finalShapeGatherIndicesSparse.push(-1), t.shrinkAxisMask |= 1 << e) : (t.finalShapeGatherIndices.push(e), t.finalShapeGatherIndicesSparse.push(s)), t.inputShapeGatherIndicesSparse[e] = s, e++;
}
}
function yp(n, t, e, s, o, r) {
if (o[t])
return e > 0 ? r[t] : r[t + 1 & 1];
{
const i = n < 0 ? s + n : n;
return i < r[0] ? r[0] : i > r[1] ? r[1] : i;
}
}
const Hv = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
assertParamsValid: Hh,
computeFlatOffset: Xh,
computeOutShape: Kh,
getNormalizedAxes: Uv,
isSliceContinous: jh,
maskToAxes: Wv,
parseSliceParams: Wl,
sliceInfo: qh,
startForAxis: Ig,
startIndicesWithElidedDims: wg,
stopForAxis: kg,
stopIndicesWithElidedDims: Cg,
stridesForAxis: $g,
stridesWithElidedDims: xg
}, Symbol.toStringTag, { value: "Module" }));
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Kv {
/**
* 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(t) {
return new Uh(t);
}
/**
* 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(t, e, s = !1) {
return new mg(t, e, s);
}
/**
* 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(t, e = 0.9, s = 0, o = null, r = !1) {
return new gg(t, e, s, o, r);
}
/**
* 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(t = 1e-3, e = 0.9, s = 0.999, o = null) {
return new pg(t, e, s, o);
}
/**
* 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(t = 1e-3, e = 0.95, s = null) {
return new hg(t, e, s);
}
/**
* 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(t = 2e-3, e = 0.9, s = 0.999, o = null, r = 0) {
return new fg(t, e, s, o, r);
}
/**
* 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(t, e = 0.1) {
return new dg(t, e);
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const fo = Kv;
/**
* @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.
* =============================================================================
*/
const jv = (() => typeof requestAnimationFrame < "u" ? requestAnimationFrame : typeof setImmediate < "u" ? setImmediate : (n) => n())();
function vg() {
return new Promise((n) => jv(() => n()));
}
/**
* @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.
* =============================================================================
*/
function Yh(n, t) {
const e = n[0].length;
n.forEach((o, r) => {
I(o.length === e, () => `Error in concat${e}D: rank of tensors[${r}] must be the same as the rank of the rest (${e})`);
}), I(t >= 0 && t < e, () => `Error in concat${e}D: axis must be between 0 and ${e - 1}.`);
const s = n[0];
n.forEach((o, r) => {
for (let i = 0; i < e; i++)
I(i === t || o[i] === s[i], () => `Error in concat${e}D: Shape of tensors[${r}] (${o}) does not match the shape of the rest (${s}) along the non-concatenated axis ${r}.`);
});
}
function An(n, t) {
const e = n[0].slice();
for (let s = 1; s < n.length; s++)
e[t] += n[s][t];
return e;
}
/**
* @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 mn;
(function(n) {
n[n.FIRST_DIM_SIZE = 0] = "FIRST_DIM_SIZE", n[n.VALUE_ROWIDS = 1] = "VALUE_ROWIDS", n[n.ROW_LENGTHS = 2] = "ROW_LENGTHS", n[n.ROW_SPLITS = 3] = "ROW_SPLITS", n[n.ROW_LIMITS = 4] = "ROW_LIMITS", n[n.ROW_STARTS = 5] = "ROW_STARTS";
})(mn || (mn = {}));
function Sg(n, t, e) {
let s = new Array();
if (e == null && t == null)
return s;
if (t == null)
for (; s.length < n + e.length; )
s.push(-1);
else
s = t.slice();
if (e == null)
return s;
if (n + e.length !== s.length)
throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${n + e.length}, but shape.rank = ${s.length}`);
for (let o = 1; o < e.length; ++o) {
const r = e[o], i = s[s.length - e.length + o], a = s[i];
if (r >= 0)
if (a >= 0) {
if (a !== r)
throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${o + n}] = ${r} but shape[${o + n}] = ${a}`);
} else
s[i] = r;
}
return s;
}
function Ng(n) {
const t = {
FIRST_DIM_SIZE: mn.FIRST_DIM_SIZE,
VALUE_ROWIDS: mn.VALUE_ROWIDS,
ROW_LENGTHS: mn.ROW_LENGTHS,
ROW_SPLITS: mn.ROW_SPLITS,
ROW_LIMITS: mn.ROW_LIMITS,
ROW_STARTS: mn.ROW_STARTS
}, e = [];
for (const s of n)
if (s in t)
e.push(t[s]);
else
break;
return e;
}
function Tg(n) {
return n.length === 0 ? 0 : n[0] === mn.FIRST_DIM_SIZE ? n.length - 1 : n.length;
}
function Eg(n, t) {
if (n == null || t == null)
return;
const e = n.length, s = t.length;
if (e >= s)
throw new Error(`defaultValue.shape=${n} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${e} must be less than ragged tensor input flatValues.rank = ${s})`);
for (let o = 0; o < Math.min(e, s - 1); ++o) {
const r = n[o], i = t[o + 1];
if (r >= 0 && i >= 0 && r !== 1 && r !== i)
throw new Error(`defaultValue.shape=${n}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${o - n.length}] = ${r} but ragged tensor input.flatValues.shape[${o - n.length}] = ${i}`);
}
}
/**
* @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.
* =============================================================================
*/
const Jh = 30;
function Ul(n) {
return n <= Jh ? n : Ac(n, Math.floor(Math.sqrt(n)));
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Zh(n, t, e) {
const s = e * (typeof n == "number" ? n : n[0]), o = t * (typeof n == "number" ? n : n[1]);
return [s, o];
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Si(n, t, e, s = !0) {
let o = [];
if (s)
o = o.concat(t.slice(0)), o.push(n[0] / e), o = o.concat(n.slice(1));
else {
o = o.concat(n[0]);
const r = t.length;
for (let i = 0; i < r; ++i)
o = o.concat([n[i + 1] / t[i], t[i]]);
o = o.concat(n.slice(r + 1));
}
return o;
}
function Ni(n, t, e = !0) {
const s = [];
if (e) {
s.push(t);
for (let o = t + 1; o < n; ++o)
o <= 2 * t ? (s.push(o), s.push(o - (t + 1))) : s.push(o);
} else {
const o = [], r = [];
for (let i = 1; i < n; ++i)
i >= t * 2 + 1 || i % 2 === 1 ? r.push(i) : o.push(i);
s.push(...o), s.push(0), s.push(...r);
}
return s;
}
function Ti(n, t, e, s = !0) {
const o = [];
s ? o.push(n[0] / e) : o.push(n[0] * e);
for (let r = 1; r < n.length; ++r)
r <= t.length ? s ? o.push(t[r - 1] * n[r]) : o.push(n[r] / t[r - 1]) : o.push(n[r]);
return o;
}
function Qh(n, t) {
const e = [0];
for (let s = 0; s < t; ++s)
e.push(n[s][0]);
return e;
}
function td(n, t, e) {
const s = n.slice(0, 1);
for (let o = 0; o < e; ++o)
s.push(n[o + 1] - t[o][0] - t[o][1]);
return s;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Gl = 1.7580993408473768, Hl = 1.0507009873554805;
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ed = 0.3275911, nd = 0.254829592, sd = -0.284496736, od = 1.421413741, rd = -1.453152027, id = 1.061405429;
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function qn(n, t) {
if (n.length !== t.length)
throw new Error(`Cannot merge real and imag arrays of different lengths. real:${n.length}, imag: ${t.length}.`);
const e = new Float32Array(n.length * 2);
for (let s = 0; s < e.length; s += 2)
e[s] = n[s / 2], e[s + 1] = t[s / 2];
return e;
}
function Rg(n) {
const t = new Float32Array(n.length / 2), e = new Float32Array(n.length / 2);
for (let s = 0; s < n.length; s += 2)
t[s / 2] = n[s], e[s / 2] = n[s + 1];
return { real: t, imag: e };
}
function Dg(n) {
const t = Math.ceil(n.length / 4), e = new Float32Array(t), s = new Float32Array(t);
for (let o = 0; o < n.length; o += 4)
e[Math.floor(o / 4)] = n[o], s[Math.floor(o / 4)] = n[o + 1];
return { real: e, imag: s };
}
function Ag(n) {
const t = Math.floor(n.length / 4), e = new Float32Array(t), s = new Float32Array(t);
for (let o = 2; o < n.length; o += 4)
e[Math.floor(o / 4)] = n[o], s[Math.floor(o / 4)] = n[o + 1];
return { real: e, imag: s };
}
function ad(n, t) {
const e = n[t * 2], s = n[t * 2 + 1];
return { real: e, imag: s };
}
function Fg(n, t, e, s) {
n[s * 2] = t, n[s * 2 + 1] = e;
}
function Og(n, t) {
const e = new Float32Array(n / 2), s = new Float32Array(n / 2);
for (let o = 0; o < Math.ceil(n / 2); o++) {
const r = (t ? 2 : -2) * Math.PI * (o / n);
e[o] = Math.cos(r), s[o] = Math.sin(r);
}
return { real: e, imag: s };
}
function _g(n, t, e) {
const s = (e ? 2 : -2) * Math.PI * (n / t), o = Math.cos(s), r = Math.sin(s);
return { real: o, imag: r };
}
/**
* @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.
* =============================================================================
*/
const gc = "->", Xv = /->/g, wp = ",", Cp = "...";
function ld(n, t) {
n = n.replace(/\s/g, "");
const e = (n.length - n.replace(Xv, "").length) / gc.length;
if (e < 1)
throw new Error("Equations without an arrow are not supported.");
if (e > 1)
throw new Error(`Equation must contain exactly one arrow ("${gc}").`);
const [s, o] = n.split(gc);
I(s.indexOf(Cp) === -1, () => `The ellipsis notation ("${Cp}") is not supported yet.`);
const r = s.split(wp), i = r.length;
if (t !== i)
throw new Error(`Expected ${i} input tensors, received ${t}`);
if (i > 2)
throw new Error("Support for more than 2 input tensors is not implemented yet.");
const a = [];
for (let d = 0; d < o.length; ++d) {
const p = o[d];
if (!r.some((f) => f.indexOf(p) !== -1))
throw new Error(`Output subscripts contain the label ${p} not present in the input subscripts.`);
a.indexOf(p) === -1 && a.push(p);
}
for (let d = 0; d < s.length; ++d) {
const p = s[d];
a.indexOf(p) === -1 && p !== wp && a.push(p);
}
const l = new Array(r.length);
for (let d = 0; d < i; ++d) {
if (new Set(r[d].split("")).size !== r[d].length)
throw new Error(`Found duplicate axes in input component ${r[d]}. Support for duplicate axes in input is not implemented yet.`);
l[d] = [];
for (let p = 0; p < r[d].length; ++p)
l[d].push(a.indexOf(r[d][p]));
}
const c = a.length, u = o.length, h = [];
for (let d = u; d < c; ++d)
h.push(d);
return { allDims: a, summedDims: h, idDims: l };
}
function cd(n, t) {
let e = new Array(n);
e.fill(-1);
for (let o = 0; o < t.length; ++o)
e[t[o]] = o;
const s = [];
for (let o = 0; o < n; ++o)
e[o] === -1 && s.push(o);
return e = e.filter((o) => o !== -1), { permutationIndices: e, expandDims: s };
}
function ud(n, t, e) {
const s = new Array(n);
for (let o = 0; o < e.length; ++o) {
const r = e[o].shape;
for (let i = 0; i < t[o].length; ++i)
s[t[o][i]] === void 0 ? s[t[o][i]] = r[i] : I(s[t[o][i]] === r[i], () => `Expected dimension ${s[t[o][i]]} at axis ${i} of input shaped ${JSON.stringify(r)}, but got dimension ${r[i]}`);
}
}
function hd(n, t) {
const e = n, s = [];
let o = 0;
n.length === 0 && e.push(-1), o = n.length + 1;
for (let i = 0; i < o; ++i)
s.push([]);
const r = [];
for (let i = 0; i < e.length; ++i) {
const a = e[i], l = qv(t, a);
for (const c of l)
r.indexOf(c) === -1 && (s[i].push(c), r.push(c));
}
return { path: e, steps: s };
}
function dd(n) {
return n.every((t, e) => t === e);
}
function qv(n, t) {
const e = [];
for (let s = 0; s < n.length; ++s)
(n[s].length === 0 || n[s].indexOf(t) !== -1 || t === -1) && e.push(s);
return e;
}
function pd(n, t, e = 0) {
let s = [];
if (typeof t == "number")
I(n.shape[e] % t === 0, () => "Number of splits must evenly divide the axis."), s = new Array(t).fill(n.shape[e] / t);
else {
const o = t.reduce((i, a) => (a === -1 && (i += 1), i), 0);
I(o <= 1, () => "There should be only one negative value in split array.");
const r = t.indexOf(-1);
if (r !== -1) {
const i = t.reduce((a, l) => l > 0 ? a + l : a);
t[r] = n.shape[e] - i;
}
I(n.shape[e] === t.reduce((i, a) => i + a), () => "The sum of sizes must match the size of the axis dimension."), s = t;
}
return s;
}
/**
* @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.
* =============================================================================
*/
function Lg(n) {
return `Received SparseTensor with denseShape[0] = 0 but
indices.shape[0] = ${n}`;
}
function Mg(n, t) {
return `indices(${n}, 0) is invalid: ${t} < 0`;
}
function Pg(n, t, e) {
return `indices(${n}, 0) is invalid: ${t} >= ${e}`;
}
/**
* @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.
* =============================================================================
*/
function zg(n, t) {
return `only one output dimension may be -1, not both ${n} and ${t}`;
}
function Bg(n, t) {
return `size ${n} must be non-negative, not ${t}`;
}
function Vg() {
return "reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero";
}
function Wg(n, t) {
const e = G(n), s = G(t);
return `Input to reshape is a SparseTensor with ${e}
dense values, but the requested shape requires a multiple of ${s}. inputShape=${n} outputShape= ${t}`;
}
function Ug(n, t) {
const e = G(n), s = G(t);
return `Input to reshape is a tensor with ${e} dense values, but the requested shape has ${s}. inputShape=${n} outputShape=${t}`;
}
/**
* @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.
* =============================================================================
*/
function Yc() {
return "segment ids must be >= 0";
}
function Gg() {
return "segment ids are not increasing";
}
function Hg(n, t) {
return `Segment id ${n} out of range [0, ${t}), possibly because segmentIds input is not sorted.`;
}
function Kg(n, t, e) {
return `Bad: indices[${n}] == ${t} out of range [0, ${e})`;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function jg(n, t) {
let e = !1, s;
for (n <= Jh ? (s = n, e = !0) : s = Ac(n, Math.floor(Math.sqrt(n))); !e; )
s > t || s === n ? e = !0 : s = Ac(n, s + 1);
return s;
}
function Xg(n, t, e) {
const s = [], o = n.length;
for (let r = 0; r < o; r++)
r !== t ? s.push(n[r]) : s.push(e);
return s;
}
function fd(n, t, e, s) {
const o = t.shape.length, r = n.shape.length;
if (s !== 0 && (s < -o || s > o))
throw new Error(`Expect batchDims in the range of [-${o}, ${o}], but got ${s}`);
if (s < 0 && (s += o), s > r)
throw new Error(`batchDims (${s}) must be less than rank(x) (
${r}).`);
if (e < s)
throw new Error(`batchDims (${s}) must be less than or equal to axis (${e}).`);
for (let h = 0; h < s; ++h)
if (n.shape[h] !== t.shape[h])
throw new Error(`x.shape[${h}]: ${n.shape[h]} should be equal to indices.shape[${h}]: ${t.shape[h]}.`);
const i = n.shape[e], a = [];
let l = 1, c = 1, u = 1;
for (let h = 0; h < s; ++h)
a.push(n.shape[h]), l *= n.shape[h];
for (let h = s; h < e; h++)
a.push(n.shape[h]), c *= n.shape[h];
for (let h = s; h < o; h++)
a.push(t.shape[h]);
for (let h = e + 1; h < r; h++)
a.push(n.shape[h]), u *= n.shape[h];
return { batchSize: l, sliceSize: u, outerSize: c, dimSize: i, outputShape: a };
}
const Yv = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
collectGatherOpShapeInfo: fd,
computeOutShape: Xg,
segOpComputeOptimalWindowSize: jg
}, Symbol.toStringTag, { value: "Module" }));
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Yn(n) {
try {
return n.map((t) => ps(t));
} catch (t) {
throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`);
}
}
function qg(n) {
return n.map((t) => us(t));
}
const Jv = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
ERF_A1: nd,
ERF_A2: sd,
ERF_A3: od,
ERF_A4: rd,
ERF_A5: id,
ERF_P: ed,
PARALLELIZE_THRESHOLD: Jh,
get RowPartitionType() {
return mn;
},
SELU_SCALE: Hl,
SELU_SCALEALPHA: Gl,
applyActivation: Mh,
assertAndGetBroadcastShape: mt,
assertAxesAreInnerMostDims: be,
assertParamsConsistent: Yh,
assignToTypedArray: Fg,
axesAreInnerMostDims: Ch,
calculateShapes: io,
checkEinsumDimSizes: ud,
checkPadOnDimRoundingMode: ze,
combineLocations: Vm,
combineRaggedTensorToTensorShapes: Sg,
complexWithEvenIndex: Dg,
complexWithOddIndex: Ag,
computeConv2DInfo: xe,
computeConv3DInfo: Cs,
computeDefaultPad: mh,
computeDilation2DInfo: Ci,
computeOptimalWindowSize: Ul,
computeOutAndReduceShapes: pe,
computeOutShape: An,
computePool2DInfo: ln,
computePool3DInfo: Zn,
convertConv2DDataFormat: Qn,
decodeEinsumEquation: ld,
eitherStridesOrDilationsAreOne: Ie,
expandShapeToKeepDim: ne,
exponent: _g,
exponents: Og,
fromStringArrayToUint8: qg,
fromUint8ToStringArray: Yn,
getAxesPermutation: jt,
getBroadcastDims: To,
getComplexWithIndex: ad,
getEinsumComputePath: hd,
getEinsumPermutation: cd,
getFusedBiasGradient: Lh,
getFusedDyActivation: _h,
getImageCenter: Zh,
getInnerMostAxes: Zt,
getPermuted: Ni,
getRaggedRank: Tg,
getReductionAxes: le,
getReshaped: Si,
getReshapedPermuted: Ti,
getRowPartitionTypesHelper: Ng,
getSliceBeginCoords: Qh,
getSliceSize: td,
getSparseFillEmptyRowsIndicesDenseShapeMismatch: Lg,
getSparseFillEmptyRowsNegativeIndexErrorMessage: Mg,
getSparseFillEmptyRowsOutOfRangeIndexErrorMessage: Pg,
getSparseReshapeEmptyTensorZeroOutputDimErrorMessage: Vg,
getSparseReshapeInputOutputMismatchErrorMessage: Ug,
getSparseReshapeInputOutputMultipleErrorMessage: Wg,
getSparseReshapeMultipleNegativeOneOutputDimErrorMessage: zg,
getSparseReshapeNegativeOutputDimErrorMessage: Bg,
getSparseSegmentReductionIndicesOutOfRangeErrorMessage: Kg,
getSparseSegmentReductionNegativeSegmentIdsErrorMessage: Yc,
getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage: Gg,
getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage: Hg,
getUndoAxesPermutation: $s,
isIdentityPermutation: dd,
log: Z1,
mergeRealAndImagArrays: qn,
prepareAndValidate: Gh,
prepareSplitSize: pd,
segment_util: Yv,
shouldFuse: Ph,
slice_util: Hv,
splitRealAndImagArrays: Rg,
stridesOrDilationsArePositive: Ks,
tupleValuesAreOne: Hs,
upcastType: Ue,
validateDefaultValueShape: Eg,
validateInput: Tk,
validateUpdateShape: rg,
warn: je
}, Symbol.toStringTag, { value: "Module" }));
/**
* @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.
* =============================================================================
*/
Bv();
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Yg = {
kernelName: Fa,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(n, vi(st(e, "float32"), -1)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Zv = {
kernelName: Sr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return {
x: () => {
const s = Vt(st(e, "float32")), o = $e(pt(Tt(1), s));
return Yt(ut(n, o));
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Qv = {
kernelName: Nr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return {
x: () => {
const s = $e(pt(Vt(st(e, "float32")), 1));
return ut(n, s);
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const tS = {
kernelName: Po,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t, o = mt(e.shape, s.shape);
return { a: () => {
let a = n;
const l = le(e.shape, o);
return l.length > 0 && (a = ct(a, l)), A(a, e.shape);
}, b: () => {
let a = n;
const l = le(s.shape, o);
return l.length > 0 && (a = ct(a, l)), A(a, s.shape);
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const eS = {
kernelName: Su,
saveAllInputs: !0,
gradFunc: (n, t) => {
const e = {};
return t.forEach((s, o) => {
e[o] = () => n.clone();
}), e;
}
};
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const nS = {
kernelName: Oa,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => kt(e) };
}
};
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sS = {
kernelName: _a,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => kt(e) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const oS = {
kernelName: Tr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => ut(n, $e(pt(Tt(1), Vt(st(e, "float32"))))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const rS = {
kernelName: Er,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return {
x: () => {
const s = $e(Y(Tt(1), Vt(st(e, "float32"))));
return ut(n, s);
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const iS = {
kernelName: Ar,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t, o = mt(e.shape, s.shape);
return { a: () => {
const a = Y(Vt(e), Vt(s));
let l = R(n, ut(s, a));
const c = le(e.shape, o);
return c.length > 0 && (l = ct(l, c)), A(l, e.shape);
}, b: () => {
const a = Y(Vt(e), Vt(s));
let l = Yt(R(n, ut(e, a)));
const c = le(s.shape, o);
return c.length > 0 && (l = ct(l, c)), A(l, s.shape);
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const aS = {
kernelName: Rr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => ut(n, Y(Vt(st(e, "float32")), 1)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const lS = {
kernelName: Dr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => ut(n, pt(Tt(1), Vt(st(e, "float32")))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function cS(n, t, e, s, o, r) {
const i = N(n, "dy", "avgPool3dGrad"), a = N(t, "input", "avgPool3dGrad");
let l = i, c = a, u = !1;
a.rank === 4 && (u = !0, l = A(i, [1, i.shape[0], i.shape[1], i.shape[2], i.shape[3]]), c = A(a, [
1,
a.shape[0],
a.shape[1],
a.shape[2],
a.shape[3]
])), I(l.rank === 5, () => `Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`), I(c.rank === 5, () => `Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`), ze("avgPool3dGrad", o, r);
const h = { dy: l, input: c }, d = { filterSize: e, strides: s, pad: o, dimRoundingMode: r }, p = D.runKernel(Ru, h, d);
return u ? A(p, [p.shape[1], p.shape[2], p.shape[3], p.shape[4]]) : p;
}
const uS = /* @__PURE__ */ O({ avgPool3dGrad_: cS });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const hS = {
kernelName: Ma,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { filterSize: o, strides: r, pad: i, dimRoundingMode: a } = e;
return {
x: () => uS(n, s, o, r, i, a)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function dS(n, t, e, s, o) {
const r = N(n, "dy", "avgPoolGrad"), i = N(t, "input", "avgPoolGrad");
I(i.rank === r.rank, () => `Rank of input (${i.rank}) does not match rank of dy (${r.rank})`);
let a = i, l = r, c = !1;
i.rank === 3 && (c = !0, a = A(i, [1, i.shape[0], i.shape[1], i.shape[2]]), l = A(r, [1, r.shape[0], r.shape[1], r.shape[2]])), I(l.rank === 4, () => `Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`), I(a.rank === 4, () => `Error in avgPoolGrad: input must be rank 4 but got rank ${a.rank}.`);
const u = { dy: l, input: a }, h = { filterSize: e, strides: s, pad: o }, d = D.runKernel(Eu, u, h);
return c ? A(d, [d.shape[1], d.shape[2], d.shape[3]]) : d;
}
const pS = /* @__PURE__ */ O({ avgPoolGrad_: dS });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const fS = {
kernelName: La,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { filterSize: o, strides: r, pad: i } = e;
return { x: () => pS(n, s, o, r, i) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const mS = {
kernelName: Pa,
inputsToSave: ["a", "b"],
gradFunc: (n, t, e) => {
const [s, o] = t, { transposeA: r, transposeB: i } = e;
return !r && !i ? {
a: () => Nt(n, o, !1, !0),
b: () => Nt(s, n, !0, !1)
} : !r && i ? {
a: () => Nt(n, o, !1, !1),
b: () => Nt(n, s, !0, !1)
} : r && !i ? {
a: () => Nt(o, n, !1, !0),
b: () => Nt(s, n, !1, !1)
} : {
a: () => Nt(o, n, !0, !0),
b: () => Nt(n, s, !0, !0)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const gS = {
kernelName: za,
gradFunc: (n, t, e) => {
const { blockShape: s, crops: o } = e;
return { x: () => Eh(n, s, o) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const xS = {
kernelName: X1,
gradFunc: (n, t, e) => {
const s = e, o = s.inputShape, r = s.shape, i = Array.from(r);
for (let l = o.length - 1; l >= 0; l--)
if (o[l] === r[l])
i[l] = 1;
else if (o[l] !== 1)
throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${r}].`);
const a = [];
for (let l = 0; l < i.length; l++)
i[l] > 1 && a.push(l);
return { x: () => ct(
n,
a,
!0
/* keepDims */
) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const bS = {
kernelName: Fr,
gradFunc: (n) => ({ x: () => n.clone() })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const yS = {
kernelName: Or,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const wS = {
kernelName: _r,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { clipValueMin: o, clipValueMax: r } = e;
return {
x: () => Re(jn(oo(s, o), Vo(s, r)), n, kt(n))
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const CS = {
kernelName: Ba,
inputsToSave: ["x"],
gradFunc: Yg.gradFunc
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const $S = {
kernelName: Va,
saveAllInputs: !0,
gradFunc: (n, t, e) => {
const s = t.map((l) => l.shape), { axis: o } = e, r = wt(o, t[0].shape)[0], i = s.map((l) => l[r]);
return qe(n, i, r).map((l) => () => l);
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const IS = {
kernelName: Wa,
inputsToSave: ["x", "filter"],
gradFunc: (n, t, e) => {
const [s, o] = t, { dilations: r, strides: i, pad: a, dataFormat: l } = e;
return I(Hs(r), () => `Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`), {
x: () => bh(s.shape, n, o, i, a, l),
filter: () => Oh(s, n, o.shape, i, a, l)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const kS = {
kernelName: Ua,
inputsToSave: ["dy", "filter"],
gradFunc: (n, t, e) => {
const [s, o] = t, { strides: r, pad: i, dataFormat: a, dimRoundingMode: l } = e;
return {
dy: () => js(n, o, r, i, a, 1, l),
filter: () => Oh(n, s, o.shape, r, i, a, l)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function vS(n, t, e, s, o) {
let r = n;
n.rank === 4 && (r = A(n, [1, n.shape[0], n.shape[1], n.shape[2], n.shape[3]]));
let i = t;
i.rank === 4 && (i = A(t, [1, t.shape[0], t.shape[1], t.shape[2], t.shape[3]])), I(r.rank === 5, () => `Error in conv3dDerFilter: input must be rank 5, but got shape ${r.shape}.`), I(i.rank === 5, () => `Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`), I(e.length === 5, () => `Error in conv3dDerFilter: filterShape must be length 5, but got ${e}.`), I(r.shape[4] === e[3], () => `Error in conv3dDerFilter: depth of input ${r.shape[4]}) must match input depth in filter (${e[3]}.`), I(i.shape[4] === e[4], () => `Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${e[4]}).`);
const a = { x: r, dy: i }, l = { strides: s, pad: o, filterShape: e };
return D.runKernel(_u, a, l);
}
const SS = /* @__PURE__ */ O({ conv3DBackpropFilter_: vS });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const NS = {
kernelName: Ga,
inputsToSave: ["x", "filter"],
gradFunc: (n, t, e) => {
const { dilations: s, strides: o, pad: r } = e;
I(Hs(s), () => `Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);
const [i, a] = t;
return {
x: () => Mm(i.shape, n, a, o, r),
filter: () => SS(i, n, a.shape, o, r)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const TS = {
kernelName: Lr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(Yt(eg(st(e, "float32"))), n) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ES = {
kernelName: Mr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(ng(st(e, "float32")), n) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const RS = {
kernelName: Ha,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { axis: o, exclusive: r, reverse: i } = e;
return {
x: () => {
const a = jt([o], s.rank);
let l = zm(n, o, r, !i);
return a != null && (l = It(l, a)), l;
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const DS = {
kernelName: Ka,
inputsToSave: ["x", "filter"],
gradFunc: (n, t, e) => {
const { dilations: s, strides: o, pad: r, dimRoundingMode: i } = e, a = s ?? [1, 1];
I(Hs(a), () => `Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);
const [l, c] = t;
return I(l.rank === 4, () => `Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`), I(c.rank === 4, () => `Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`), I(l.shape[3] === c.shape[2], () => `Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`), I(Ie(o, a), () => `Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${a}'.`), ze("depthwiseConv2d", r, i), {
x: () => jk(l.shape, n, c, o, r, a, i),
filter: () => Hk(l, n, c.shape, o, r, a, i)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const AS = {
kernelName: ja,
inputsToSave: ["x", "filter"],
gradFunc: (n, t, e) => {
const [s, o] = t, r = { x: s, filter: o, dy: n }, i = { x: s, filter: o, dy: n };
return {
x: () => D.runKernel(Fc, r, e),
filter: () => D.runKernel(Oc, i, e)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const FS = {
kernelName: zr,
outputsToSave: [!0],
gradFunc: (n, t) => {
const [e] = t, s = { dy: n, y: e };
return { x: () => D.runKernel(Gu, s) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const OS = {
kernelName: Br,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t, s = R(Ln(Yt(Vt(e))), 2 / Math.sqrt(Math.PI));
return { x: () => R(n, s) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const _S = {
kernelName: Vr,
outputsToSave: [!0],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(n, e) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const LS = {
kernelName: qa,
inputsToSave: ["input"],
gradFunc: (n, t) => {
const [e] = t;
return { input: () => A(n, e.shape) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const MS = {
kernelName: Wr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(n, Ln(e)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const PS = {
kernelName: Ur,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const zS = {
kernelName: Gr,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t, o = mt(e.shape, s.shape);
return { a: () => {
const a = ut(n, st(s, "float32")), l = le(e.shape, o);
return l.length > 0 ? A(ct(a, l), e.shape) : a;
}, b: () => {
let a = R(n, st(e, "float32"));
const l = le(s.shape, o);
l.length > 0 && (a = A(ct(a, l), s.shape));
const c = Vt(s);
return Yt(ut(a, st(c, "float32")));
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const BS = {
kernelName: Ya,
inputsToSave: ["x", "mean", "variance", "scale"],
gradFunc: (n, t, e) => {
const { varianceEpsilon: s } = e, [o, r, i, a] = t, l = a ?? Tt(1), c = le(r.shape, o.shape), u = [];
if (r.rank === 1) {
for (let y = 0; y < o.shape.length - 1; ++y)
u.push(o.shape[y]);
u.push(1);
}
const h = pt(o, r), d = R(n, l), p = Zm(Y(i, Tt(s))), f = R(R(R(p, p), p), Tt(-0.5));
return {
x: () => r.rank === 1 ? A(R(R(n, gn(A(p, [1, 1, 1, r.shape[0]]), u)), l), o.shape) : A(R(R(n, p), l), o.shape),
mean: () => {
let y = R(R(p, Tt(-1)), d);
return r.rank === 1 && (y = ct(y, c)), A(y, r.shape);
},
variance: () => {
let y = R(R(f, h), d);
return r.rank === 1 && (y = ct(y, c)), A(y, r.shape);
},
scale: () => {
const y = R(h, p);
let C = R(n, y);
return r.rank === 1 && (C = ct(C, c)), A(C, r.shape);
},
offset: () => {
let y = n;
return r.rank === 1 && (y = ct(y, c)), A(y, r.shape);
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const VS = {
kernelName: Ja,
inputsToSave: ["x", "indices"],
gradFunc: (n, t, e) => {
const [s, o] = t, { axis: r, batchDims: i } = e, a = wt(r, s.shape)[0], l = (c, u, h) => () => {
const d = c.shape, p = u.size, f = d.slice(0, a), m = f.length, g = d.slice(r, d.length).slice(1), x = g.length, b = $p(0, m), w = $p(m + 1, m + 1 + x), y = Ip([
f,
[p],
g
]), C = A(h, y), $ = A(u, [p]), k = Ip([[m], b, w]), v = It(C, k);
let S = ag(v, $, c.shape[a]);
const T = $s(k);
return S = It(S, T), S;
};
if (i === 1) {
const c = s.shape[0], u = s.split(c, 0);
return { x: () => Xn(u.map((p, f) => l(p, o.slice(f, 1), n.slice(f, 1))())).reshape(s.shape), indices: () => o };
} else
return { x: l(s, o, n), indices: () => o };
}
};
function $p(n, t) {
const e = [];
for (let s = n; s < t; ++s)
e.push(s);
return e;
}
function Ip(n) {
const t = [];
for (let e = 0; e < n.length; ++e)
for (let s = 0; s < n[e].length; ++s)
t.push(n[e][s]);
return t;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const WS = {
kernelName: Hr,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t;
return { a: () => kt(e), b: () => kt(s) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const US = {
kernelName: Kr,
gradFunc: (n) => ({ x: () => st(n, "float32") })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const GS = {
kernelName: jr,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const HS = {
kernelName: Xr,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const KS = {
kernelName: qr,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const jS = {
kernelName: Qa,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { alpha: o } = e, r = Je(s, 0);
return { x: () => Re(r, n, R(n, o)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const XS = {
kernelName: Jr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => ut(n, Y(e, 1)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const qS = {
kernelName: Yr,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => ut(n, st(e, "float32")) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const YS = {
kernelName: Y1,
inputsToSave: [],
outputsToSave: [!0],
gradFunc: (n, t, e) => {
const [s] = t, { axis: o } = e;
return {
logits: () => {
const i = Ln(s);
return pt(n, R(ct(n, o, !0), i));
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function JS(n, t, e, s = 5, o = 1, r = 1, i = 0.5) {
const a = { x: n, y: t, dy: e }, l = { depthRadius: s, bias: o, alpha: r, beta: i };
return D.runKernel(Yu, a, l);
}
const ZS = O({ localResponseNormalizationBackprop_: JS });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const QS = {
kernelName: rl,
inputsToSave: ["x"],
outputsToSave: [!0],
gradFunc: (n, t, e) => {
const [s, o] = t, { depthRadius: r, bias: i, alpha: a, beta: l } = e;
return {
x: () => ZS(s, o, n, r, i, a, l)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Jg(n, t, e, s) {
return t.rank < e.rank && (t = A(t, ne(t.shape, s))), n.rank < e.rank && (n = A(n, ne(n.shape, s))), {
x: () => R(n, st(_n(e, t), n.dtype))
};
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const kp = {
kernelName: il,
inputsToSave: ["x"],
outputsToSave: [!0],
gradFunc: (n, t, e) => {
const s = e, { reductionIndices: o } = s, r = t[0], i = t[1], a = wt(o, r.shape), l = Jg(n, i, r, a);
return {
x: () => l.x()
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const tN = {
kernelName: Zr,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t;
return { a: () => R(n, st(oo(e, s), "float32")), b: () => R(n, st(ha(e, s), "float32")) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function eN(n, t, e, s, o, r, i) {
const a = N(n, "dy", "maxPool3dGrad"), l = N(t, "input", "maxPool3dGrad"), c = N(e, "output", "maxPool3dGrad");
let u = a, h = l, d = c, p = !1;
l.rank === 4 && (p = !0, u = A(a, [1, a.shape[0], a.shape[1], a.shape[2], a.shape[3]]), h = A(l, [
1,
l.shape[0],
l.shape[1],
l.shape[2],
l.shape[3]
]), d = A(c, [
1,
c.shape[0],
c.shape[1],
c.shape[2],
c.shape[3]
])), I(u.rank === 5, () => `Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`), I(h.rank === 5, () => `Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`), I(d.rank === 5, () => `Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`), ze("maxPool3dGrad", r, i);
const f = { dy: u, input: h, output: d }, m = { filterSize: s, strides: o, pad: r, dimRoundingMode: i }, g = D.runKernel(Zu, f, m);
return p ? A(g, [g.shape[1], g.shape[2], g.shape[3], g.shape[4]]) : g;
}
const nN = /* @__PURE__ */ O({ maxPool3dGrad_: eN });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sN = {
kernelName: ll,
inputsToSave: ["x"],
outputsToSave: [!0],
gradFunc: (n, t, e) => {
const [s, o] = t, { filterSize: r, strides: i, pad: a, dimRoundingMode: l } = e;
return {
x: () => nN(n, s, o, r, i, a, l)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function oN(n, t, e, s, o, r, i) {
const a = N(n, "dy", "maxPoolGrad"), l = N(t, "input", "maxPoolGrad"), c = N(e, "output", "maxPoolGrad");
I(l.rank === a.rank, () => `Rank of input (${l.rank}) does not match rank of dy (${a.rank})`), I(a.rank === 4, () => `Error in maxPoolGrad: dy must be rank 4 but got rank ${a.rank}.`), I(l.rank === 4, () => `Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`), ze("maxPoolGrad", r, i);
const u = { dy: a, input: l, output: c }, h = { filterSize: s, strides: o, pad: r, dimRoundingMode: i };
return D.runKernel(Ju, u, h);
}
const rN = /* @__PURE__ */ O({ maxPoolGrad_: oN });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const iN = {
kernelName: al,
inputsToSave: ["x"],
outputsToSave: [!0],
gradFunc: (n, t, e) => {
const [s, o] = t, { filterSize: r, strides: i, pad: a } = e;
return {
x: () => rN(n, s, o, r, i, a)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const aN = {
kernelName: cl,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { axis: o } = e, r = wt(o, s.shape), a = pe(s.shape, r)[1], l = G(a);
return { x: () => {
const u = s.shape.slice();
r.forEach((p) => {
u[p] = 1;
});
const h = A(n, u);
return ut(R(h, ks(s.shape, "float32")), l);
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const lN = {
kernelName: ul,
inputsToSave: ["x"],
outputsToSave: [!0],
gradFunc: (n, t, e) => {
const s = e, { axis: o } = s, [r, i] = t, a = wt(o, r.shape), l = Jg(n, i, r, a);
return {
x: () => l.x()
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const cN = {
kernelName: Qr,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t;
return { a: () => R(n, st(Vo(e, s), "float32")), b: () => R(n, st(Je(e, s), "float32")) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const uN = {
kernelName: hl,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const s = t[0], { paddings: o } = e, r = o.map((i) => i[0]);
return { x: () => zt(n, r, s.shape) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const hN = {
kernelName: ti,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t, o = mt(e.shape, s.shape);
return { a: () => {
const a = le(e.shape, o);
return a.length > 0 ? A(ct(n, a), e.shape) : n;
}, b: () => {
const a = R(n, Yt(Vl(ut(e, s)))), l = le(s.shape, o);
return l.length > 0 ? A(ct(a, l), s.shape) : a;
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const dN = {
kernelName: ei,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t, o = mt(e.shape, s.shape);
return { a: () => {
const a = R(n, st(s, "float32")), l = le(e.shape, o);
return l.length > 0 ? A(ct(a, l), e.shape) : a;
}, b: () => {
const a = R(n, st(e, "float32")), l = le(s.shape, o);
return l.length > 0 ? A(ct(a, l), s.shape) : a;
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const pN = {
kernelName: dl,
gradFunc: (n) => ({ x: () => Yt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const fN = {
kernelName: ml,
inputsToSave: ["indices"],
gradFunc: (n, t) => {
const e = t[0];
return { indices: () => he(e.shape, "float32") };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const mN = {
kernelName: fl,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const gN = {
kernelName: gl,
saveAllInputs: !0,
gradFunc: (n, t, e) => {
const { axis: s } = e;
return Ys(n, s).map((r) => () => r);
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const vp = {
kernelName: xl,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const s = t[0], { paddings: o } = e, r = o.map((i) => i[0]);
return { x: () => zt(n, r, s.shape) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const xN = {
kernelName: ni,
inputsToSave: ["a", "b"],
outputsToSave: [!0],
gradFunc: (n, t) => {
const [e, s, o] = t, r = e, i = s, a = mt(r.shape, i.shape);
return { a: () => {
const u = st(i, "float32");
let h = R(n, R(u, Xs(r, pt(u, Tt(1)))));
const d = le(r.shape, a);
return d.length > 0 && (h = ct(h, d)), A(h, r.shape);
}, b: () => {
const u = Je(r, 0), h = Re(u, Mn(r), kt(r));
let d = R(n, R(o, h));
const p = le(i.shape, a);
return p.length > 0 && (d = ct(d, p)), A(d, i.shape);
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const bN = {
kernelName: bl,
inputsToSave: ["x", "alpha"],
gradFunc: (n, t) => {
const [e, s] = t, o = Je(e, 0);
return {
x: () => Re(o, n, R(n, s)),
alpha: () => {
let r = Re(o, kt(n), R(n, e));
const i = le(s.shape, n.shape);
return i.length > 0 && (r = ct(r, i)), A(r, s.shape);
}
};
}
};
/**
* @license
* Copyright 2022 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yN(n, t, e) {
const s = n.shape.slice();
s[e] = 1;
const o = A(t, s), r = jc(n, e, !0, !1), i = jc(n, e, !0, !0), a = R(r, i);
return R(o, a);
}
function wN(n, t, e) {
const s = n.shape.length, o = s - e.length, r = jt(e, s);
let i = n;
r != null && (i = It(n, r));
const a = i.shape.slice(), c = a.splice(s - e.length, e.length).reduce((d, p) => d * p, 1);
a.push(c);
const u = i.reshape(a);
let h = yN(u, t, o);
if (h = h.reshape(i.shape), r != null) {
const d = $s(r);
h = It(h, d);
}
return h;
}
const CN = {
kernelName: yl,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { axis: o } = e;
let r = [];
return o == null ? r = s.shape.map((i, a) => a) : typeof o == "number" ? r = [o] : r = o, { x: () => wN(s, n, r) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const $N = {
kernelName: Pr,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t, o = mt(e.shape, s.shape);
return { a: () => {
const a = ut(n, st(s, "float32")), l = le(e.shape, o);
return l.length > 0 ? A(ct(a, l), e.shape) : a;
}, b: () => {
let a = R(n, st(e, "float32"));
const l = le(s.shape, o);
l.length > 0 && (a = A(ct(a, l), s.shape));
const c = Vt(s);
return Yt(ut(a, st(c, "float32")));
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const IN = {
kernelName: si,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => ut(n, Yt(Vt(e))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const kN = {
kernelName: ri,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t, s = R(Vo(e, 6), vi(e));
return { x: () => R(n, st(s, "float32")) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const vN = {
kernelName: oi,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(n, st(vi(e), "float32")) };
}
};
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const SN = {
kernelName: wl,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => A(n, e.shape) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const NN = {
kernelName: $l,
inputsToSave: ["images"],
gradFunc: (n, t, e) => {
const [s] = t, o = { dy: n, images: s };
return { images: () => (
// tslint:disable-next-line: no-unnecessary-type-assertion
D.runKernel(rh, o, e)
) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const TN = {
kernelName: Cl,
inputsToSave: ["images"],
gradFunc: (n, t, e) => {
const [s] = t, o = { dy: n, images: s };
return { images: () => (
// tslint:disable-next-line: no-unnecessary-type-assertion
D.runKernel(oh, o, e)
) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const EN = {
kernelName: Il,
gradFunc: (n, t, e) => {
const { dims: s } = e, o = wt(s, n.shape);
return { x: () => qs(n, o) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const RN = {
kernelName: ii,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const DN = {
kernelName: ai,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => Yt(ut(n, R(Xs(e, 1.5), 2))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const AN = {
kernelName: kl,
inputsToSave: ["condition"],
gradFunc: (n, t) => {
const [e] = t;
return {
// TODO(julianoks): Return null for condition gradient
// when backprop supports it.
condition: () => st(kt(e), "float32"),
t: () => R(n, st(e, n.dtype)),
e: () => R(n, st(vh(e), n.dtype))
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const FN = {
kernelName: li,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return {
x: () => {
const s = Je(e, Tt(0)), o = Tt(Gl), r = Tt(Hl), i = R(n, r), a = R(R(n, o), Ln(st(e, "float32")));
return Re(s, i, a);
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ON = {
kernelName: di,
outputsToSave: [!0],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(n, R(e, pt(Tt(1), e))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const _N = {
kernelName: hi,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const LN = {
kernelName: ci,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(yh(st(e, "float32")), n) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const MN = {
kernelName: ui,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(Pm(st(e, "float32")), n) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const PN = {
kernelName: vl,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { begin: o, size: r } = e, i = s.shape, [a, l] = Wl(s, o, r), c = [];
for (let u = 0; u < n.rank; u++)
c.push([a[u], i[u] - a[u] - l[u]]);
return { x: () => Th(n, c) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const zN = {
kernelName: El,
outputsToSave: [!0],
gradFunc: (n, t, e) => {
const [s] = t, { dim: o } = e, r = !0, i = R(n, s);
return {
logits: () => pt(i, R(ct(i, [o], r), s))
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const BN = {
kernelName: pi,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(n, Bo(e)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Sp = {
kernelName: Nl,
gradFunc: (n, t, e) => {
const { blockShape: s, paddings: o } = e;
return { x: () => xh(n, s, o) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Np = {
kernelName: Tl,
gradFunc: (n, t, e) => {
const { axis: s } = e;
return { x: () => Le(n, s) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const VN = {
kernelName: fi,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => ut(n, R($e(st(e, "float32")), 2)) };
}
};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const WN = {
kernelName: ih,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(n, R(st(e, "float32"), 2)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const UN = {
kernelName: mi,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t, o = Tt(2);
return { a: () => R(n, R(o, pt(e, s))), b: () => R(n, R(o, pt(s, e))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const GN = {
kernelName: wi,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const HN = {
kernelName: gi,
inputsToSave: ["a", "b"],
gradFunc: (n, t) => {
const [e, s] = t, o = mt(e.shape, s.shape);
return { a: () => {
let a = n;
const l = le(e.shape, o);
return l.length > 0 && (a = ct(a, l)), A(a, e.shape);
}, b: () => {
let a = n;
const l = le(s.shape, o);
return l.length > 0 && (a = ct(a, l)), A(Yt(a), s.shape);
} };
}
};
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const KN = {
kernelName: Sl,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, o = s.shape.slice(), { axis: r } = e;
wt(r, s.shape).forEach((c) => {
o[c] = 1;
});
const a = A(n, o), l = R(a, ks(s.shape, "float32"));
return { x: () => l };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const jN = {
kernelName: xi,
inputsToSave: ["x"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => ut(n, Vt(yh(e))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const XN = {
kernelName: bi,
outputsToSave: [!0],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => R(pt(Tt(1), Vt(e)), n) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const qN = {
kernelName: yi,
inputsToSave: ["x"],
gradFunc: (n, t, e) => {
const [s] = t, { reps: o } = e;
return { x: () => {
let i = kt(s);
if (s.rank === 1)
for (let a = 0; a < o[0]; ++a)
i = Y(i, zt(n, [a * s.shape[0]], [s.shape[0]]));
else if (s.rank === 2)
for (let a = 0; a < o[0]; ++a)
for (let l = 0; l < o[1]; ++l)
i = Y(i, zt(n, [a * s.shape[0], l * s.shape[1]], [
s.shape[0],
s.shape[1]
]));
else if (s.rank === 3)
for (let a = 0; a < o[0]; ++a)
for (let l = 0; l < o[1]; ++l)
for (let c = 0; c < o[2]; ++c)
i = Y(i, zt(n, [a * s.shape[0], l * s.shape[1], c * s.shape[2]], [s.shape[0], s.shape[1], s.shape[2]]));
else if (s.rank === 4)
for (let a = 0; a < o[0]; ++a)
for (let l = 0; l < o[1]; ++l)
for (let c = 0; c < o[2]; ++c)
for (let u = 0; u < o[3]; ++u)
i = Y(i, zt(n, [
a * s.shape[0],
l * s.shape[1],
c * s.shape[2],
u * s.shape[3]
], [s.shape[0], s.shape[1], s.shape[2], s.shape[3]]));
else
throw new Error(`Gradient for tile operation is not implemented for rank-${s.rank} tensors yet.`);
return i;
} };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const YN = {
kernelName: Co,
gradFunc: (n, t, e) => {
const s = e, { perm: o } = s, r = $s(o);
return { x: () => It(n, r) };
}
};
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const JN = {
kernelName: Rl,
gradFunc: (n, t, e) => {
const s = e, { axis: o } = s;
return { value: () => Xn(n, o) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ZN = {
kernelName: Dl,
inputsToSave: ["segmentIds"],
gradFunc: (n, t) => {
const [e] = t;
return { x: () => QN(n, e) };
}
};
function QN(n, t) {
const e = Is(t, kt(t)), s = $h(n, e);
let o = oo(t, Tt(0, "int32"));
const r = s.rank - o.rank;
for (let a = 0; a < r; ++a)
o = Oe(o, a + 1);
o = jn(o, ks(s.shape, "bool"));
const i = kt(s);
return Re(o, s, i);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const t2 = {
kernelName: Al,
gradFunc: (n) => ({ x: () => kt(n) })
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const e2 = [
Yg,
Zv,
Qv,
tS,
eS,
nS,
sS,
oS,
rS,
iS,
aS,
lS,
hS,
fS,
mS,
gS,
xS,
bS,
yS,
wS,
CS,
$S,
kS,
IS,
NS,
TS,
ES,
RS,
DS,
AS,
$N,
FS,
OS,
_S,
LS,
MS,
zS,
PS,
BS,
VS,
WS,
US,
GS,
HS,
KS,
jS,
XS,
qS,
YS,
QS,
kp,
kp,
tN,
sN,
iN,
aN,
lN,
cN,
uN,
hN,
dN,
pN,
fN,
mN,
gN,
vp,
vp,
xN,
bN,
CN,
IN,
kN,
vN,
SN,
NN,
TN,
EN,
RN,
DN,
AN,
FN,
ON,
_N,
LN,
MN,
PN,
zN,
BN,
Sp,
Sp,
Np,
Np,
VN,
UN,
WN,
GN,
HN,
KN,
jN,
XN,
qN,
YN,
JN,
ZN,
t2
];
for (const n of e2)
Q1(n);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.abs = function() {
return this.throwIfDisposed(), Ne(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.acos = function() {
return this.throwIfDisposed(), Qw(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.acosh = function() {
return this.throwIfDisposed(), eC(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.add = function(n) {
return this.throwIfDisposed(), Y(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.all = function(n, t) {
return this.throwIfDisposed(), Om(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.any = function(n, t) {
return this.throwIfDisposed(), Hc(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.argMax = function(n) {
return this.throwIfDisposed(), dr(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.argMin = function(n) {
return this.throwIfDisposed(), iC(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.asScalar = function() {
return this.throwIfDisposed(), I(this.size === 1, () => "The array must have only 1 element."), A(this, []);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.asType = function(n) {
return this.throwIfDisposed(), st(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.as1D = function() {
return this.throwIfDisposed(), A(this, [this.size]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.as2D = function(n, t) {
return this.throwIfDisposed(), A(this, [n, t]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.as3D = function(n, t, e) {
return this.throwIfDisposed(), A(this, [n, t, e]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.as4D = function(n, t, e, s) {
return this.throwIfDisposed(), A(this, [n, t, e, s]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.as5D = function(n, t, e, s, o) {
return this.throwIfDisposed(), A(this, [n, t, e, s, o]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.asin = function() {
return this.throwIfDisposed(), lC(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.asinh = function() {
return this.throwIfDisposed(), uC(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.atan = function() {
return this.throwIfDisposed(), dC(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.atan2 = function(n) {
return this.throwIfDisposed(), fC(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.atanh = function() {
return this.throwIfDisposed(), gC(this);
};
W().prototype.avgPool = function(n, t, e, s) {
return this.throwIfDisposed(), gh(this, n, t, e, s);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.batchToSpaceND = function(n, t) {
return this.throwIfDisposed(), xh(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.batchNorm = function(n, t, e, s, o) {
return this.throwIfDisposed(), Ml(this, n, t, e, s, o);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.broadcastTo = function(n) {
return this.throwIfDisposed(), ur(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.cast = function(n) {
return this.throwIfDisposed(), st(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.ceil = function() {
return this.throwIfDisposed(), UC(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.clipByValue = function(n, t) {
return this.throwIfDisposed(), Ye(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.concat = function(n, t) {
return this.throwIfDisposed(), n instanceof se && (n = [n]), Le([this, ...n], t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.conv1d = function(n, t, e, s, o, r) {
return this.throwIfDisposed(), _m(this, n, t, e, s, o, r);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.conv2dTranspose = function(n, t, e, s, o) {
return this.throwIfDisposed(), Lm(this, n, t, e, s, o);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.conv2d = function(n, t, e, s, o, r) {
return this.throwIfDisposed(), js(this, n, t, e, s, o, r);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.cos = function() {
return this.throwIfDisposed(), yh(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.cosh = function() {
return this.throwIfDisposed(), Pm(this);
};
/**
* @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.
* =============================================================================
*/
W().prototype.cumprod = function(n, t, e) {
return this.throwIfDisposed(), jc(this, n, t, e);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.cumsum = function(n, t, e) {
return this.throwIfDisposed(), zm(this, n, t, e);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.depthToSpace = function(n, t) {
return this.throwIfDisposed(), f$(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.depthwiseConv2d = function(n, t, e, s, o, r) {
return this.throwIfDisposed(), wh(this, n, t, e, s, o, r);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.dilation2d = function(n, t, e, s, o) {
return this.throwIfDisposed(), x$(this, n, t, e, s, o);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.divNoNan = function(n) {
return this.throwIfDisposed(), $$(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.div = function(n) {
return this.throwIfDisposed(), ut(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.dot = function(n) {
return this.throwIfDisposed(), k$(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.elu = function() {
return this.throwIfDisposed(), zl(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.equal = function(n) {
return this.throwIfDisposed(), _n(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.erf = function() {
return this.throwIfDisposed(), Bm(this);
};
/**
* @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.
* =============================================================================
*/
W().prototype.euclideanNorm = function(n, t) {
return this.throwIfDisposed(), L$(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.exp = function() {
return this.throwIfDisposed(), Ln(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.expandDims = function(n) {
return this.throwIfDisposed(), Oe(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.expm1 = function() {
return this.throwIfDisposed(), B$(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.fft = function() {
return this.throwIfDisposed(), og(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.flatten = function() {
return this.throwIfDisposed(), A(this, [this.size]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.floor = function() {
return this.throwIfDisposed(), Vl(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.floorDiv = function(n) {
return this.throwIfDisposed(), Fm(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.gather = function(n, t, e) {
return this.throwIfDisposed(), $h(this, n, t, e);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.greaterEqual = function(n) {
return this.throwIfDisposed(), oo(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.greater = function(n) {
return this.throwIfDisposed(), Je(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.ifft = function() {
return this.throwIfDisposed(), Xc(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.irfft = function() {
return this.throwIfDisposed(), mk(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.isFinite = function() {
return this.throwIfDisposed(), q$(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.isInf = function() {
return this.throwIfDisposed(), J$(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.isNaN = function() {
return this.throwIfDisposed(), Q$(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.leakyRelu = function(n) {
return this.throwIfDisposed(), kh(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.lessEqual = function(n) {
return this.throwIfDisposed(), Vo(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.less = function(n) {
return this.throwIfDisposed(), ha(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.localResponseNormalization = function(n, t, e, s) {
return this.throwIfDisposed(), oI(this, n, t, e, s);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.logSigmoid = function() {
return this.throwIfDisposed(), hI(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.logSoftmax = function(n) {
return this.throwIfDisposed(), Hm(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.logSumExp = function(n, t) {
return this.throwIfDisposed(), Km(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.log = function() {
return this.throwIfDisposed(), Mn(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.log1p = function() {
return this.throwIfDisposed(), Gm(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.logicalAnd = function(n) {
return this.throwIfDisposed(), jn(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.logicalNot = function() {
return this.throwIfDisposed(), vh(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.logicalOr = function(n) {
return this.throwIfDisposed(), jm(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.logicalXor = function(n) {
return this.throwIfDisposed(), yI(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.matMul = function(n, t, e) {
return this.throwIfDisposed(), Nt(this, n, t, e);
};
W().prototype.maxPool = function(n, t, e, s) {
return this.throwIfDisposed(), Sh(this, n, t, e, s);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.max = function(n, t) {
return this.throwIfDisposed(), bn(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.maximum = function(n) {
return this.throwIfDisposed(), Is(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.mean = function(n, t) {
return this.throwIfDisposed(), ee(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.min = function(n, t) {
return this.throwIfDisposed(), ua(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.minimum = function(n) {
return this.throwIfDisposed(), mr(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.mirrorPad = function(n, t) {
return this.throwIfDisposed(), NI(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.mod = function(n) {
return this.throwIfDisposed(), EI(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.mul = function(n) {
return this.throwIfDisposed(), R(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.neg = function() {
return this.throwIfDisposed(), Yt(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.norm = function(n, t, e) {
return this.throwIfDisposed(), Bl(this, n, t, e);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.notEqual = function(n) {
return this.throwIfDisposed(), da(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.oneHot = function(n, t = 1, e = 0) {
return this.throwIfDisposed(), Xm(this, n, t, e);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.onesLike = function() {
return this.throwIfDisposed(), an(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.pad = function(n, t) {
return this.throwIfDisposed(), Th(this, n, t);
};
W().prototype.pool = function(n, t, e, s, o, r) {
return this.throwIfDisposed(), zI(this, n, t, e, s, o, r);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.pow = function(n) {
return this.throwIfDisposed(), Xs(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.prelu = function(n) {
return this.throwIfDisposed(), Rh(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.prod = function(n, t) {
return this.throwIfDisposed(), WI(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.reciprocal = function() {
return this.throwIfDisposed(), qI(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.relu = function() {
return this.throwIfDisposed(), ro(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.relu6 = function() {
return this.throwIfDisposed(), Ym(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.reshapeAs = function(n) {
return this.throwIfDisposed(), A(this, n.shape);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.reshape = function(n) {
return this.throwIfDisposed(), A(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.resizeBilinear = function(n, t, e) {
return this.throwIfDisposed(), cg(this, n, t, e);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.resizeNearestNeighbor = function(n, t, e) {
return this.throwIfDisposed(), ug(this, n, t, e);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.reverse = function(n) {
return this.throwIfDisposed(), qs(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.rfft = function() {
return this.throwIfDisposed(), bk(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.round = function() {
return this.throwIfDisposed(), Jm(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.rsqrt = function() {
return this.throwIfDisposed(), Zm(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.selu = function() {
return this.throwIfDisposed(), Qm(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.separableConv2d = function(n, t, e, s, o, r) {
return this.throwIfDisposed(), tg(this, n, t, e, s, o, r);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.sigmoid = function() {
return this.throwIfDisposed(), Bo(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.sign = function() {
return this.throwIfDisposed(), ok(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.sin = function() {
return this.throwIfDisposed(), eg(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.sinh = function() {
return this.throwIfDisposed(), ng(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.slice = function(n, t) {
return this.throwIfDisposed(), zt(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.softmax = function(n) {
return this.throwIfDisposed(), Fh(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.softplus = function() {
return this.throwIfDisposed(), $i(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.spaceToBatchND = function(n, t) {
return this.throwIfDisposed(), Eh(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.split = function(n, t) {
return this.throwIfDisposed(), qe(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.sqrt = function() {
return this.throwIfDisposed(), $e(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.square = function() {
return this.throwIfDisposed(), Vt(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.squaredDifference = function(n) {
return this.throwIfDisposed(), wk(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.squeeze = function(n) {
return this.throwIfDisposed(), ki(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.stack = function(n, t) {
this.throwIfDisposed();
const e = n instanceof se ? [this, n] : [this, ...n];
return Xn(e, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.step = function(n) {
return this.throwIfDisposed(), vi(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.stridedSlice = function(n, t, e, s, o, r, i, a) {
return this.throwIfDisposed(), vk(this, n, t, e, s, o, r, i, a);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.sub = function(n) {
return this.throwIfDisposed(), pt(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.sum = function(n, t) {
return this.throwIfDisposed(), ct(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.tan = function() {
return this.throwIfDisposed(), Nk(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.tanh = function() {
return this.throwIfDisposed(), Ll(this);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.tile = function(n) {
return this.throwIfDisposed(), gn(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.toBool = function() {
return this.throwIfDisposed(), st(this, "bool");
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.toFloat = function() {
return this.throwIfDisposed(), st(this, "float32");
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.toInt = function() {
return this.throwIfDisposed(), st(this, "int32");
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.topk = function(n, t) {
return this.throwIfDisposed(), Rk(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.transpose = function(n) {
return this.throwIfDisposed(), It(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.unique = function(n) {
return this.throwIfDisposed(), Fk(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.unsortedSegmentSum = function(n, t) {
return this.throwIfDisposed(), ag(this, n, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.unstack = function(n) {
return this.throwIfDisposed(), Ys(this, n);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.where = function(n, t) {
return this.throwIfDisposed(), Re(n, this, t);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
W().prototype.zerosLike = function() {
return this.throwIfDisposed(), kt(this);
};
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class Sn extends Error {
constructor(t) {
super(t), Object.setPrototypeOf(this, Sn.prototype);
}
}
class sn extends Error {
constructor(t) {
super(t), Object.setPrototypeOf(this, sn.prototype);
}
}
class E extends Error {
constructor(t) {
super(t), Object.setPrototypeOf(this, E.prototype);
}
}
class gt extends Error {
constructor(t) {
super(t), Object.setPrototypeOf(this, gt.prototype);
}
}
class md extends Error {
constructor(t) {
super(t), Object.setPrototypeOf(this, md.prototype);
}
}
/**
* @license
* Copyright 2022 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class Zg {
constructor(t) {
this.maxEntries = t || 100, this.cache = /* @__PURE__ */ new Map();
}
/**
* Get the entry for the key and mark it as used recently.
*/
get(t) {
let e;
return this.cache.has(t) && (e = this.cache.get(t), this.cache.delete(t), this.cache.set(t, e)), e;
}
/**
* Put the entry into the cache. If the key already existed, mark the key as
* used recently.
*/
put(t, e) {
if (this.cache.has(t))
this.cache.delete(t);
else if (this.cache.size >= this.maxEntries) {
const s = this.cache.keys().next().value;
this.cache.delete(s);
}
this.cache.set(t, e);
}
/**
* Get the MaxEntries of the cache.
*/
getMaxEntries() {
return this.maxEntries;
}
/**
* Set the MaxEntries of the cache. If the maxEntries is decreased, reduce
* entries in the cache.
*/
setMaxEntries(t) {
if (t < 0)
throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${t}.`);
if (this.maxEntries > t)
for (let e = 0; e < this.maxEntries - t; e++) {
const s = this.cache.keys().next().value;
this.cache.delete(s);
}
this.maxEntries = t;
}
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function Js(n, t) {
if (Array.isArray(n)) {
let e = [];
for (let s = 0; s < t; s++)
e = e.concat(n);
return e;
} else {
const e = new Array(t);
return e.fill(n), e;
}
}
function Nn(n, t) {
if (!n)
throw new md(t);
}
function Tp(n, t) {
let e = 0;
for (const s of n)
s === t && e++;
return e;
}
function _e(n) {
return n.length === 1 ? n[0] : n;
}
function Dt(n) {
return Array.isArray(n) ? n : [n];
}
function Un(n) {
const e = n.replace(/(.)([A-Z][a-z0-9]+)/g, "$1_$2").replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
return e[0] !== "_" ? e : "private" + e;
}
function Os(n) {
return n.length <= 1 || n.indexOf("_") === -1 ? n : n.replace(/[_]+(\w|$)/g, (t, e) => e.toUpperCase());
}
let Qe = {};
function gd(n) {
if (n == null)
return null;
const t = {};
return t.className = n.getClassName(), t.config = n.getConfig(), t;
}
function Jc(n) {
if (!(n == null || typeof n != "object"))
if (Array.isArray(n))
n.forEach((t) => Jc(t));
else {
const t = Object.keys(n);
for (const e of t) {
const s = n[e];
s != null && typeof s == "object" && (!Array.isArray(s) && s.type === "ndarray" && typeof s.value == "number" ? n[e] = s.value : Jc(s));
}
}
}
function Ei(n, t = {}, e = {}, s = "object", o = !1) {
if (typeof n == "string") {
const r = n;
let i;
if (r in e)
i = e[r];
else if (r in Qe)
i = Qe[r];
else if (i = t[r], i == null)
throw new E(`Unknown ${s}: ${n}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);
return i;
} else {
const r = n;
if (r.className == null || r.config == null)
throw new E(`${s}: Improper config format: ${JSON.stringify(r)}.
'className' and 'config' must set.`);
const i = r.className;
let a, l;
if (i in e ? [a, l] = e[i] : i in Qe ? [a, l] = Qe.className : i in t && ([a, l] = t[i]), a == null)
throw new E(`Unknown ${s}: ${i}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);
if (l != null) {
const c = {};
for (const p of Object.keys(Qe))
c[p] = Qe[p];
for (const p of Object.keys(e))
c[p] = e[p];
const u = r.config;
u.customObjects = c;
const h = Object.assign({}, Qe);
for (const p of Object.keys(e))
Qe[p] = e[p];
Jc(r.config);
const d = l(a, r.config, e, o);
return Qe = Object.assign({}, h), d;
} else {
const c = Object.assign({}, Qe);
for (const h of Object.keys(e))
Qe[h] = e[h];
const u = new a(r.config);
return Qe = Object.assign({}, c), u;
}
}
}
function n2(n, t) {
return n < t ? -1 : n > t ? 1 : 0;
}
function Hi(n, t) {
return -1 * n2(n, t);
}
function hs(n) {
if (n == null)
return n;
const t = [];
for (const e of n)
t.indexOf(e) === -1 && t.push(e);
return t;
}
function s2(n) {
if (n == null)
throw new E(`Invalid value in obj: ${JSON.stringify(n)}`);
for (const t in n)
if (n.hasOwnProperty(t))
return !1;
return !0;
}
function ao(n, t, e) {
if (e != null && n.indexOf(e) < 0)
throw new E(`${e} is not a valid ${t}. Valid values are ${n} or null/undefined.`);
}
function xd(n, t, e = 0, s = 1 / 0) {
return Nn(e >= 0), Nn(s >= e), Array.isArray(n) && n.length >= e && n.length <= s && n.every((o) => typeof o === t);
}
function de(n, t) {
Array.isArray(n) ? (I(n.length > 0, () => `${t} is unexpectedly an empty array.`), n.forEach((e, s) => de(e, `element ${s + 1} of ${t}`))) : I(Number.isInteger(n) && n > 0, () => `Expected ${t} to be a positive integer, but got ${Qg(n)}.`);
}
function Qg(n) {
return n === null ? "null" : Array.isArray(n) ? "[" + n.map((t) => Qg(t)).join(",") + "]" : typeof n == "string" ? `"${n}"` : `${n}`;
}
function o2(n, t, e) {
let s = e != null ? e() : Fe(), o;
return (...i) => {
const a = e != null ? e() : Fe();
return a - s < t || (s = a, o = n(...i)), o;
};
}
function tx(n) {
return n === "relu" ? "relu" : n === "linear" ? "linear" : n === "elu" ? "elu" : null;
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
let r2 = 0;
function ex() {
return r2++;
}
const Ki = {};
function Kl(n = "") {
return n in Ki || (Ki[n] = 0), Ki[n] += 1, n + Ki[n].toString();
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const i2 = ["channelsFirst", "channelsLast"], a2 = ["nearest", "bilinear"], l2 = ["valid", "same", "causal"], c2 = ["max", "avg"], u2 = ["sum", "mul", "concat", "ave"];
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const mo = /* @__PURE__ */ new Map();
function Qt(n) {
ao(i2, "DataFormat", n);
}
function h2(n) {
ao(a2, "InterpolationFormat", n);
}
function Ze(n) {
ao(l2, "PaddingMode", n);
}
function nx(n) {
ao(c2, "PoolMode", n);
}
const hr = [], Ep = "/";
function zs(n, t) {
hr.push(n);
try {
const e = t();
return hr.pop(), e;
} catch (e) {
throw hr.pop(), e;
}
}
function d2() {
return hr.length === 0 ? "" : hr.join(Ep) + Ep;
}
function sx(n) {
if (!rx(n))
throw new Error("Not a valid tensor name: '" + n + "'");
return d2() + n;
}
function ox(n) {
if (!rx(n))
throw new Error("Not a valid tensor name: '" + n + "'");
mo.has(n) || mo.set(n, 0);
const t = mo.get(n);
if (mo.set(n, mo.get(n) + 1), t > 0) {
const e = `${n}_${t}`;
return mo.set(e, 1), e;
} else
return n;
}
const p2 = new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);
function rx(n) {
return !!n.match(p2);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function f2(n) {
return n === parseInt(n.toString(), 10);
}
function ds(n, t, e) {
t == null && (t = 0), e == null && (e = n.length);
let s = 1;
for (let o = t; o < e; ++o)
s *= n[o];
return s;
}
function Ro(n) {
if (n.length === 0)
return Number.NaN;
let t = Number.POSITIVE_INFINITY;
for (let e = 0; e < n.length; e++) {
const s = n[e];
s < t && (t = s);
}
return t;
}
function fs(n) {
if (n.length === 0)
return Number.NaN;
let t = Number.NEGATIVE_INFINITY;
for (let e = 0; e < n.length; e++) {
const s = n[e];
s > t && (t = s);
}
return t;
}
function wn(n, t) {
if (t < n)
throw new E(`end (${t}) < begin (${n}) is forbidden.`);
const e = [];
for (let s = n; s < t; ++s)
e.push(s);
return e;
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
let xc;
function oe() {
return xc == null && (xc = Iw().epsilon()), xc;
}
function Cn() {
return "channelsLast";
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function Fn(n, t) {
return st(n, t);
}
function Ri(n, t = -1) {
const e = n.shape.slice();
return t < 0 && (t = e.length + t + 1), e.splice(t, 0, 1), A(n, e);
}
function m2(n, t) {
return _(() => {
if (n.shape.length !== 2)
throw new E(`repeat() expects a rank-2 tensor, but received a rank-${n.shape.length} tensor.`);
const e = Ri(n, 1);
return Zc(e, [1, t, 1]);
});
}
function g2(n) {
const t = [ds(n.shape)];
return A(n, t);
}
function x2(n) {
if (n.rank <= 1)
throw new E(`batchFlatten requires a minimum rank of 2. Got rank: ${n.rank}.`);
const t = [n.shape[0], ds(n.shape, 1)];
return A(n, t);
}
function Bs(n, t, e) {
return _(() => {
switch (n.rank) {
case 1:
return Dh(n, t, e);
case 2:
return sg(n, [t, 0], [e, n.shape[1]]);
case 3:
return Ah(n, [t, 0, 0], [e, n.shape[1], n.shape[2]]);
case 4:
return fa(n, [t, 0, 0, 0], [e, n.shape[1], n.shape[2], n.shape[3]]);
case 5:
return zt(n, [t, 0, 0, 0, 0], [
e,
n.shape[1],
n.shape[2],
n.shape[3],
n.shape[4]
]);
case 6:
return zt(n, [t, 0, 0, 0, 0, 0], [
e,
n.shape[1],
n.shape[2],
n.shape[3],
n.shape[4],
n.shape[5]
]);
default:
throw new E(`sliceAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`);
}
});
}
function bc(n, t, e) {
return _(() => {
switch (n.rank) {
case 1:
return Dh(n, t, e);
case 2:
return sg(n, [0, t], [n.shape[0], e]);
case 3:
return Ah(n, [0, 0, t], [n.shape[0], n.shape[1], e]);
case 4:
return fa(n, [0, 0, 0, t], [n.shape[0], n.shape[1], n.shape[2], e]);
default:
throw new E(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`);
}
});
}
function ji(n, t, e, s) {
return _(() => {
switch (n.rank) {
case 1:
return Dh(n, t, e);
case 2:
switch (s) {
case 1:
return Bs(n, t, e);
case 2:
return bc(n, t, e);
default:
throw new E(`The axis is not within the rank of the tensor ${s}`);
}
case 3:
switch (s) {
case 1:
return Bs(n, t, e);
case 2:
return Ah(n, [0, t, 0], [n.shape[0], e, n.shape[2]]);
case 3:
return bc(n, t, e);
default:
throw new E(`The axis is not within the rank of the tensor ${s}`);
}
case 4:
switch (s) {
case 1:
return Bs(n, t, e);
case 2:
return fa(n, [0, t, 0, 0], [n.shape[0], e, n.shape[2], n.shape[3]]);
case 3:
return fa(n, [0, 0, t, 0], [n.shape[0], n.shape[1], e, n.shape[3]]);
case 4:
return bc(n, t, e);
default:
throw new E(`The axis is not within the rank of the tensor ${s}`);
}
default:
throw new E(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`);
}
});
}
function bd(n, t = -1) {
let e;
return t < 0 && (e = n[0].rank, e !== 0 ? t = e : t = 0), t === n[0].rank && (t = -1), Le(n, t);
}
function Rp(n, t) {
switch (n.rank) {
case 1:
return KC([n, t]);
case 2:
return XC([n, t], 0);
case 3:
return YC([n, t], 0);
case 4:
return ZC([n, t], 0);
default:
throw new E(`concatAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`);
}
}
function Zc(n, t) {
if (Array.isArray(t) || (t = [t]), n.rank !== t.length)
throw new E(`The length of input n (${t.length}) does not match the number of dimensions in input x (${n.rank})`);
return gn(n, t);
}
function jl(n, t = 0, e = 1, s, o) {
return HI(n, t, e, s, o);
}
function On(n, t, e, s) {
if (n.rank < 2 || t.rank < 2)
throw new gt(`dot requires both inputs to be rank >= 2 but got x shape = ${n.shape} and y shape = ${t.shape}`);
if (t.rank >= 3) {
const o = n.shape.slice(-1)[0], r = t.shape.slice(-2)[0];
if (o !== r)
throw new gt(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${n.shape} and y shape = ${t.shape}`);
}
if (n.rank === 2 && t.rank === 2)
return gp({
a: n,
b: t,
transposeA: !1,
transposeB: !1,
bias: s ? Qc(n.rank, s, Cn()) : null,
activation: e
});
{
const o = n.shape.slice(), r = o.pop();
n = A(n, [-1, r]);
const i = t.shape.slice(), a = i.pop(), l = i.pop(), c = [...i, a], u = Array.from({ length: t.rank }, (f, m) => m === 0 ? t.rank - 2 : m <= t.rank - 2 ? m - 1 : m);
t = A(It(t, u), [l, -1]);
const h = [...o, ...c];
return A(gp({
a: n,
b: t,
transposeA: !1,
transposeB: !1,
bias: s ? Qc(n.rank, s, Cn()) : null,
activation: e
}), h);
}
}
function ix(n, t, e) {
return _(() => (Array.isArray(t) ? t = We(t, "int32") : t = st(t, "int32"), $h(n, t, e)));
}
function Di(n) {
return R(n, n);
}
function Qc(n, t, e) {
const s = t.shape;
if (t.rank !== 1 && t.rank !== n)
throw new E(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${n}`);
if (n === 5) {
if (e === "channelsFirst")
return s.length === 1 ? A(t, [1, s[0], 1, 1, 1]) : A(t, [1, s[3], s[0], s[1], s[2]]);
if (e === "channelsLast")
return s.length === 1 ? A(t, [1, 1, 1, 1, s[0]]) : A(t, [1].concat(s));
} else if (n === 4) {
if (e === "channelsFirst")
return s.length === 1 ? A(t, [1, s[0], 1, 1]) : A(t, [1, s[2], s[0], s[1]]);
if (e === "channelsLast")
return s.length === 1 ? A(t, [1, 1, 1, s[0]]) : A(t, [1].concat(s));
} else if (n === 3) {
if (e === "channelsFirst")
return s.length === 1 ? A(t, [1, s[0], 1]) : A(t, [1, s[1], s[0]]);
if (e === "channelsLast")
return s.length === 1 ? A(t, [1, 1, s[0]]) : A(t, [1].concat(s));
} else if (n < 3)
return t;
throw new E(`Unsupported input rank by biasAdd: ${t.rank}`);
}
function In(n, t, e) {
return _(() => (e == null && (e = Cn()), Qt(e), Y(n, Qc(n.rank, t, e))));
}
function b2(n, t = 1) {
if (t !== 1)
throw new gt(`Support for alpha values other than 1 (${t}) is not implemented yet.`);
return zl(n);
}
function y2(n) {
return _(() => ut(n, Y(Ne(n), 1)));
}
function ax(n, t, e, s) {
return _(() => Bk(n, t, e, s));
}
function w2(n) {
return _(() => {
const t = Y(0.5, R(0.2, n));
return Ye(t, 0, 1);
});
}
function Ai(n, t, e = !1) {
return e ? n() : t();
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const C2 = ["fanIn", "fanOut", "fanAvg"], $2 = ["normal", "uniform", "truncatedNormal"];
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function I2(n) {
ao(C2, "FanMode", n);
}
function k2(n) {
ao($2, "Distribution", n);
}
class cn extends Uo {
fromConfigUsesCustomObjects() {
return !1;
}
getConfig() {
return {};
}
}
class lx extends cn {
apply(t, e) {
return he(t, e);
}
}
lx.className = "Zeros";
j(lx);
class yd extends cn {
apply(t, e) {
return ks(t, e);
}
}
yd.className = "Ones";
j(yd);
class cx extends cn {
constructor(t) {
if (super(), typeof t != "object")
throw new E(`Expected argument of type ConstantConfig but got ${t}`);
if (t.value === void 0)
throw new E(`config must have value set but got ${t}`);
this.value = t.value;
}
apply(t, e) {
return _(() => R(Tt(this.value), ks(t, e)));
}
getConfig() {
return {
value: this.value
};
}
}
cx.className = "Constant";
j(cx);
class ux extends cn {
constructor(t) {
super(), this.DEFAULT_MINVAL = -0.05, this.DEFAULT_MAXVAL = 0.05, this.minval = t.minval || this.DEFAULT_MINVAL, this.maxval = t.maxval || this.DEFAULT_MAXVAL, this.seed = t.seed;
}
apply(t, e) {
return Ii(t, this.minval, this.maxval, e, this.seed);
}
getConfig() {
return { minval: this.minval, maxval: this.maxval, seed: this.seed };
}
}
ux.className = "RandomUniform";
j(ux);
class hx extends cn {
constructor(t) {
super(), this.DEFAULT_MEAN = 0, this.DEFAULT_STDDEV = 0.05, this.mean = t.mean || this.DEFAULT_MEAN, this.stddev = t.stddev || this.DEFAULT_STDDEV, this.seed = t.seed;
}
apply(t, e) {
if (e = e || "float32", e !== "float32" && e !== "int32")
throw new gt(`randomNormal does not support dType ${e}.`);
return jl(t, this.mean, this.stddev, e, this.seed);
}
getConfig() {
return { mean: this.mean, stddev: this.stddev, seed: this.seed };
}
}
hx.className = "RandomNormal";
j(hx);
class dx extends cn {
constructor(t) {
super(), this.DEFAULT_MEAN = 0, this.DEFAULT_STDDEV = 0.05, this.mean = t.mean || this.DEFAULT_MEAN, this.stddev = t.stddev || this.DEFAULT_STDDEV, this.seed = t.seed;
}
apply(t, e) {
if (e = e || "float32", e !== "float32" && e !== "int32")
throw new gt(`truncatedNormal does not support dType ${e}.`);
return ig(t, this.mean, this.stddev, e, this.seed);
}
getConfig() {
return { mean: this.mean, stddev: this.stddev, seed: this.seed };
}
}
dx.className = "TruncatedNormal";
j(dx);
class px extends cn {
constructor(t) {
super(), this.gain = t.gain != null ? t.gain : 1;
}
apply(t, e) {
return _(() => {
if (t.length !== 2 || t[0] !== t[1])
throw new E("Identity matrix initializer can only be used for 2D square matrices.");
return R(this.gain, Um(t[0]));
});
}
getConfig() {
return { gain: this.gain };
}
}
px.className = "Identity";
j(px);
function v2(n, t = "channelsLast") {
let e, s;
if (Qt(t), n.length === 2)
e = n[0], s = n[1];
else if ([3, 4, 5].indexOf(n.length) !== -1) {
if (t === "channelsFirst") {
const o = ds(n, 2);
e = n[1] * o, s = n[0] * o;
} else if (t === "channelsLast") {
const o = ds(n, 0, n.length - 2);
e = n[n.length - 2] * o, s = n[n.length - 1] * o;
}
} else {
const o = ds(n);
e = Math.sqrt(o), s = Math.sqrt(o);
}
return [e, s];
}
class Ge extends cn {
/**
* Constructor of VarianceScaling.
* @throws ValueError for invalid value in scale.
*/
constructor(t) {
if (super(), t.scale < 0)
throw new E(`scale must be a positive float. Got: ${t.scale}`);
this.scale = t.scale == null ? 1 : t.scale, this.mode = t.mode == null ? "fanIn" : t.mode, I2(this.mode), this.distribution = t.distribution == null ? "normal" : t.distribution, k2(this.distribution), this.seed = t.seed;
}
apply(t, e) {
const s = v2(t), o = s[0], r = s[1];
let i = this.scale;
if (this.mode === "fanIn" ? i /= Math.max(1, o) : this.mode === "fanOut" ? i /= Math.max(1, r) : i /= Math.max(1, (o + r) / 2), this.distribution === "normal") {
const a = Math.sqrt(i);
if (e = e || "float32", e !== "float32" && e !== "int32")
throw new gt(`${this.getClassName()} does not support dType ${e}.`);
return ig(t, 0, a, e, this.seed);
} else {
const a = Math.sqrt(3 * i);
return Ii(t, -a, a, e, this.seed);
}
}
getConfig() {
return {
scale: this.scale,
mode: this.mode,
distribution: this.distribution,
seed: this.seed
};
}
}
Ge.className = "VarianceScaling";
j(Ge);
class wd extends Ge {
/**
* Constructor of GlorotUniform
* @param scale
* @param mode
* @param distribution
* @param seed
*/
constructor(t) {
super({
scale: 1,
mode: "fanAvg",
distribution: "uniform",
seed: t == null ? null : t.seed
});
}
getClassName() {
return Ge.className;
}
}
wd.className = "GlorotUniform";
j(wd);
class Cd extends Ge {
/**
* Constructor of GlorotNormal.
* @param scale
* @param mode
* @param distribution
* @param seed
*/
constructor(t) {
super({
scale: 1,
mode: "fanAvg",
distribution: "normal",
seed: t == null ? null : t.seed
});
}
getClassName() {
return Ge.className;
}
}
Cd.className = "GlorotNormal";
j(Cd);
class $d extends Ge {
constructor(t) {
super({
scale: 2,
mode: "fanIn",
distribution: "normal",
seed: t == null ? null : t.seed
});
}
getClassName() {
return Ge.className;
}
}
$d.className = "HeNormal";
j($d);
class Id extends Ge {
constructor(t) {
super({
scale: 2,
mode: "fanIn",
distribution: "uniform",
seed: t == null ? null : t.seed
});
}
getClassName() {
return Ge.className;
}
}
Id.className = "HeUniform";
j(Id);
class kd extends Ge {
constructor(t) {
super({
scale: 1,
mode: "fanIn",
distribution: "normal",
seed: t == null ? null : t.seed
});
}
getClassName() {
return Ge.className;
}
}
kd.className = "LeCunNormal";
j(kd);
class vd extends Ge {
constructor(t) {
super({
scale: 1,
mode: "fanIn",
distribution: "uniform",
seed: t == null ? null : t.seed
});
}
getClassName() {
return Ge.className;
}
}
vd.className = "LeCunUniform";
j(vd);
class fx extends cn {
constructor(t) {
super(), this.DEFAULT_GAIN = 1, this.ELEMENTS_WARN_SLOW = 2e3, this.gain = t.gain == null ? this.DEFAULT_GAIN : t.gain, this.seed = t.seed;
}
apply(t, e) {
return _(() => {
if (t.length < 2)
throw new gt("Shape must be at least 2D.");
if (e !== "int32" && e !== "float32" && e !== void 0)
throw new TypeError(`Unsupported data type ${e}.`);
e = e;
const s = G(t.slice(0, -1)), o = t[t.length - 1], r = s * o;
r > this.ELEMENTS_WARN_SLOW && console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${r}) elements: Slowness may result.`);
const i = [Math.max(o, s), Math.min(o, s)], a = jl(i, 0, 1, e, this.seed), l = Lv.qr(a, !1);
let c = l[0];
const h = l[1].flatten().stridedSlice([0], [Math.min(o, s) * Math.min(o, s)], [Math.min(o, s) + 1]);
return c = R(c, h.sign()), s < o && (c = c.transpose()), R(Tt(this.gain), c.reshape(t));
});
}
getConfig() {
return {
gain: this.gain,
seed: this.seed
};
}
}
fx.className = "Orthogonal";
j(fx);
const Dp = {
constant: "Constant",
glorotNormal: "GlorotNormal",
glorotUniform: "GlorotUniform",
heNormal: "HeNormal",
heUniform: "HeUniform",
identity: "Identity",
leCunNormal: "LeCunNormal",
leCunUniform: "LeCunUniform",
ones: "Ones",
orthogonal: "Orthogonal",
randomNormal: "RandomNormal",
randomUniform: "RandomUniform",
truncatedNormal: "TruncatedNormal",
varianceScaling: "VarianceScaling",
zeros: "Zeros"
};
function Ap(n, t = {}) {
return Ei(n, nn.getMap().classNameMap, t, "initializer");
}
function Kt(n) {
return gd(n);
}
function Ut(n) {
if (typeof n == "string") {
const t = n in Dp ? Dp[n] : n;
if (t === "GlorotNormal")
return new Cd();
if (t === "GlorotUniform")
return new wd();
if (t === "HeNormal")
return new $d();
if (t === "HeUniform")
return new Id();
if (t === "LeCunNormal")
return new kd();
if (t === "LeCunUniform")
return new vd();
{
const e = {};
return e.className = t, e.config = {}, Ap(e);
}
} else
return n instanceof cn ? n : Ap(n);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function tu(n) {
return Array.isArray(n) && Array.isArray(n[0]);
}
function ma(n) {
return n.length === 0 ? [] : Array.isArray(n[0]) ? n : [n];
}
function ft(n) {
let t;
if (Array.isArray(n)) {
if (n.length !== 1)
throw new E(`Expected Tensor length to be 1; got ${n.length}`);
t = n[0];
} else
t = n;
return t;
}
function St(n) {
if (Array.isArray(n) && Array.isArray(n[0])) {
if (n.length === 1)
return n = n, n[0];
throw new E(`Expected exactly 1 Shape; got ${n.length}`);
} else
return n;
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function ga(n) {
let t = 0;
for (const e of n)
e.shape.length === 0 ? t += 1 : t += e.shape.reduce((s, o) => s * o);
return t;
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const Fp = "Variable";
class S2 {
/**
* Construct Variable from a `tf.Tensor`.
*
* If not explicitly named, the Variable will be given a name with the
* prefix 'Variable'. Variable names are unique. In the case of name
* collision, suffixies '_<num>' will be added to the name.
*
* @param val Initial value of the Variable.
* @param name Name of the variable. If `null` or `undefined` is provided, it
* will default a name with the prefix 'Variable'.
* @param constraint Optional, projection function to be applied to the
* variable after optimize updates
* @throws ValueError if `name` is `null` or `undefined`.
*/
constructor(t, e = "float32", s = Fp, o = !0, r = null) {
this.dtype = e ?? "float32", this.shape = t.shape, this.id = ex(), s = s ?? Fp, this.originalName = sx(s), this.name = ox(this.originalName), this.trainable_ = o, this.constraint = r, this.val = Lk(t, this.trainable_, this.name, this.dtype);
}
/**
* Get a snapshot of the Variable's value.
*
* The returned value is a snapshot of the Variable's value at the time of
* the invocation. Future mutations in the value of the tensor will only
* be reflected by future calls to this method.
*/
read() {
return this.assertNotDisposed(), this.val;
}
/**
* Update the value of the Variable.
*
* @param newVal: The new value to update to. Must be consistent with the
* dtype and shape of the Variable.
* @return This Variable.
*/
write(t) {
return this.assertNotDisposed(), N2(this.val, t), this.val.id !== t.id && (this.val.assign(t), this.constraint != null && this.val.assign(this.constraint.apply(this.val))), this;
}
/**
* Dispose this LayersVariable instance from memory.
*/
dispose() {
this.assertNotDisposed(), this.val.dispose();
}
assertNotDisposed() {
if (this.val.isDisposed)
throw new Error(`LayersVariable ${this.name} is already disposed.`);
}
get trainable() {
return this.trainable_;
}
set trainable(t) {
this.trainable_ = t, this.val.trainable = t;
}
}
function N2(n, t) {
if (n.shape.toString() !== t.shape.toString())
throw new Error("Shape mismatch: " + JSON.stringify(n.shape) + " vs. " + JSON.stringify(t.shape));
}
function eu(n) {
return n.map((t) => t.read());
}
function Sd(n) {
n.forEach((t) => {
t[0].write(t[1]);
});
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class re {
constructor(t) {
this.dtype = t.dtype, this.shape = t.shape, t.shape != null ? this.ndim = t.shape.length : this.ndim = t.ndim, this.maxNDim = t.maxNDim, this.minNDim = t.minNDim, this.axes = t.axes || {};
}
}
class Pn {
/**
*
* @param dtype
* @param shape
* @param sourceLayer The Layer that produced this symbolic tensor.
* @param inputs The inputs passed to sourceLayer's __call__() method.
* @param nodeIndex
* @param tensorIndex
* @param callArgs The keyword arguments passed to the __call__() method.
* @param name
* @param outputTensorIndex The index of this tensor in the list of outputs
* returned by apply().
*/
constructor(t, e, s, o, r, i, a) {
this.dtype = t, this.shape = e, this.sourceLayer = s, this.inputs = o, this.callArgs = r, this.outputTensorIndex = a, this.id = ex(), i != null && (this.originalName = sx(i), this.name = ox(this.originalName)), this.rank = e.length;
}
}
let T2 = 0;
class Xl {
constructor(t, e) {
this.callArgs = e, this.id = T2++, this.outboundLayer = t.outboundLayer, this.inboundLayers = t.inboundLayers, this.nodeIndices = t.nodeIndices, this.tensorIndices = t.tensorIndices, this.inputTensors = t.inputTensors, this.outputTensors = t.outputTensors, this.inputMasks = t.inputMasks, this.outputMasks = t.outputMasks, this.inputShapes = t.inputShapes, this.outputShapes = t.outputShapes;
for (const s of t.inboundLayers)
s?.outboundNodes.push(this);
t.outboundLayer.inboundNodes.push(this);
}
getConfig() {
const t = [];
for (const e of this.inboundLayers)
e != null ? t.push(e.name) : t.push(null);
return {
outboundLayer: this.outboundLayer ? this.outboundLayer.name : null,
inboundLayers: t,
nodeIndices: this.nodeIndices,
tensorIndices: this.tensorIndices
};
}
}
let E2 = 0;
class Ct extends Uo {
constructor(t = {}) {
super(), this._callHook = null, this._addedWeightNames = [], this._stateful = !1, this.id = E2++, this.activityRegularizer = null, this.inputSpec = null, this.supportsMasking = !1, this._trainableWeights = [], this._nonTrainableWeights = [], this._losses = [], this._updates = [], this._built = !1, this.inboundNodes = [], this.outboundNodes = [];
let e = t.name;
if (!e) {
const s = this.getClassName();
e = Un(s) + "_" + Kl(s);
}
if (this.name = e, this.trainable_ = t.trainable == null ? !0 : t.trainable, t.inputShape != null || t.batchInputShape != null) {
let s;
if (t.batchInputShape != null)
s = t.batchInputShape;
else if (t.inputShape != null) {
let r = null;
t.batchSize != null && (r = t.batchSize), s = [r].concat(t.inputShape);
}
this.batchInputShape = s;
let o = t.dtype;
o == null && (o = t.inputDType), o == null && (o = "float32"), this.dtype = o;
}
t.weights != null ? this.initialWeights = t.weights : this.initialWeights = null, this._refCount = null, this.fastWeightInitDuringBuild = !1;
}
/**
* Converts a layer and its index to a unique (immutable type) name.
* This function is used internally with `this.containerNodes`.
* @param layer The layer.
* @param nodeIndex The layer's position (e.g. via enumerate) in a list of
* nodes.
*
* @returns The unique name.
*/
static nodeKey(t, e) {
return t.name + "_ib-" + e.toString();
}
/**
* Returns this.inboundNode at index nodeIndex.
*
* Porting note: This is a replacement for _get_node_attribute_at_index()
* @param nodeIndex
* @param attrName The name of the attribute related to request for this node.
*/
getNodeAtIndex(t, e) {
if (this.inboundNodes.length === 0)
throw new sn(`The layer has never been called and thus has no defined ${e}.`);
if (this.inboundNodes.length <= t)
throw new E(`Asked to get ${e} at node ${t}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);
return this.inboundNodes[t];
}
/**
* Retrieves the input tensor(s) of a layer at a given node.
*
* @param nodeIndex Integer, index of the node from which to retrieve the
* attribute. E.g. `nodeIndex=0` will correspond to the first time the layer
* was called.
*
* @return A tensor (or list of tensors if the layer has multiple inputs).
*/
getInputAt(t) {
return _e(this.getNodeAtIndex(t, "input").inputTensors);
}
/**
* Retrieves the output tensor(s) of a layer at a given node.
*
* @param nodeIndex Integer, index of the node from which to retrieve the
* attribute. E.g. `nodeIndex=0` will correspond to the first time the layer
* was called.
*
* @return A tensor (or list of tensors if the layer has multiple outputs).
*/
getOutputAt(t) {
return _e(this.getNodeAtIndex(t, "output").outputTensors);
}
// Properties
/**
* Retrieves the input tensor(s) of a layer.
*
* Only applicable if the layer has exactly one inbound node,
* i.e. if it is connected to one incoming layer.
*
* @return Input tensor or list of input tensors.
*
* @exception AttributeError if the layer is connected to more than one
* incoming layers.
*/
get input() {
if (this.inboundNodes.length > 1)
throw new Sn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);
if (this.inboundNodes.length === 0)
throw new Sn(`Layer ${this.name} is not connected, no input to return.`);
return _e(this.getNodeAtIndex(0, "input").inputTensors);
}
/**
* Retrieves the output tensor(s) of a layer.
*
* Only applicable if the layer has exactly one inbound node,
* i.e. if it is connected to one incoming layer.
*
* @return Output tensor or list of output tensors.
*
* @exception AttributeError if the layer is connected to more than one
* incoming layers.
*/
get output() {
if (this.inboundNodes.length === 0)
throw new Sn(`Layer ${this.name} has no inbound nodes.`);
if (this.inboundNodes.length > 1)
throw new Sn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);
return _e(this.getNodeAtIndex(0, "output").outputTensors);
}
get losses() {
return this._losses;
}
/**
* Retrieves the Layer's current loss values.
*
* Used for regularizers during training.
*/
calculateLosses() {
return this.losses.map((t) => t());
}
get updates() {
return this._updates;
}
get built() {
return this._built;
}
set built(t) {
this._built = t;
}
get trainable() {
return this.trainable_;
}
set trainable(t) {
this._trainableWeights.forEach((e) => e.trainable = t), this.trainable_ = t;
}
get trainableWeights() {
return this.trainable_ ? this._trainableWeights.filter((t) => t.trainable) : [];
}
set trainableWeights(t) {
this._trainableWeights = t;
}
get nonTrainableWeights() {
return this.trainable ? this._trainableWeights.filter((t) => !t.trainable).concat(this._nonTrainableWeights) : this._trainableWeights.concat(this._nonTrainableWeights);
}
set nonTrainableWeights(t) {
this._nonTrainableWeights = t;
}
/**
* The concatenation of the lists trainableWeights and nonTrainableWeights
* (in this order).
*/
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
get stateful() {
return this._stateful;
}
/**
* Reset the states of the layer.
*
* This method of the base Layer class is essentially a no-op.
* Subclasses that are stateful (e.g., stateful RNNs) should override this
* method.
*/
resetStates() {
if (!this.stateful)
throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.");
}
/**
* Checks compatibility between the layer and provided inputs.
*
* This checks that the tensor(s) `input`
* verify the input assumptions of the layer
* (if any). If not, exceptions are raised.
*
* @param inputs Input tensor or list of input tensors.
*
* @exception ValueError in case of mismatch between
* the provided inputs and the expectations of the layer.
*/
assertInputCompatibility(t) {
const e = Dt(t);
if (this.inputSpec == null || this.inputSpec.length === 0)
return;
const s = Dt(this.inputSpec);
if (e.length !== s.length)
throw new E(`Layer ${this.name} expects ${s.length} inputs, but it received ${e.length} input tensors. Input received: ${t}`);
for (let o = 0; o < e.length; o++) {
const r = e[o], i = s[o];
if (i == null)
continue;
const a = r.rank;
if (i.ndim != null && a !== i.ndim)
throw new E(`Input ${o} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${a}`);
if (i.maxNDim != null && a > i.maxNDim)
throw new E(`Input ${o} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${a}`);
if (i.minNDim != null && a < i.minNDim)
throw new E(`Input ${o} is incompatible with layer ${this.name}: expected min_ndim=${i.minNDim}, found ndim=${a}.`);
if (i.dtype != null && r.dtype !== i.dtype)
throw new E(`Input ${o} is incompatible with layer ${this.name} : expected dtype=${i.dtype}, found dtype=${r.dtype}.`);
if (i.axes) {
const l = r.shape;
for (const c in i.axes) {
const u = Number(c), h = i.axes[c], d = u >= 0 ? l[u] : l[l.length + u];
if (h != null && [h, null].indexOf(d) === -1)
throw new E(`Input ${o} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${h} but got shape ${l}.`);
}
}
if (i.shape != null)
for (let l = 0; l < i.shape.length; ++l) {
const c = i.shape[l], u = r.shape[l];
if (c != null && u != null && c !== u)
throw new E(`Input ${o} is incompatible with layer ${this.name}: expected shape=${i.shape}, found shape=${r.shape}.`);
}
}
}
/**
* This is where the layer's logic lives.
*
* @param inputs Input tensor, or list/tuple of input tensors.
* @param kwargs Additional keyword arguments.
*
* @return A tensor or list/tuple of tensors.
*/
call(t, e) {
return t;
}
invokeCallHook(t, e) {
this._callHook != null && this._callHook(t, e);
}
/**
* Set call hook.
* This is currently used for testing only.
* @param callHook
*/
setCallHook(t) {
this._callHook = t;
}
/**
* Clear call hook.
* This is currently used for testing only.
*/
clearCallHook() {
this._callHook = null;
}
/**
* Builds or executes a `Layer`'s logic.
*
* When called with `tf.Tensor`(s), execute the `Layer`'s computation and
* return Tensor(s). For example:
*
* ```js
* const denseLayer = tf.layers.dense({
* units: 1,
* kernelInitializer: 'zeros',
* useBias: false
* });
*
* // Invoke the layer's apply() method with a `tf.Tensor` (with concrete
* // numeric values).
* const input = tf.ones([2, 2]);
* const output = denseLayer.apply(input);
*
* // The output's value is expected to be [[0], [0]], due to the fact that
* // the dense layer has a kernel initialized to all-zeros and does not have
* // a bias.
* output.print();
* ```
*
* When called with `tf.SymbolicTensor`(s), this will prepare the layer for
* future execution. This entails internal book-keeping on shapes of
* expected Tensors, wiring layers together, and initializing weights.
*
* Calling `apply` with `tf.SymbolicTensor`s are typically used during the
* building of non-`tf.Sequential` models. For example:
*
* ```js
* const flattenLayer = tf.layers.flatten();
* const denseLayer = tf.layers.dense({units: 1});
*
* // Use tf.layers.input() to obtain a SymbolicTensor as input to apply().
* const input = tf.input({shape: [2, 2]});
* const output1 = flattenLayer.apply(input);
*
* // output1.shape is [null, 4]. The first dimension is the undetermined
* // batch size. The second dimension comes from flattening the [2, 2]
* // shape.
* console.log(JSON.stringify(output1.shape));
*
* // The output SymbolicTensor of the flatten layer can be used to call
* // the apply() of the dense layer:
* const output2 = denseLayer.apply(output1);
*
* // output2.shape is [null, 1]. The first dimension is the undetermined
* // batch size. The second dimension matches the number of units of the
* // dense layer.
* console.log(JSON.stringify(output2.shape));
*
* // The input and output can be used to construct a model that consists
* // of the flatten and dense layers.
* const model = tf.model({inputs: input, outputs: output2});
* ```
*
* @param inputs a `tf.Tensor` or `tf.SymbolicTensor` or an Array of them.
* @param kwargs Additional keyword arguments to be passed to `call()`.
*
* @return Output of the layer's `call` method.
*
* @exception ValueError error in case the layer is missing shape information
* for its `build` call.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
// Porting Note: This is a replacement for __call__() in Python.
apply(t, e) {
e = e || {}, this.assertNotDisposed();
const s = Dt(t), o = A2(t), r = F2(t);
if (o === r)
throw new E("Arguments to apply() must be all SymbolicTensors or all Tensors");
return zs(this.name, () => {
if (!this.built) {
this.assertInputCompatibility(t);
const i = [];
for (const a of Dt(t))
i.push(a.shape);
this.build(_e(i)), this.built = !0, this.initialWeights && this.setWeights(this.initialWeights), this._refCount === null && r && (this._refCount = 1);
}
if (this.assertInputCompatibility(t), r) {
let i = this.call(t, e);
this.supportsMasking && this.setMaskMetadata(t, i);
const a = Dt(i), l = [];
for (let c of a)
s.indexOf(c) !== -1 && (c = c.clone()), l.push(c);
if (i = _e(l), this.activityRegularizer != null)
throw new gt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");
return i;
} else {
const i = R2(t), a = this.computeOutputShape(i);
let l;
const c = D2(t);
if (this.warnOnIncompatibleInputShape(Array.isArray(t) ? i[0] : i), a != null && a.length > 0 && Array.isArray(a[0]) ? l = a.map((u, h) => new Pn(c, u, this, Dt(t), e, this.name, h)) : l = new Pn(c, a, this, Dt(t), e, this.name), this.addInboundNode(t, l, null, null, i, a, e), this._refCount++, this.activityRegularizer != null)
throw new gt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");
return l;
}
});
}
/**
* Check compatibility between input shape and this layer's batchInputShape.
*
* Print warning if any incompatibility is found.
*
* @param inputShape Input shape to be checked.
*/
warnOnIncompatibleInputShape(t) {
if (this.batchInputShape != null)
if (t.length !== this.batchInputShape.length)
console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(t)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);
else {
let e = !1;
this.batchInputShape.forEach((s, o) => {
s != null && t[o] != null && t[o] !== s && (e = !0);
}), e && console.warn(`The shape of the input tensor (${JSON.stringify(t)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`);
}
}
/**
* Retrieves the output shape(s) of a layer.
*
* Only applicable if the layer has only one inbound node, or if all inbound
* nodes have the same output shape.
*
* @returns Output shape or shapes.
* @throws AttributeError: if the layer is connected to more than one incoming
* nodes.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
get outputShape() {
if (this.inboundNodes == null || this.inboundNodes.length === 0)
throw new Sn(`The layer ${this.name} has never been called and thus has no defined output shape.`);
const t = [];
for (const e of this.inboundNodes) {
const s = JSON.stringify(e.outputShapes);
t.indexOf(s) === -1 && t.push(s);
}
if (t.length === 1) {
const e = this.inboundNodes[0].outputShapes;
return Array.isArray(e) && Array.isArray(e[0]) && e.length === 1 ? e[0] : e;
} else
throw new Sn(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`);
}
/**
* Counts the total number of numbers (e.g., float32, int32) in the
* weights.
*
* @returns An integer count.
* @throws RuntimeError: If the layer is not built yet (in which case its
* weights are not defined yet.)
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
countParams() {
if (!this.built)
throw new sn(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);
return ga(this.weights);
}
/**
* Creates the layer weights.
*
* Must be implemented on all layers that have weights.
*
* Called when apply() is called to construct the weights.
*
* @param inputShape A `Shape` or array of `Shape` (unused).
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
build(t) {
this.built = !0;
}
/**
* Returns the current values of the weights of the layer.
*
* @param trainableOnly Whether to get the values of only trainable weights.
* @returns Weight values as an `Array` of `tf.Tensor`s.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
getWeights(t = !1) {
return eu(t ? this.trainableWeights : this.weights);
}
/**
* Sets the weights of the layer, from Tensors.
*
* @param weights a list of Tensors. The number of arrays and their shape
* must match number of the dimensions of the weights of the layer (i.e.
* it should match the output of `getWeights`).
*
* @exception ValueError If the provided weights list does not match the
* layer's specifications.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
setWeights(t) {
_(() => {
const e = this.weights;
if (e.length !== t.length)
throw new E(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${t.length}, but the layer was expecting ${e.length} weights. Provided weights: ${t}...`);
if (e.length === 0)
return;
const s = [], o = eu(e);
for (let r = 0; r < o.length; ++r) {
const i = o[r], a = e[r], l = t[r];
if (!Et(i.shape, l.shape))
throw new E(`Layer weight shape ${i.shape} not compatible with provided weight shape ${l.shape}`);
s.push([a, l]);
}
Sd(s);
});
}
/**
* Adds a weight variable to the layer.
*
* @param name Name of the new weight variable.
* @param shape The shape of the weight.
* @param dtype The dtype of the weight.
* @param initializer An initializer instance.
* @param regularizer A regularizer instance.
* @param trainable Whether the weight should be trained via backprop or not
* (assuming that the layer itself is also trainable).
* @param constraint An optional trainable.
* @return The created weight variable.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
addWeight(t, e, s, o, r, i, a, l) {
if (this._addedWeightNames.indexOf(t) !== -1)
throw new E(`Duplicate weight name ${t} for layer ${this.name}`);
this._addedWeightNames.push(t), s == null && (s = "float32"), this.fastWeightInitDuringBuild && (o = l != null ? l() : Ut("zeros"));
const c = o.apply(e, s), u = new S2(c, s, t, i, a);
return c.dispose(), r != null && this.addLoss(() => r.apply(u.read())), i == null && (i = !0), i ? this._trainableWeights.push(u) : this._nonTrainableWeights.push(u), u;
}
/**
* Set the fast-weight-initialization flag.
*
* In cases where the initialized weight values will be immediately
* overwritten by loaded weight values during model loading, setting
* the flag to `true` saves unnecessary calls to potentially expensive
* initializers and speeds up the loading process.
*
* @param value Target value of the flag.
*/
setFastWeightInitDuringBuild(t) {
this.fastWeightInitDuringBuild = t;
}
/**
* Add losses to the layer.
*
* The loss may potentially be conditional on some inputs tensors,
* for instance activity losses are conditional on the layer's inputs.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
addLoss(t) {
t == null || Array.isArray(t) && t.length === 0 || (t = Dt(t), this._losses !== void 0 && this._losses !== null && this.losses.push(...t));
}
/**
* Computes the output shape of the layer.
*
* Assumes that the layer will be built to match that input shape provided.
*
* @param inputShape A shape (tuple of integers) or a list of shape tuples
* (one per output tensor of the layer). Shape tuples can include null for
* free dimensions, instead of an integer.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
computeOutputShape(t) {
return t;
}
/**
* Computes an output mask tensor.
*
* @param inputs Tensor or list of tensors.
* @param mask Tensor or list of tensors.
*
* @return null or a tensor (or list of tensors, one per output tensor of the
* layer).
*/
computeMask(t, e) {
if (!this.supportsMasking) {
if (e != null)
if (Array.isArray(e))
e.forEach((s) => {
if (s != null)
throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);
});
else
throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);
return null;
}
return e;
}
setMaskMetadata(t, e, s) {
if (!this.supportsMasking)
return;
const o = this.computeMask(t, s), r = Dt(e), i = Dt(o);
if (r.length !== i.length)
throw new Error(`${this.name} outputs ${r.length} tensors but ${r.length} masks for those tensors`);
for (let a = 0; a < r.length; a++)
r[a].kerasMask = i[a];
}
/**
* Internal method to create an inbound node for the layer.
*
* @param inputTensors List of input tensors.
* @param outputTensors List of output tensors.
* @param inputMasks List of input masks (a mask can be a tensor, or null).
* @param outputMasks List of output masks (a mask can be a tensor, or null).
* @param inputShapes List of input shape tuples.
* @param outputShapes List of output shape tuples.
* @param kwargs Dictionary of keyword arguments that were passed to the
* `call` method of the layer at the call that created the node.
*/
addInboundNode(t, e, s, o, r, i, a = null) {
const l = Dt(t);
e = Dt(e), s = Dt(s), o = Dt(o), r = ma(r), i = ma(i);
const c = [], u = [], h = [];
for (const d of l)
c.push(d.sourceLayer), u.push(d.nodeIndex), h.push(d.tensorIndex);
new Xl({
outboundLayer: this,
inboundLayers: c,
nodeIndices: u,
tensorIndices: h,
inputTensors: l,
outputTensors: e,
inputMasks: s,
outputMasks: o,
inputShapes: r,
outputShapes: i
}, a);
for (let d = 0; d < e.length; d++)
e[d].sourceLayer = this, e[d].nodeIndex = this.inboundNodes.length - 1, e[d].tensorIndex = d;
}
/**
* Returns the config of the layer.
*
* A layer config is a TS dictionary (serializable)
* containing the configuration of a layer.
* The same layer can be reinstantiated later
* (without its trained weights) from this configuration.
*
* The config of a layer does not include connectivity
* information, nor the layer class name. These are handled
* by 'Container' (one layer of abstraction above).
*
* Porting Note: The TS dictionary follows TS naming standards for
* keys, and uses tfjs-layers type-safe Enums. Serialization methods
* should use a helper function to convert to the pythonic storage
* standard. (see serialization_utils.convertTsToPythonic)
*
* @returns TS dictionary of configuration.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
getConfig() {
const t = { name: this.name, trainable: this.trainable };
return this.batchInputShape != null && (t.batchInputShape = this.batchInputShape), this.dtype != null && (t.dtype = this.dtype), t;
}
/**
* Dispose the weight variables that this Layer instance holds.
*
* @returns {number} Number of disposed variables.
*/
disposeWeights() {
return this.weights.forEach((t) => t.dispose()), this.weights.length;
}
assertNotDisposed() {
if (this._refCount === 0)
throw new Error(`Layer '${this.name}' is already disposed.`);
}
/**
* Attempt to dispose layer's weights.
*
* This method decreases the reference count of the Layer object by 1.
*
* A Layer is reference-counted. Its reference count is incremented by 1
* the first item its `apply()` method is called and when it becomes a part
* of a new `Node` (through calling the `apply()` method on a
* `tf.SymbolicTensor`).
*
* If the reference count of a Layer becomes 0, all the weights will be
* disposed and the underlying memory (e.g., the textures allocated in WebGL)
* will be freed.
*
* Note: If the reference count is greater than 0 after the decrement, the
* weights of the Layer will *not* be disposed.
*
* After a Layer is disposed, it cannot be used in calls such as `apply()`,
* `getWeights()` or `setWeights()` anymore.
*
* @returns A DisposeResult Object with the following fields:
* - refCountAfterDispose: The reference count of the Container after this
* `dispose()` call.
* - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed
* during this `dispose()` call.
* @throws {Error} If the layer is not built yet, or if the layer has already
* been disposed.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
dispose() {
if (!this.built)
throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);
if (this._refCount === null)
throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);
this.assertNotDisposed();
let t = 0;
return --this._refCount === 0 && (t = this.disposeWeights()), { refCountAfterDispose: this._refCount, numDisposedVariables: t };
}
}
function R2(n) {
n = Dt(n);
const t = [];
for (const e of n)
t.push(e.shape);
return _e(t);
}
function D2(n) {
return "float32";
}
function mx(n, t, e) {
if ((t == null || e != null && e > 0) && (t = n.sourceLayer, e = n.nodeIndex), t.inboundNodes.length === 0)
return [n];
{
const s = t.inboundNodes[e];
if (s.inboundLayers.length === 0)
return s.inputTensors;
{
const o = [];
for (let r = 0; r < s.inboundLayers.length; r++) {
const i = s.inputTensors[r], a = s.inboundLayers[r], l = s.nodeIndices[r], c = mx(i, a, l);
for (const u of c)
o.indexOf(u) === -1 && o.push(u);
}
return o;
}
}
}
function A2(n) {
let t = !0;
for (const e of Dt(n))
if (!(e instanceof Pn)) {
t = !1;
break;
}
return t;
}
function F2(n) {
let t = !0;
for (const e of Dt(n))
if (e instanceof Pn) {
t = !1;
break;
}
return t;
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class Fi extends Ct {
constructor(t) {
if (super({
dtype: t.dtype,
name: t.name != null ? t.name : Kl("input").toString()
}), t.batchSize == null && (t.batchSize = null), t.sparse == null && (t.sparse = !1), this.trainable = !1, this.built = !0, this.sparse = t.sparse, t.inputShape != null && t.batchInputShape != null)
throw new E("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");
let e = t.batchInputShape;
if (e == null) {
if (t.inputShape == null)
throw new E("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");
e = [t.batchSize].concat(t.inputShape);
} else if (t.batchSize != null)
throw new E("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");
const s = t.dtype || "float32";
this.batchInputShape = e, this.dtype = s, this.inputSpec = [{ shape: e }];
const o = new Pn(this.dtype, this.batchInputShape, this, [], {}, this.name);
o.nodeIndex = 0, o.tensorIndex = 0, new Xl({
outboundLayer: this,
inboundLayers: [],
nodeIndices: [],
tensorIndices: [],
inputTensors: [o],
outputTensors: [o],
inputMasks: [null],
outputMasks: [null],
inputShapes: [e],
outputShapes: [e]
});
}
apply(t, e) {
throw new E(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`);
}
dispose() {
return { refCountAfterDispose: this._refCount, numDisposedVariables: 0 };
}
getConfig() {
return {
batchInputShape: this.batchInputShape,
dtype: this.dtype,
sparse: this.sparse,
name: this.name
};
}
}
Fi.className = "InputLayer";
j(Fi);
function O2(n) {
if (n.batchShape == null && n.shape == null)
throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");
if (n.batchShape != null && n.shape != null)
throw new E("Please provide either a `shape` or `batchShape` argument to Input, but not both.");
let t = n.batchShape;
n.shape != null && t == null && (t = [null].concat(n.shape));
let e = n.dtype;
return e == null && (e = "float32"), new Fi({
batchInputShape: t,
name: n.name,
dtype: e,
sparse: n.sparse
}).inboundNodes[0].outputTensors[0];
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function _2(n, t) {
if (n.dtype == null || n.dtype === t.dtype)
return t;
try {
return st(t, n.dtype);
} catch {
throw new E(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${n.name}' (${n.dtype}).`);
}
}
class as {
/**
* Constructor, optionally does copy-construction.
* @param feeds An Array of `Feed`s, or another `FeedDict`, in which case
* copy-construction will be performed.
*/
constructor(t) {
if (this.id2Value = {}, this.id2Mask = {}, this.name2Id = {}, t instanceof as)
for (const e in t.id2Value)
this.id2Value[e] = t.id2Value[e], e in t.id2Mask && (this.id2Mask[e] = t.id2Mask[e]);
else {
if (t == null)
return;
for (const e of t)
this.add(e.key, e.value);
}
}
/**
* Add a key-value pair to the FeedDict.
*
* @param key The key of the feed.
* @param value The value of the tensor feed.
* @param mask The value of the mask feed (optional).
* @returns This `FeedDict`.
* @throws ValueError: If the key `SymbolicTensor` already exists in the
* `FeedDict`.
*/
add(t, e, s) {
if (this.id2Value[t.id] == null)
this.id2Value[t.id] = _2(t, e), this.name2Id[t.name] = t.id, s != null && (this.id2Mask[t.id] = s);
else
throw new E(`Duplicate key: name=${t.name}, id=${t.id}`);
return this;
}
/**
* Add a Feed to the FeedDict.
* @param feed The new `Feed` to add.
* @returns This `FeedDict`.
*/
addFeed(t) {
this.add(t.key, t.value);
}
/**
* Probe whether a key already exists in the FeedDict.
* @param key
*/
hasKey(t) {
return this.id2Value[t.id] != null;
}
/**
* Get all the SymbolicTensor available in this FeedDict.
*/
names() {
return Object.keys(this.name2Id);
}
/**
* Get the feed value for given key.
* @param key The SymbolicTensor, or its name (as a string), of which the
* value is sought.
* @returns If `key` exists, the corresponding feed value.
* @throws ValueError: If `key` does not exist in this `FeedDict`.
*/
getValue(t) {
if (t instanceof Pn) {
if (this.id2Value[t.id] == null)
throw new E(`Nonexistent key: ${t.name}`);
return this.id2Value[t.id];
} else {
const e = this.name2Id[t];
if (e == null)
throw new E(`Feed dict has no SymbolicTensor name: ${t}`);
return this.id2Value[e];
}
}
/**
* Get the feed mask for given key.
* @param key The SymbolicTensor, or its name (as a string), of which the
* value is sought.
* @returns If `key` exists, the corresponding feed mask.
* @throws ValueError: If `key` does not exist in this `FeedDict`.
*/
getMask(t) {
if (t instanceof Pn) {
if (this.id2Value[t.id] == null)
throw new E(`Nonexistent key: ${t.name}`);
return this.id2Mask[t.id];
} else {
const e = this.name2Id[t];
if (e == null)
throw new E(`Feed dict has no SymbolicTensor name: ${t}`);
return this.id2Mask[e];
}
}
/** Dispose all mask Tensors held by this object. */
disposeMasks() {
this.id2Mask != null && $t(this.id2Mask);
}
}
const xa = new Zg(), ba = new Zg();
function L2(n) {
xa?.setMaxEntries(n), ba?.setMaxEntries(n);
}
function ir(n, t, e, s) {
const o = e == null ? !1 : e.training, r = Array.isArray(n), i = r ? n : [n], a = i.map((f) => f.name), l = [], c = t.names();
for (const f of a)
c.indexOf(f) !== -1 ? l.push(t.getValue(f)) : l.push(null);
s != null && (s.maxNumTensors = -1 / 0, s.minNumTensors = 1 / 0);
const u = a.join(",") + "|" + t.names().sort().join(",");
let h = xa.get(u), d;
if (h == null) {
const f = M2(i, t);
h = f.sorted, d = f.recipientCounts, xa.put(u, h), ba.put(u, d);
}
d = {}, o || Object.assign(d, ba.get(u));
const p = new as(t);
for (let f = 0; f < h.length; ++f) {
if (s != null) {
const S = Vc().numTensors;
S > s.maxNumTensors && (s.maxNumTensors = S), S < s.minNumTensors && (s.minNumTensors = S);
}
const m = h[f], g = m.sourceLayer;
if (g instanceof Fi)
continue;
const x = [], b = [], w = [];
let y = !1;
for (const S of m.inputs) {
const T = p.getValue(S), F = p.getMask(S);
x.push(T), b.push(F), F != null && (y = !0), o || (d[S.name]--, d[S.name] === 0 && !t.hasKey(S) && a.indexOf(S.name) === -1 && !T.isDisposed && S.sourceLayer.stateful !== !0 && w.push(T));
}
y && (e = e || {}, e.mask = b[0]);
const C = Dt(g.apply(x, e));
let $ = null;
g.supportsMasking && ($ = g.computeMask(x, b));
const k = z2(m), v = Array.isArray(k) ? k : [k];
for (let S = 0; S < v.length; ++S) {
p.hasKey(v[S]) || p.add(v[S], C[S], Array.isArray($) ? $[0] : $);
const T = a.indexOf(v[S].name);
T !== -1 && (l[T] = C[S]);
}
o || $t(w);
}
return p.disposeMasks(), r ? l : l[0];
}
function M2(n, t) {
I(n != null && n.length > 0, () => "Expected at least one fetch, got none");
let e = [], s = {};
if (n.length === 1) {
const o = Op(n[0], t);
e = o.sorted, s = o.recipientMap;
} else {
const o = /* @__PURE__ */ new Set();
for (const r of n) {
const { sorted: i, recipientMap: a } = Op(r, t);
for (const l of i)
o.has(l.name) || (e.push(l), o.add(l.name));
for (const l in a)
s[l] == null && (s[l] = /* @__PURE__ */ new Set()), a[l].forEach((c) => s[l].add(c));
}
}
return {
sorted: e,
recipientCounts: P2(s)
};
}
function P2(n) {
const t = {};
for (const e in n)
t[e] = n[e].size;
return t;
}
function Op(n, t) {
const e = /* @__PURE__ */ new Set(), s = [], o = {};
for (const a of t.names())
e.add(a);
const r = [], i = [];
for (r.push(n); r.length > 0; ) {
const a = r[r.length - 1];
if (e.has(a.name)) {
r.pop();
continue;
}
const l = i[i.length - 1] === r.length - 1;
if (a.inputs.length === 0 || l)
r.pop(), s.push(a), e.add(a.name), l && i.pop();
else {
i.push(r.length - 1);
for (const c of a.inputs)
o[c.name] == null && (o[c.name] = /* @__PURE__ */ new Set()), o[c.name].add(a.name), !e.has(c.name) && r.push(c);
}
}
return { sorted: s, recipientMap: o };
}
function z2(n) {
let t;
if (n.sourceLayer.inboundNodes.length === 1)
t = n.sourceLayer.output;
else {
let e = null;
for (let s = 0; s < n.sourceLayer.inboundNodes.length; ++s)
for (const o of n.sourceLayer.inboundNodes[s].outputTensors)
if (o.id === n.id) {
e = s;
break;
}
t = n.sourceLayer.getOutputAt(e);
}
return t;
}
/**
* @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.
* =============================================================================
*/
const B2 = P();
B2.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES", () => 100, L2);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function Nd(n, t) {
return _(() => $e(ct(R(n, n), t, !0)));
}
class Oi extends Uo {
getConfig() {
return {};
}
}
class gx extends Oi {
constructor(t) {
super(), this.defaultMaxValue = 2, this.defaultAxis = 0, this.maxValue = t.maxValue != null ? t.maxValue : this.defaultMaxValue, this.axis = t.axis != null ? t.axis : this.defaultAxis;
}
apply(t) {
return _(() => {
const e = Nd(t, this.axis), s = Ye(e, 0, this.maxValue);
return R(t, ut(s, Y(oe(), e)));
});
}
getConfig() {
return { maxValue: this.maxValue, axis: this.axis };
}
}
gx.className = "MaxNorm";
j(gx);
class xx extends Oi {
constructor(t) {
super(), this.defaultAxis = 0, this.axis = t.axis != null ? t.axis : this.defaultAxis;
}
apply(t) {
return _(() => ut(t, Y(oe(), Nd(t, this.axis))));
}
getConfig() {
return { axis: this.axis };
}
}
xx.className = "UnitNorm";
j(xx);
class bx extends Oi {
apply(t) {
return ro(t);
}
}
bx.className = "NonNeg";
j(bx);
class yx extends Oi {
constructor(t) {
super(), this.defaultMinValue = 0, this.defaultMaxValue = 1, this.defaultRate = 1, this.defaultAxis = 0, this.minValue = t.minValue != null ? t.minValue : this.defaultMinValue, this.maxValue = t.maxValue != null ? t.maxValue : this.defaultMaxValue, this.rate = t.rate != null ? t.rate : this.defaultRate, this.axis = t.axis != null ? t.axis : this.defaultAxis;
}
apply(t) {
return _(() => {
const e = Nd(t, this.axis), s = Y(R(this.rate, Ye(e, this.minValue, this.maxValue)), R(1 - this.rate, e));
return R(t, ut(s, Y(oe(), e)));
});
}
getConfig() {
return {
minValue: this.minValue,
maxValue: this.maxValue,
rate: this.rate,
axis: this.axis
};
}
}
yx.className = "MinMaxNorm";
j(yx);
const _p = {
maxNorm: "MaxNorm",
minMaxNorm: "MinMaxNorm",
nonNeg: "NonNeg",
unitNorm: "UnitNorm"
};
function ie(n) {
return gd(n);
}
function Lp(n, t = {}) {
return Ei(n, nn.getMap().classNameMap, t, "constraint");
}
function ae(n) {
if (n == null)
return null;
if (typeof n == "string") {
const e = { className: n in _p ? _p[n] : n, config: {} };
return Lp(e);
} else
return n instanceof Oi ? n : Lp(n);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
async function Rs(n) {
if (n == null)
return;
const t = [], e = [], s = [];
for (const o in n) {
const r = n[o];
if (typeof r != "number") {
const i = r;
t.push(i.data()), e.push(o), s.push(i);
}
}
if (t.length > 0) {
const o = await Promise.all(t);
for (let r = 0; r < o.length; ++r)
n[e[r]] = o[r][0];
$t(s);
}
}
function wx(n) {
if (n != null)
for (const t in n) {
const e = n[t];
typeof e != "number" && e.dispose();
}
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
var Mp;
(function(n) {
n[n.SILENT = 0] = "SILENT", n[n.VERBOSE = 1] = "VERBOSE";
})(Mp || (Mp = {}));
const V2 = 125;
class xr {
constructor() {
this.validationData = null;
}
setParams(t) {
this.params = t;
}
async onEpochBegin(t, e) {
}
async onEpochEnd(t, e) {
}
async onBatchBegin(t, e) {
}
async onBatchEnd(t, e) {
}
async onTrainBegin(t) {
}
async onTrainEnd(t) {
}
// LayersModel needs to call Callback.setModel(), but cannot actually depend
// on Callback because that creates a cyclic dependency. Providing this no-op
// method on BaseCallback breaks the cycle: this way LayersModel can depend on
// BaseCallback but not on Callback. The argument is typed as `Container`
// (the superclass of LayersModel) to avoid recapitulating the cycle. Callback
// overrides this method and enforces that the argument is really a
// LayersModel.
setModel(t) {
}
}
class W2 {
// TODO(cais): When the need arises, uncomment the following lines and
// implement the queue for time values.
// private deltaTBatch: number;
// private deltaTsBatchBegin: Array<number>;
// private deltaTsBatchEnd: Array<number>;
/**
* Constructor of CallbackList.
* @param callbacks Array of `Callback` instances.
* @param queueLength Queue length for keeping running statistics over
* callback execution time.
*/
constructor(t, e = 10) {
t == null && (t = []), this.callbacks = t, this.queueLength = e;
}
append(t) {
this.callbacks.push(t);
}
setParams(t) {
for (const e of this.callbacks)
e.setParams(t);
}
setModel(t) {
for (const e of this.callbacks)
e.setModel(t);
}
/**
* Called at the start of an epoch.
* @param epoch Index of epoch.
* @param logs Dictionary of logs.
*/
async onEpochBegin(t, e) {
e == null && (e = {});
for (const s of this.callbacks)
await s.onEpochBegin(t, e);
}
/**
* Called at the end of an epoch.
* @param epoch Index of epoch.
* @param logs Dictionary of logs.
*/
async onEpochEnd(t, e) {
e == null && (e = {});
for (const s of this.callbacks)
await s.onEpochEnd(t, e);
}
/**
* Called right before processing a batch.
* @param batch Index of batch within the current epoch.
* @param logs Dictionary of logs.
*/
async onBatchBegin(t, e) {
e == null && (e = {});
for (const s of this.callbacks)
await s.onBatchBegin(t, e);
}
/**
* Called at the end of a batch.
* @param batch Index of batch within the current epoch.
* @param logs Dictionary of logs.
*/
async onBatchEnd(t, e) {
e == null && (e = {});
for (const s of this.callbacks)
await s.onBatchEnd(t, e);
}
/**
* Called at the beginning of training.
* @param logs Dictionary of logs.
*/
async onTrainBegin(t) {
t == null && (t = {});
for (const e of this.callbacks)
await e.onTrainBegin(t);
}
/**
* Called at the end of training.
* @param logs Dictionary of logs.
*/
async onTrainEnd(t) {
t == null && (t = {});
for (const e of this.callbacks)
await e.onTrainEnd(t);
}
}
class U2 extends xr {
constructor() {
super();
}
async onEpochBegin(t) {
this.seen = 0, this.totals = {};
}
async onBatchEnd(t, e) {
e == null && (e = {});
const s = e.size == null ? 0 : e.size;
this.seen += s;
for (const o in e) {
const r = e[o];
if (typeof r == "number")
this.totals.hasOwnProperty(o) || (this.totals[o] = 0), this.totals[o] = this.totals[o] + r * s;
else {
let i;
o in this.totals ? i = this.totals[o] : this.totals[o] = 0;
const a = _(() => Y(this.totals[o], R(r, s)));
this.totals[o] = a, i?.dispose();
}
}
}
async onEpochEnd(t, e) {
if (e != null)
for (const s of this.params.metrics)
this.totals[s] != null && (typeof this.totals[s] == "number" ? e[s] = this.totals[s] / this.seen : _(() => {
const o = R(ut(1, this.seen), this.totals[s]);
e[s] = o, this.totals[s].dispose(), Dn(e[s]);
}));
}
}
class G2 extends xr {
async onTrainBegin(t) {
this.epoch = [], this.history = {};
}
async onEpochEnd(t, e) {
e == null && (e = {}), this.epoch.push(t);
for (const s in e)
this.history[s] == null && (this.history[s] = []), this.history[s].push(e[s]);
}
/**
* Await the values of all losses and metrics.
*/
async syncData() {
const t = [], e = [], s = [];
for (const r in this.history) {
const i = this.history[r];
for (let a = 0; a < i.length; ++a)
if (typeof i[a] != "number") {
const l = i[a];
t.push(l.data()), e.push(r), s.push(a);
}
}
const o = await Promise.all(t);
for (let r = 0; r < o.length; ++r)
this.history[e[r]][s[r]].dispose(), this.history[e[r]][s[r]] = o[r][0];
}
}
class H2 extends xr {
constructor(t, e) {
if (super(), this.currentEpoch = 0, this.nowFunc = t.nowFunc, this.nextFrameFunc = t.nextFrameFunc || vg, this.yieldEvery = e || "auto", this.yieldEvery === "auto" && (this.yieldEvery = V2), this.yieldEvery === "never" && t.onYield != null)
throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");
Rc(this.yieldEvery) && (this.maybeWait = o2(this.maybeWait.bind(this), this.yieldEvery, this.nowFunc)), this.trainBegin = t.onTrainBegin, this.trainEnd = t.onTrainEnd, this.epochBegin = t.onEpochBegin, this.epochEnd = t.onEpochEnd, this.batchBegin = t.onBatchBegin, this.batchEnd = t.onBatchEnd, this.yield = t.onYield;
}
async maybeWait(t, e, s) {
const o = [];
this.yield != null && (await Rs(s), o.push(this.yield(t, e, s))), o.push(this.nextFrameFunc()), await Promise.all(o);
}
async onEpochBegin(t, e) {
this.currentEpoch = t, this.epochBegin != null && (await Rs(e), await this.epochBegin(t, e));
}
async onEpochEnd(t, e) {
const s = [];
this.epochEnd != null && (await Rs(e), s.push(this.epochEnd(t, e))), this.yieldEvery === "epoch" && s.push(this.nextFrameFunc()), await Promise.all(s);
}
async onBatchBegin(t, e) {
this.batchBegin != null && (await Rs(e), await this.batchBegin(t, e));
}
async onBatchEnd(t, e) {
const s = [];
this.batchEnd != null && (await Rs(e), s.push(this.batchEnd(t, e))), this.yieldEvery === "batch" ? s.push(this.nextFrameFunc()) : Rc(this.yieldEvery) && s.push(this.maybeWait(this.currentEpoch, t, e)), await Promise.all(s);
}
async onTrainBegin(t) {
this.trainBegin != null && (await Rs(t), await this.trainBegin(t));
}
async onTrainEnd(t) {
this.trainEnd != null && (await Rs(t), await this.trainEnd(t));
}
}
function Cx(n, t) {
return n == null && (n = {}), n instanceof xr ? [n] : Array.isArray(n) && n[0] instanceof xr ? n : Dt(n).map((s) => new H2(s, t));
}
class en {
/**
* Blocks public access to constructor.
*/
constructor() {
}
/**
* Register a tf.LayersModel.fit() callback constructor.
*
* The registered callback constructor will be used to instantiate
* callbacks for every tf.LayersModel.fit() call afterwards.
*
* @param verbosityLevel Level of verbosity at which the `callbackConstructor`
* is to be reigstered.
* @param callbackConstructor A no-arg constructor for `tf.Callback`.
* @throws Error, if the same callbackConstructor has been registered before,
* either at the same or a different `verbosityLevel`.
*/
static registerCallbackConstructor(t, e) {
I(t >= 0 && Number.isInteger(t), () => `Verbosity level is expected to be an integer >= 0, but got ${t}`), en.checkForDuplicate(e), en.constructors[t] == null && (en.constructors[t] = []), en.constructors[t].push(e);
}
static checkForDuplicate(t) {
for (const e in en.constructors)
en.constructors[+e].forEach((o) => {
if (o === t)
throw new E("Duplicate callback constructor.");
});
}
/**
* Clear all registered callback constructors.
*/
static clear() {
en.constructors = {};
}
/**
* Create callbacks using the registered callback constructors.
*
* Given `verbosityLevel`, all constructors registered at that level or above
* will be called and the instantiated callbacks will be used.
*
* @param verbosityLevel: Level of verbosity.
*/
static createCallbacks(t) {
const e = [];
for (const s in en.constructors) {
const o = +s;
t >= o && e.push(...en.constructors[o]);
}
return e.map((s) => new s());
}
}
en.constructors = {};
function $x(n, t, e, s, o, r, i, a, l) {
const c = new G2(), u = [
new U2(),
...en.createCallbacks(t)
];
n != null && u.push(...n), u.push(c);
const h = new W2(u);
return h.setParams({
epochs: e,
initialEpoch: s,
samples: o,
steps: r,
batchSize: i,
verbose: t,
doValidation: a,
metrics: l
}), { callbackList: h, history: c };
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function Kn(n, t = {}, e = !1) {
return Ei(n, nn.getMap().classNameMap, t, "layer", e);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function ya(n, t) {
return _(() => {
n.dtype !== "float32" && (n = st(n, "float32"));
const e = ct(Di(n), t, !0), s = Pl(e.shape, oe()), o = $e(Is(e, s));
return ut(n, o);
});
}
function ql(n, t) {
return _(() => ee(Di(pt(t, n)), -1));
}
function Td(n, t) {
return _(() => ee(Ne(pt(t, n)), -1));
}
function Ed(n, t) {
return _(() => {
const e = pt(n, t), s = Ye(Ne(n), oe(), Number.MAX_VALUE), o = Ne(ut(e, s));
return R(100, ee(o, -1));
});
}
function K2(n, t) {
return _(() => {
const e = Ye(t, oe(), Number.MAX_VALUE), s = Mn(Y(1, e)), o = Ye(n, oe(), Number.MAX_VALUE), r = Mn(Y(1, o));
return ee(Di(pt(s, r)), -1);
});
}
function j2(n, t) {
return _(() => {
const e = Is(0, pt(1, R(n, t)));
return ee(Di(e), -1);
});
}
function X2(n, t) {
return _(() => {
const e = Is(0, pt(1, R(n, t)));
return ee(e, -1);
});
}
function q2(n, t) {
return _(() => {
const e = ct(R(n, t), -1), s = bn(R(pt(1, n), t), -1);
return Is(0, Y(1, pt(s, e)));
});
}
function Y2(n, t) {
return _(() => {
const e = Math.log(2), s = pt(t, n), o = pt(Y(s, $i(R(-2, s))), e);
return ee(o, -1);
});
}
function br(n, t, e = !1) {
return _(() => {
if (e)
t = Fh(t);
else {
const s = ct(t, t.shape.length - 1, !0);
t = ut(t, s);
}
return t = Ye(t, oe(), 1 - oe()), Yt(ct(R(st(n, "float32"), Mn(t)), t.shape.length - 1));
});
}
function wa(n, t, e = !1) {
return _(() => {
const s = st(Vl(g2(n)), "int32");
t = Ye(t, oe(), 1 - oe());
const o = t.shape, r = A(Xm(s, o[o.length - 1]), o);
return br(r, t, e);
});
}
function J2(n, t) {
if (!Et(n.shape, t.shape))
throw new E(`logits and labels must have the same shape, but got shapes ${JSON.stringify(n.shape)} and ${JSON.stringify(t.shape)}`);
return _(() => {
const e = ro(t), s = Yt(Ne(t));
return Y(pt(e, R(t, n)), Gm(Ln(s)));
});
}
function Yl(n, t) {
return _(() => {
let e;
return e = Ye(t, oe(), 1 - oe()), e = Mn(ut(e, pt(1, e))), ee(J2(n, e), -1);
});
}
function Z2(n, t) {
return _(() => {
const e = Ye(n, oe(), 1), s = Ye(t, oe(), 1);
return ct(R(n, Mn(ut(e, s))), -1);
});
}
function Q2(n, t) {
return _(() => {
const e = Mn(Y(oe(), t));
return ee(pt(t, R(n, e)), -1);
});
}
function Ix(n, t) {
return _(() => {
const e = ya(n, -1), s = ya(t, -1), o = R(e, s);
return Yt(ct(o, -1));
});
}
const Ca = {
meanSquaredError: ql,
meanAbsoluteError: Td,
meanAbsolutePercentageError: Ed,
meanSquaredLogarithmicError: K2,
squaredHinge: j2,
hinge: X2,
categoricalHinge: q2,
logcosh: Y2,
categoricalCrossentropy: br,
sparseCategoricalCrossentropy: wa,
binaryCrossentropy: Yl,
kullbackLeiblerDivergence: Z2,
poisson: Q2,
cosineProximity: Ix
};
function yc(n) {
if (typeof n == "string") {
if (n in Ca)
return Ca[n];
let t = `Unknown loss ${n}`;
throw n.toLowerCase().includes("softmaxcrossentropy") && (t = `Unknown loss ${n}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`), new E(t);
} else
return n;
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function kx(n, t) {
return _(() => {
const e = R(0.5, an(t)), s = Fn(Je(t, e), n.dtype);
return ee(_n(n, s), -1);
});
}
function vx(n, t) {
return _(() => Fn(_n(dr(n, -1), dr(t, -1)), "float32"));
}
function tT(n, t) {
return _(() => st(ct(jn(_n(n, 1), _n(t, 1))), "float32"));
}
function eT(n, t) {
return _(() => st(ct(jn(_n(n, 0), _n(t, 1))), "float32"));
}
function nT(n, t) {
return _(() => {
const e = tT(n, t), s = eT(n, t), o = Y(e, s);
return st(Re(Je(o, 0), ut(e, o), 0), "float32");
});
}
function sT(n, t) {
return Yl(n, t);
}
function oT(n, t) {
return n.rank === t.rank && (n = ki(n, [n.rank - 1])), t = dr(t, -1), t.dtype !== n.dtype && (t = st(t, n.dtype)), st(_n(n, t), "float32");
}
const rT = ql, iT = ql, aT = Td, lT = Td, cT = Ed, uT = Ed, Sx = br, hT = Ix, Nx = wa, $a = {
binaryAccuracy: kx,
categoricalAccuracy: vx,
precision: nT,
categoricalCrossentropy: Sx,
sparseCategoricalCrossentropy: Nx,
mse: rT,
MSE: iT,
mae: aT,
MAE: lT,
mape: cT,
MAPE: uT,
cosine: hT
};
function dT(n) {
if (typeof n == "string" && n in $a)
return $a[n];
if (typeof n != "string" && n != null)
return n;
throw new E(`Unknown metric ${n}`);
}
function Xi(n) {
if (Nn(n !== null, `Unknown LossOrMetricFn ${n}`), typeof n == "string")
return n;
{
let t;
for (const e of Object.keys(Ca))
if (Ca[e] === n) {
t = e;
break;
}
if (t !== void 0)
return t;
for (const e of Object.keys($a))
if ($a[e] === n) {
t = e;
break;
}
return t !== void 0 ? t : n.name;
}
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function pT(n) {
const t = {
Adagrad: () => fo.adagrad(0.01),
Adadelta: () => fo.adadelta(1, 0.95, oe()),
Adam: () => fo.adam(1e-3, 0.9, 0.999, oe()),
Adamax: () => fo.adamax(2e-3, 0.9, 0.999, oe(), 0),
RMSProp: () => fo.rmsprop(1e-3, 0.9, 0, oe()),
SGD: () => fo.sgd(0.01)
};
if (t.adagrad = t.Adagrad, t.adadelta = t.Adadelta, t.adam = t.Adam, t.adamax = t.Adamax, t.rmsprop = t.RMSProp, t.sgd = t.SGD, n in t)
return t[n]();
throw new E(`Unknown Optimizer ${n}`);
}
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const Pp = 1 * 1024 * 1024;
function zp(n, t, e = !1) {
if (n == null || typeof n != "object" || Object.getPrototypeOf(n) !== Object.prototype || !nu(n))
throw new Error("User-defined metadata is expected to be a JSON object, but is not.");
if (e) {
const s = JSON.stringify(n);
s.length > Pp && console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${Pp}.`);
}
}
function nu(n) {
if (n === null)
return !0;
if (typeof n == "object")
if (Object.getPrototypeOf(n) === Object.prototype) {
const t = Object.keys(n);
for (const e of t)
if (typeof e != "string" || !nu(n[e]))
return !1;
return !0;
} else if (Array.isArray(n)) {
for (const t of n)
if (!nu(t))
return !1;
return !0;
} else
return !1;
else {
const t = typeof n;
return t === "string" || t === "number" || t === "boolean";
}
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function fT(n, t, e, s = console.log) {
const o = gT(n), r = ["Layer (type)", "Input Shape", "Output shape", "Param #"];
o ? (t = t || 90, e = e || [0.32, 0.61, 0.89, 1]) : (t = t || 115, e = e || [0.24, 0.48, 0.7, 0.8, 1]), e[e.length - 1] <= 1 && (e = e.map((u) => Math.floor(t * u)));
let i;
if (!o) {
r.push("Receives inputs"), i = [];
for (const u in n.nodesByDepth)
i.push(...n.nodesByDepth[u]);
}
s("_".repeat(t)), Ia(r, e, s), s("=".repeat(t));
const a = n.layers;
for (let u = 0; u < a.length; ++u)
o ? xT(a[u], e, s) : bT(a[u], e, i, s), s((u === a.length - 1 ? "=" : "_").repeat(t));
n.checkTrainableWeightsConsistency();
const l = mT(n), c = ga(n.nonTrainableWeights);
s(`Total params: ${l + c}`), s(`Trainable params: ${l}`), s(`Non-trainable params: ${c}`), s("_".repeat(t));
}
function mT(n) {
let t;
return n.collectedTrainableWeights != null ? t = ga(n.collectedTrainableWeights) : t = ga(n.trainableWeights), t;
}
function gT(n) {
let t = !0;
const e = [], s = [];
for (const o in n.nodesByDepth)
e.push(n.nodesByDepth[o]);
for (const o of e) {
if (o.length > 1 || o.length === 1 && o[0].inboundLayers.length > 1) {
t = !1;
break;
}
s.push(...o);
}
if (t)
for (const o of n.layers) {
let r = !1;
for (const i of o.inboundNodes)
if (s.indexOf(i) !== -1)
if (r) {
t = !1;
break;
} else
r = !0;
if (!t)
break;
}
return t;
}
function Ia(n, t, e = console.log) {
let s = "";
for (let o = 0; o < n.length; ++o)
o > 0 && (s = s.slice(0, s.length - 1) + " "), s += n[o], s = s.slice(0, t[o]), s += " ".repeat(t[o] - s.length);
e(s);
}
function xT(n, t, e) {
let s, o;
try {
o = n.inboundNodes.map((l) => JSON.stringify(l.inputShapes)).join(",");
} catch {
o = "multiple";
}
try {
s = JSON.stringify(n.outputShape);
} catch {
s = "multiple";
}
const r = n.name, i = n.getClassName(), a = [
`${r} (${i})`,
o,
s,
n.countParams().toString()
];
Ia(a, t, e);
}
function bT(n, t, e, s) {
let o, r;
try {
r = n.inboundNodes.map((h) => JSON.stringify(h.inputShapes)).join(",");
} catch {
r = "multiple";
}
try {
o = JSON.stringify(n.outputShape);
} catch {
o = "multiple";
}
const i = [];
for (const h of n.inboundNodes)
if (!(e != null && e.length > 0 && e.indexOf(h) === -1))
for (let d = 0; d < h.inboundLayers.length; ++d) {
const p = h.inboundLayers[d].name, f = h.nodeIndices[d], m = h.tensorIndices[d];
i.push(`${p}[${f}][${m}]`);
}
const a = n.name, l = n.getClassName(), c = i.length === 0 ? "" : i[0], u = [
`${a} (${l})`,
r,
o,
n.countParams().toString(),
c
];
Ia(u, t, s);
for (let h = 1; h < i.length; ++h)
Ia(["", "", "", "", i[h]], t, s);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function Tx(n, t, e) {
return (n === "inboundNodes" || n === "outputLayers" || n === "inputLayers") && t === 0 && typeof e == "string";
}
function su(n, t) {
if (n === null)
return null;
if (typeof n == "string")
return Os(n);
if (typeof n == "number" || typeof n == "boolean")
return n;
if (n instanceof Array) {
const e = [], s = n.length;
for (let o = 0; o < s; ++o) {
const r = n[o];
Tx(t, o, r) ? e.push(r) : e.push(su(r, t));
}
return e;
} else {
const e = {};
for (const s of Object.keys(n)) {
const o = n[s];
if (s === "name" && typeof o == "string")
e[s] = o;
else {
const r = Os(s);
e[r] = su(o, r);
}
}
return e;
}
}
function ou(n, t) {
if (n == null)
return null;
if (typeof n == "string")
return Un(n);
if (typeof n == "number" || typeof n == "boolean")
return n;
if (n instanceof Array) {
const e = [], s = n.length;
for (let o = 0; o < s; ++o) {
const r = n[o];
Tx(t, o, r) ? e.push(r) : e.push(ou(r, t));
}
return e;
} else {
const e = {};
for (const s of Object.keys(n)) {
const o = n[s], r = Un(s);
(s === "name" || s === "className") && typeof o == "string" ? e[r] = o : e[r] = ou(o, s);
}
return e;
}
}
/** @license See the LICENSE file. */
const Ex = "4.22.0";
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const yT = (n) => {
const t = Object.keys(n);
if (t.length === 0)
return !1;
const e = t[0].split("/");
return !isNaN(parseInt(e[e.length - 1], 10));
};
class pn extends Ct {
constructor(t) {
if (super({}), this.containerNodes = /* @__PURE__ */ new Set(), this.name = t.name, this.name == null) {
const b = this.getClassName().toLowerCase();
this.name = Kl(b);
}
if (this.supportsMasking = !1, this.trainable_ = !0, Array.isArray(t.inputs) ? this.inputs = t.inputs.slice() : this.inputs = [t.inputs], Array.isArray(t.outputs) ? this.outputs = t.outputs.slice() : this.outputs = [t.outputs], hs(this.inputs).length !== this.inputs.length)
throw new E(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((b) => b.name)}`);
hs(this.outputs).length !== this.outputs.length && console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((b) => b.name)}`), this.inputLayers = [], this.inputLayersNodeIndices = [], this.inputLayersTensorIndices = [], this.outputLayers = [], this.outputLayersNodeIndices = [], this.outputLayersTensorIndices = [], this.layers = [], this.internalContainerRefs = [];
for (const b of this.outputs) {
const w = b.sourceLayer, y = b.nodeIndex, C = b.tensorIndex;
this.outputLayers.push(w), this.outputLayersNodeIndices.push(y), this.outputLayersTensorIndices.push(C);
}
for (const b of this.inputs) {
const w = b.sourceLayer, y = b.nodeIndex, C = b.tensorIndex;
Nn(y === 0, "input layer has >1 nodes"), Nn(C === 0, "input layer has >1 tensors"), this.inputLayers.push(w), this.inputLayersNodeIndices.push(y), this.inputLayersTensorIndices.push(C);
}
this.inputNames = [], this.outputNames = [], this.feedInputShapes = [], this.feedInputNames = [], this.feedOutputNames = [];
for (let b = 0; b < this.inputLayers.length; b++) {
const w = this.inputLayers[b];
if (!(w instanceof Fi))
throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${t.inputs}. Input ${b} (0-based) originates from layer type ${w.getClassName()}.`);
this.inputNames.push(w.name), this.feedInputShapes.push(w.batchInputShape), this.feedInputNames.push(w.name);
}
for (const b of this.outputLayers)
this.outputNames.push(b.name);
this.internalInputShapes = this.inputs.map((b) => b.shape), this.internalOutputShapes = this.outputs.map((b) => b.shape);
const e = {}, s = {}, o = {}, r = {}, i = {}, a = [], l = (b, w, y, C, $, k) => {
(C == null || $ == null || k == null) && (C = b.sourceLayer, $ = b.nodeIndex, k = b.tensorIndex);
const v = C.inboundNodes[$];
if (y.indexOf(v) !== -1)
throw new sn(`The tensor ${b.name} at layer "${C.name}" is part of a cycle.`);
if (w.indexOf(v) !== -1)
return;
this.containerNodes.add(pn.nodeKey(C, $)), C.id in i || (i[C.id] = Object.keys(i).length), y.indexOf(v) === -1 && y.push(v);
const S = v.inboundLayers.length;
for (let T = 0; T < S; T++) {
const F = v.inputTensors[T], L = v.inboundLayers[T], M = v.nodeIndices[T], B = v.tensorIndices[T];
l(F, w, y, L, M, B);
}
for (w.push(v); y.indexOf(v) >= 0; )
y.splice(y.indexOf(v), 1);
a.push(v);
}, c = [], u = [];
for (const b of this.outputs)
l(b, c, u);
const h = a.slice().reverse();
for (const b of h) {
s[b.id] = b, b.id in e || (e[b.id] = 0);
let w = e[b.id];
const y = o[b.outboundLayer.id] == null ? 0 : o[b.outboundLayer.id];
w = Math.max(w, y), o[b.outboundLayer.id] = w, r[b.outboundLayer.id] = b.outboundLayer, e[b.id] = w;
for (let C = 0; C < b.inboundLayers.length; C++) {
const $ = b.inboundLayers[C], k = b.nodeIndices[C], v = $.inboundNodes[k], S = e[v.id] == null ? 0 : e[v.id];
e[v.id] = Math.max(w + 1, S), s[v.id] = v;
}
}
const d = {};
for (const b in e) {
const w = e[b];
w in d || (d[w] = []), d[w].push(s[b]);
}
const p = {};
for (const b in o) {
const w = o[b];
w in p || (p[w] = []), p[w].push(r[b]);
}
let f = Object.keys(p).map((b) => parseInt(b, 10)).sort(Hi);
this.layers = [];
for (const b of f) {
const w = p[b];
w.sort((y, C) => {
const $ = i[y.id], k = i[C.id];
return $ < k ? -1 : $ > k ? 1 : 0;
});
for (const y of w)
y instanceof pn && this.internalContainerRefs.push(y), this.layers.push(y);
}
this.layersByDepth = p, f = Object.keys(d).map((b) => parseInt(b, 10)).sort(Hi);
const m = this.inputs.slice(), g = [];
for (const b of f)
for (const w of d[b]) {
const y = w.outboundLayer;
if (y != null) {
for (const C of w.inputTensors)
if (m.indexOf(C) === -1)
throw new sn(`Graph disconnected: cannot obtain value for tensor ${C} at layer "${y.name}". The following previous layers were accessed without issue: ${g}`);
for (const C of w.outputTensors)
m.push(C);
g.push(y.name);
}
}
this.nodesByDepth = d;
const x = this.layers.map((b) => b.name);
for (const b of x) {
const w = x.filter((y) => y === b).length;
if (w !== 1)
throw new sn(`The name "${b}" is used ${w} times in the model. All layer names should be unique. Layer names: ` + JSON.stringify(x));
}
this.outboundNodes = [], this.inboundNodes = [], new Xl({
outboundLayer: this,
inboundLayers: [],
nodeIndices: [],
tensorIndices: [],
inputTensors: this.inputs,
outputTensors: this.outputs,
inputMasks: this.inputs.map((b) => null),
outputMasks: this.outputs.map((b) => null),
inputShapes: this.inputs.map((b) => b.shape),
outputShapes: this.outputs.map((b) => b.shape)
}), this.built = !0, this._refCount = 1;
}
assertNotDisposed() {
if (this._refCount === 0)
throw new Error(`Container '${this.name}' is already disposed.`);
}
/**
* Attempt to dispose a LayersModel's weights.
*
* This method decrease the reference count of the LayersModel object by 1.
*
* A LayersModel is reference-counted. Its reference count is incremented by 1
* when it is first constructed and when it is used as a Layer of another
* LayersModel.
*
* If the reference count of a LayersModel becomes 0, the `dispose` method of
* all its constituent `Layer`s will be called.
*
* Note: If the reference count is greater than 0 after the decrement, the
* `dispose` method of its constituent `Layer`s will *not* be called.
*
* After a LayersModel is disposed, it cannot be used in calls such as
* 'predict`, `evaluate` or `fit` anymore.
*
* @returns A DisposeResult Object with the following fields:
* - refCountAfterDispose: The reference count of the LayersModel after this
* `dispose()` call.
* - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed
* during this `dispose()` call.
* @throws {Error} If the layer is not built yet, or if the LayersModel has
* already been disposed.
*/
dispose() {
this.assertNotDisposed();
const t = { refCountAfterDispose: null, numDisposedVariables: 0 };
if (--this._refCount === 0) {
for (const e of this.layers)
t.numDisposedVariables += e.dispose().numDisposedVariables;
for (const e of this.internalContainerRefs)
t.numDisposedVariables += e.dispose().numDisposedVariables;
}
return t.refCountAfterDispose = this._refCount, t;
}
get trainable() {
return this.trainable_;
}
set trainable(t) {
this.layers.forEach((e) => {
e._trainableWeights.forEach((s) => s.trainable = t);
}), this.trainable_ = t;
}
get trainableWeights() {
if (this._trainableWeights.length > 0)
throw new E("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");
if (!this.trainable)
return [];
let t = [];
for (const e of this.layers)
t = t.concat(e.trainableWeights);
return t;
}
get nonTrainableWeights() {
const t = [];
for (const e of this.layers)
t.push(...e.nonTrainableWeights);
if (!this.trainable) {
const e = [];
for (const s of this.layers)
e.push(...s.trainableWeights);
return e.concat(t);
}
return t;
}
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
/**
* Loads all layer weights from a JSON object.
*
* Porting Note: HDF5 weight files cannot be directly loaded in JavaScript /
* TypeScript. The utility script at `scripts/pykeras.py` offers means
* to convert them into JSON strings compatible with this method.
* Porting Note: TensorFlow.js Layers supports only loading by name currently.
*
* @param weights A JSON mapping weight names to weight values as nested
* arrays of numbers, or a `NamedTensorMap`, i.e., a JSON mapping weight
* names to `tf.Tensor` objects.
* @param strict Require that the provided weights exactly match those
* required by the container. Default: `true`. Passing `false` means that
* extra weights and missing weights will be silently ignored.
*/
loadWeights(t, e = !0) {
const s = {};
let o = 0;
const r = yT(t);
r && this.parseWeights(t);
for (const a of this.layers)
for (const [l, c] of a.weights.entries()) {
const u = r ? `${c.name.split("/").slice(0, -1).join("/") + "/"}${l}` : c.originalName;
if (s[u] != null)
throw new E(`Duplicate weight name: ${u}`);
s[u] = c, o++;
}
const i = [];
for (const a in t) {
let l = a;
if (s[a] == null) {
const c = a.split("/");
l = c.slice(0, -2).concat([c[c.length - 1]]).join("/");
}
if (s[l] != null)
i.push([s[l], t[a]]);
else if (e)
throw new E(`Provided weight data has no target variable: ${a}`);
delete s[l];
}
if (e) {
const a = [];
for (const l in s)
a.push(l);
if (a.length > 0)
throw new E(`${a.length} of ${o} weights are not set: ${a}`);
}
Sd(i);
}
parseWeights(t) {
for (const e in Object.keys(t)) {
const s = e.split("/"), o = ["vars", "layer_checkpoint_dependencies"], r = s.map((i) => i.startsWith("_") ? i.slice(1) : i).filter((i) => !o.includes(i)).join("/");
r !== e && (t[r] = t[e], delete t[e]);
}
}
/**
* Util shared between different serialization methods.
* @returns LayersModel config with Keras version information added.
*/
updatedConfig() {
const t = this.getConfig(), e = {};
return e.className = this.getClassName(), e.config = t, e.kerasVersion = `tfjs-layers ${Ex}`, e.backend = "TensorFlow.js", e;
}
/**
* Returns a JSON string containing the network configuration.
*
* To load a network from a JSON save file, use
* models.modelFromJSON(jsonString);
* @param extraJsonArgs Unused in tfjs-layers, maintained for PyKeras
* @param returnString Whether the return value should be stringified
* (default: `true`).
* @returns a JSON string if `returnString` (default), or a JSON object if
* `!returnString`.
*/
// tslint:disable-next-line:no-any
toJSON(t, e = !0) {
const s = ou(this.updatedConfig());
return e ? JSON.stringify(s) : s;
}
/**
* Call the model on new inputs.
*
* In this case `call` just reapplies all ops in the graph to the new inputs
* (e.g. build a new computational graph from the provided inputs).
*
* @param inputs A tensor or list of tensors.
* @param mask A mask or list of masks. A mask can be either a tensor or null
* (no mask).
*
* @return A tensor if there is a single output, or a list of tensors if there
* are more than one outputs.
*/
call(t, e) {
return _(() => {
t = Dt(t);
const s = new as();
for (let o = 0; o < this.inputs.length; ++o)
s.add(this.inputs[o], t[o]);
return ir(this.outputs, s, e);
});
}
/**
* Computes an output mask tensor.
*
* @param inputs Tensor or list of tensors.
* @param mask Tensor or list of tensors.
*
* @return null or a tensor (or list of tensors, one per output tensor of the
* layer).
*/
computeMask(t, e) {
return _(() => {
t = Dt(t);
let s;
return e == null ? s = Js(null, t.length) : s = Dt(e), this.runInternalGraph(t, s)[1];
});
}
/**
* Computes the output shape of the layer.
*
* Assumes that the layer will be built to match that input shape provided.
*
* @param inputShape A shape (tuple of integers) or a list of shape tuples
* (one per output tensor of the layer). Shape tuples can include null for
* free dimensions, instead of an integer.
*/
computeOutputShape(t) {
const e = ma(t);
if (e.length !== this.inputLayers.length)
throw new E(`Invalid inputShape argument ${t}: model has ${this.inputLayers.length} tensor inputs.`);
const s = {};
for (let a = 0; a < e.length; a++) {
const l = this.inputLayers[a], c = e[a], u = l.name + "_0_0";
s[u] = c;
}
const o = Object.keys(this.nodesByDepth).map((a) => parseInt(a, 10)).sort(Hi);
if (o.length > 1)
for (const a of o) {
const l = this.nodesByDepth[a];
for (const c of l) {
const u = c.outboundLayer;
if (this.inputLayers.map((m) => m.id).indexOf(u.id) !== -1)
continue;
const h = [];
for (let m = 0; m < c.inboundLayers.length; m++) {
const g = c.inboundLayers[m], x = c.nodeIndices[m], b = c.tensorIndices[m], w = `${g.name}_${x}_${b}`, y = s[w];
h.push(y);
}
const d = u.computeOutputShape(_e(h)), p = ma(d), f = u.inboundNodes.indexOf(c);
for (let m = 0; m < p.length; m++) {
const g = `${u.name}_${f}_${m}`;
s[g] = p[m];
}
}
}
const r = [], i = [];
for (let a = 0; a < this.outputLayers.length; a++) {
const l = this.outputLayers[a], c = this.outputLayersNodeIndices[a], u = this.outputLayersTensorIndices[a], h = `${l.name}_${c}_${u}`;
i.push(h);
}
for (let a = 0; a < i.length; a++) {
const l = i[a];
Nn(l in s), r.push(s[l]);
}
return _e(r);
}
/**
* Computes output tensors for new inputs.
*
* Note:
* - Expects `inputs` to be a list (potentially with 1 element).
*
* @param inputs List of tensors
* @param masks List of masks (tensors or null).
* @return Three lists: outputTensors, outputMasks, outputShapes
*/
runInternalGraph(t, e) {
e == null && (e = Js(null, t.length));
const s = {};
for (let l = 0; l < this.inputs.length; ++l) {
const c = this.inputs[l], u = t[l], h = e[l];
s[c.id] = [u, h];
}
const o = Object.keys(this.nodesByDepth).map((l) => parseInt(l, 10)).sort(Hi);
for (const l of o) {
const c = this.nodesByDepth[l];
for (const u of c) {
const h = u.outboundLayer, d = u.inputTensors, p = u.outputTensors, f = new Array();
for (const m of d)
m.id in s && f.push(s[m.id]);
if (f.length === d.length) {
let m = {}, g, x, b, w;
if (u.callArgs != null && (m = u.callArgs), f.length === 1) {
const [y, C] = f[0];
m.mask == null && (m.mask = C), b = Dt(h.call(y, m)), w = Dt(h.computeMask(y, C)), g = [y], x = [C];
} else
g = f.map((y) => y[0]), x = f.map((y) => y[1]), m.mask == null && (m.mask = x), b = Dt(h.call(g, m)), w = Dt(h.computeMask(g, x));
if (h.activityRegularizer)
throw new gt("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");
for (let y = 0; y < p.length; ++y) {
const C = p[y], $ = b[y], k = w[y];
s[C.id] = [$, k];
}
}
}
}
const r = [], i = [], a = [];
for (const l of this.outputs) {
Nn(l.id in s, `Could not compute output ${l.name} : ${l.id}`);
const [c, u] = s[l.id];
a.push(c.shape), r.push(c), i.push(u);
}
return [r, i, a];
}
/**
* Builds a map of internal node keys to node ordering.
* Used in serializaion a node orderings may change as unused nodes are
* dropped. Porting Note: This helper method was pulled out of getConfig to
* improve readability.
* @param layers An array of Layers in the model.
* @returns Map of Node Keys to index order within the layer.
*/
buildNodeConversionMap(t) {
const e = {};
let s;
for (const o of this.layers) {
s = o instanceof pn ? 1 : 0;
for (let r = 0; r < o.inboundNodes.length; r++) {
const i = pn.nodeKey(o, r);
this.containerNodes.has(i) && (e[i] = s, s += 1);
}
}
return e;
}
getLayer(t, e) {
if (e != null)
return this.findLayer(e);
if (t == null)
throw new E("Provide either a layer name or layer index");
if (typeof t == "number")
return this.findLayer(t);
for (const s of this.layers)
if (s.name === t)
return s;
throw new E(`No such layer: ${t}`);
}
findLayer(t) {
if (this.layers.length <= t)
throw new E(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);
return this.layers[t];
}
/**
* Retrieves the Container's current loss values.
*
* Used for regularizers during training.
*/
calculateLosses() {
return _(() => {
const t = [];
for (const e of this.layers)
for (let s = 0; s < e.inboundNodes.length; ++s) {
const o = pn.nodeKey(e, s);
this.containerNodes.has(o) && t.push(...e.calculateLosses());
}
return t;
});
}
getConfig() {
const t = { name: this.name }, e = this.buildNodeConversionMap(this.layers), s = [];
for (const i of this.layers) {
const a = i.getClassName(), l = i.getConfig(), c = [];
for (let h = 0; h < i.inboundNodes.length; h++) {
const d = i.inboundNodes[h], p = pn.nodeKey(i, h);
let f = {};
if (this.containerNodes.has(p)) {
if (d.callArgs)
try {
JSON.stringify(d.callArgs), f = d.callArgs;
} catch {
console.warn(`Layer ${i.name} was passed non-serializable keyword arguments: ${d.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`), f = {};
}
if (d.inboundLayers.length > 0) {
const m = [];
for (let g = 0; g < d.inboundLayers.length; g++) {
const x = d.inboundLayers[g], b = d.nodeIndices[g], w = d.tensorIndices[g], y = pn.nodeKey(x, b);
let C = e[y];
C == null && (C = 0), m.push([x.name, C, w, f]);
}
c.push(m);
}
}
}
const u = {};
u.name = i.name, u.className = a, u.config = l, u.inboundNodes = c, s.push(u);
}
t.layers = s;
const o = [];
for (let i = 0; i < this.inputLayers.length; i++) {
const a = this.inputLayers[i], l = this.inputLayersNodeIndices[i], c = pn.nodeKey(a, l);
if (!this.containerNodes.has(c))
continue;
let u = e[c];
u == null && (u = 0);
const h = this.inputLayersTensorIndices[i];
o.push([a.name, u, h]);
}
t.inputLayers = o;
const r = [];
for (let i = 0; i < this.outputLayers.length; i++) {
const a = this.outputLayers[i], l = this.outputLayersNodeIndices[i], c = pn.nodeKey(a, l);
if (!this.containerNodes.has(c))
continue;
let u = e[c];
u == null && (u = 0);
const h = this.outputLayersTensorIndices[i];
r.push([a.name, u, h]);
}
return t.outputLayers = r, t;
}
/**
* Instantiates a LayersModel from its config (output of `get_config()`).
* @param cls the class to create
* @param config LayersModel config dictionary.
* @param customObjects An optional dictionary of custom objects.
* @param fastWeightInit Optional flag to use fast weight initialization
* during deserialization. This is applicable to cases in which
* the initialization will be immediately overwritten by loaded weight
* values. Default: `false`.
* @returns A LayersModel instance.
* @throws ValueError: In case of improperly formatted config dict.
*/
/** @nocollapse */
static fromConfig(t, e, s = {}, o = !1) {
const r = {}, i = {};
function a(g, x) {
g.name in i ? i[g.name].push(x) : i[g.name] = [x];
}
function l(g, x) {
const b = [];
let w;
for (const y of x) {
const C = y[0], $ = y[1], k = y[2];
if (w = y[3] == null ? {} : y[3], !(C in r)) {
a(g, x);
return;
}
const v = r[C];
if (v.inboundNodes.length <= $) {
a(g, x);
return;
}
const S = v.inboundNodes[$];
b.push(S.outputTensors[k]);
}
b.length > 0 && g.apply(_e(b), w);
}
function c(g) {
const x = g.name, b = Kn(g, e.customObjects != null ? e.customObjects : {});
b.setFastWeightInitDuringBuild(o), r[x] = b, g.inboundNodes.forEach((y) => {
if (!(y instanceof Array))
throw new E(`Corrupted configuration, expected array for nodeData: ${y}`);
a(b, y);
});
}
const u = e.name, h = e.layers;
for (const g of h)
c(g);
for (; !s2(i); )
for (const g of h) {
const x = r[g.name];
if (x.name in i) {
const b = i[x.name];
delete i[x.name];
for (const w of b)
l(x, w);
}
}
const d = [], p = [], f = e.inputLayers;
for (const g of f) {
const x = g[0], b = g[1], w = g[2];
Nn(x in r);
const C = r[x].inboundNodes[b].outputTensors;
d.push(C[w]);
}
const m = e.outputLayers;
for (const g of m) {
const x = g[0], b = g[1], w = g[2];
Nn(x in r);
const C = r[x].inboundNodes[b].outputTensors;
p.push(C[w]);
}
return new t({ inputs: d, outputs: p, name: u });
}
/**
* Determine whether the container is stateful.
*
* Porting Note: this is the equivalent of the stateful @property of
* the Container class in PyKeras.
*/
get stateful() {
if (this._stateful)
throw new E("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");
for (const t of this.layers)
if (t.stateful)
return !0;
return !1;
}
/**
* Reset the state of all stateful constituent layers (if any).
*
* Examples of stateful layers include RNN layers whose `stateful` property
* is set as `true`.
*/
resetStates() {
_(() => {
this.layers.forEach((t) => {
t.stateful && t.resetStates();
});
});
}
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function wT(n, t, e) {
const s = t.length;
if (n == null || Array.isArray(n) && n.length === 0)
return t.map((o) => null);
if (s === 1)
return Array.isArray(n) && n.length === 1 ? n : typeof n == "object" && t[0] in n ? [n[t[0]]] : [n];
if (Array.isArray(n)) {
if (n.length !== s)
throw new Error(`Provided ${e} is an array of ${n.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);
return n;
} else if (typeof n == "object" && Object.keys(n).length > 0 && typeof n[Object.keys(n)[0]] == "object") {
const o = [];
return t.forEach((r) => {
r in n ? o.push(n[r]) : o.push(null);
}), o;
} else
throw new Error(`The model has multiple (${s}) outputs, so ${e} must be either an array with ${s} elements or an object with ${t} keys. Provided ${e} not understood: ${JSON.stringify(n)}`);
}
function Rx(n, t) {
return wT(n, t, "classWeight");
}
async function Dx(n, t, e, s) {
if (t != null || s != null)
throw new Error("Support sampleWeight is not implemented yet");
if (e != null) {
const o = _(() => {
if (n.shape.length === 1)
return Ps(n);
if (n.shape.length === 2) {
if (n.shape[1] > 1)
return dr(n, 1);
if (n.shape[1] === 1)
return A(n, [n.shape[0]]);
throw new Error(`Encountered unexpected last-dimension size (${n.shape[1]}) during handling of class weights. The size is expected to be >= 1.`);
} else
throw new Error(`Unexpected rank of target (y) tensor (${n.rank}) during handling of class weights. The rank is expected to be 1 or 2.`);
}), r = Array.from(await o.data());
$t(o);
const i = [];
return r.forEach((a) => {
if (e[a] == null)
throw new Error(`classWeight must contain all classes in the training data. The class ${a} exists in the data but not in classWeight`);
i.push(e[a]);
}), We(i, "float32");
} else
return null;
}
function CT(n, t) {
return R(n, t);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const $T = 32;
function Ax(n, t) {
let e, s;
const o = t;
e = o.xs, s = o.ys, I(e != null && s != null, () => `A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);
const r = Bp("input", n.inputNames, e), i = Bp("output", n.outputNames, s), a = r[0].shape[0];
I(r.length === n.inputs.length, () => `LayersModel has ${n.inputs.length} inputs, but the dataset provides ${r.length} inputs. (Expected input keys: ${JSON.stringify(n.inputNames)})`), I(i.length === n.outputs.length, () => `LayersModel has ${n.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(n.outputNames)})`);
for (let l = 0; l < r.length; l++)
I(r[l].shape[0] === a, () => `Batch size mismatch: input ${n.inputNames[l]} has ${r[l].shape[0]}; expected ${a} based on input ${n.inputNames[0]}.`);
for (let l = 0; l < i.length; l++)
I(i[l].shape[0] === a, () => `Batch size mismatch: output ${n.outputNames[l]} has ${i[l].shape[0]}; expected ${a} based on input ${n.inputNames[0]}.`);
return { xs: r, ys: i };
}
function Bp(n, t, e) {
if (e instanceof se)
return [e];
if (Array.isArray(e))
return I(e.length === t.length, () => `Received an array of ${e.length} Tensors, but expected ${t.length} to match the ${n} keys ${t}.`), e;
{
const s = [];
for (const o of t) {
if (e[o] == null)
throw new E(`The feature data generated by the dataset lacks the required ${n} key '${o}'.`);
s.push(e[o]);
}
return s;
}
}
function IT(n) {
if (n.length === 3)
throw new gt("Validation with sample weights is not implemented yet.");
return { xs: n[0], ys: n[1] };
}
async function kT(n, t, e) {
const s = e.batchesPerEpoch != null;
if (I(n.optimizer != null, () => "You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."), I(e != null, () => "For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."), I(e.epochs != null && e.epochs > 0 && Number.isInteger(e.epochs), () => `For fitDataset(), config.epochs is expected to be a positive integer, but got ${e.epochs}`), I(!s || e.batchesPerEpoch > 0 && Number.isInteger(e.batchesPerEpoch), () => `For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${e.batchesPerEpoch}`), I(
// tslint:disable-next-line:no-any
e.validationSplit == null,
() => "`validationSplit` is not supported by `fitDataset()`. Use validationData instead."
), n.isTraining)
throw new Error("Cannot start training because another fit() call is ongoing.");
n.isTraining = !0;
try {
const o = e.validationData != null;
let r, i;
if (o)
if (Vp(e.validationData))
I(e.validationBatches == null || e.validationBatches > 0 && Number.isInteger(e.validationBatches), () => `For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${e.validationBatches}`);
else {
const g = IT(e.validationData);
r = g.xs, i = g.ys;
}
const a = n.makeTrainFunction(), l = n.getDedupedMetricsNames();
let c;
o ? c = l.slice().concat(l.map((g) => "val_" + g)) : c = l.slice();
const u = Cx(e.callbacks, e.yieldEvery), h = e.verbose == null ? 1 : e.verbose, { callbackList: d, history: p } = $x(
u,
h,
e.epochs,
null,
null,
vT(t, e),
null,
// Batch size determined by the dataset itself.
o,
c
);
d.setModel(n), n.history = p, await d.onTrainBegin(), n.stopTraining_ = !1;
let f = e.initialEpoch == null ? 0 : e.initialEpoch, m = await t.iterator();
for (; f < e.epochs; ) {
const g = {};
await d.onEpochBegin(f);
let x = 0, b = 0;
for (s || (m = await t.iterator()); !s || x < e.batchesPerEpoch; ) {
const w = await m.next();
if (s && w.done) {
console.warn(`You provided \`batchesPerEpoch\` as ${e.batchesPerEpoch}, but your dataset iterator ran out of data after ${x} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${e.batchesPerEpoch * e.epochs} batches). You may need to use the repeat() function when building your dataset.`);
break;
}
if (w.value != null) {
const { xs: y, ys: C } = Ax(n, w.value), $ = {};
$.batch = b, $.size = y[0].shape[0], await d.onBatchBegin(b, $);
const k = [];
if (e.classWeight != null) {
const T = Rx(e.classWeight, n.outputNames);
for (let F = 0; F < T.length; ++F)
k.push(await Dx(C[F], null, T[F]));
}
const v = y.concat(C).concat(k), S = a(v);
$t(v);
for (let T = 0; T < l.length; ++T) {
const F = l[T], L = S[T];
$[F] = L, Dn(L);
}
await d.onBatchEnd(b, $), wx($), b++, x++;
}
if (s ? x >= e.batchesPerEpoch : w.done) {
if (o) {
let y;
Vp(e.validationData) ? y = Dt(await n.evaluateDataset(e.validationData, { batches: e.validationBatches })) : y = Dt(n.evaluate(r, i, {
batchSize: e.validationBatchSize == null ? $T : e.validationBatchSize,
verbose: 0
}));
for (let C = 0; C < n.metricsNames.length; ++C)
g[`val_${n.metricsNames[C]}`] = y[C];
}
break;
}
if (n.stopTraining_)
break;
}
if (await d.onEpochEnd(f, g), f++, n.stopTraining_)
break;
}
return await d.onTrainEnd(), await n.history.syncData(), n.history;
} finally {
n.isTraining = !1;
}
}
function vT(n, t) {
let e = null;
return t.batchesPerEpoch != null ? e = t.batchesPerEpoch : Number.isFinite(n.size) && (e = n.size), e;
}
function Vp(n) {
return typeof n.iterator == "function";
}
function ST(n) {
return typeof n.next == "function";
}
async function NT(n, t, e) {
e = e || {};
const s = e.batches != null, o = n.testFunction;
let r = [];
if (e.verbose > 0)
throw new gt("Verbose mode is not implemented yet.");
I(!s || e.batches > 0 && Number.isInteger(e.batches), () => `Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(e.batches)}`);
const i = ST(t) ? t : await t.iterator();
let a = 0, l = 0;
for (; !s || l < e.batches; ) {
const c = await i.next();
if (r = _(() => {
if (c.value) {
const { xs: u, ys: h } = Ax(n, c.value), d = u.concat(h), p = _(() => o(d));
if ($t(d), l === 0)
for (let m = 0; m < p.length; ++m)
r.push(Tt(0));
const f = d[0].shape[0];
for (let m = 0; m < p.length; ++m) {
const g = p[m], x = r[m];
r[m] = _(() => Y(r[m], R(f, g))), l > 0 && $t(x);
}
$t(p), a += f, ++l;
}
return r;
}), c.done) {
s && console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${e.batches} batches). You may need to use the repeat() function when building your dataset.`);
break;
}
}
for (let c = 0; c < r.length; ++c) {
const u = r[c];
r[c] = ut(r[c], a), $t(u);
}
return _e(r);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function wc(n) {
I(n > 0 && Number.isInteger(n), () => `batchSize is required to be a positive integer, but got ${n}`);
}
function nr(n, t, e) {
return n == null ? [null] : Array.isArray(n) ? n.map((s) => Bs(s, t, e - t)) : Bs(n, t, e - t);
}
function ru(n, t) {
return _(() => n == null ? null : Array.isArray(n) ? n.map((e) => ru(e, t)) : ix(n, t.dtype === "int32" ? t : st(t, "int32")));
}
function Cc(n, t) {
const e = [];
let s = 0, o = null;
for (; s < n; )
o = s + t, o >= n && (o = n), e.push([s, o]), s = o;
return e;
}
function Fx(n) {
const t = [];
n instanceof se && (n = [n]);
for (let e = 0; e < n.length; ++e) {
const s = n[e];
if (s.rank === 1)
t.push(Ri(s, 1));
else {
if (s.rank === 0)
throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");
t.push(s);
}
}
return t;
}
function dn(n, t) {
if (n == null)
return;
const e = [];
if (t instanceof se)
e.push(t.id);
else if (Array.isArray(t))
t.forEach((o) => e.push(o.id));
else if (t != null)
for (const o in t) {
const r = t[o];
e.push(r.id);
}
const s = [];
if (n instanceof se)
e.indexOf(n.id) === -1 && s.push(n);
else if (Array.isArray(n))
n.forEach((o) => {
e.indexOf(o.id) === -1 && s.push(o);
});
else if (n != null)
for (const o in n) {
const r = n[o];
e.indexOf(r.id) === -1 && s.push(r);
}
s.forEach((o) => {
o.isDisposed || o.dispose();
});
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function TT(n) {
return n instanceof se;
}
function iu(n) {
return Array.isArray(n);
}
function Wp(n) {
return !TT(n) && !iu(n);
}
function Up(n, t, e, s = !0, o = "") {
if (t == null || t.length === 0) {
if (n != null) {
let i = !1;
if (iu(n) && n.length > 0)
i = !0;
else if (Wp(n)) {
for (const a in n)
if (n.hasOwnProperty(a)) {
i = !0;
break;
}
} else
i = !0;
if (i)
throw new E(`Error when checking model ${o} expected no data, but got ${n}`);
}
return [];
}
if (n == null)
return t.map((i) => null);
let r;
if (Wp(n)) {
n = n, r = [];
for (const i of t) {
if (n[i] == null)
throw new E(`No data provided for "${i}". Need data for each key in: ${t}`);
r.push(n[i]);
}
} else if (iu(n)) {
if (n = n, n.length !== t.length)
throw new E(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${n}`);
r = n;
} else {
if (n = n, t.length > 1)
throw new E(`The model ${o} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${n.shape}`);
r = [n];
}
if (r = Fx(r), e != null)
for (let i = 0; i < t.length; ++i) {
if (e[i] == null)
continue;
const a = r[i];
if (a.shape.length !== e[i].length)
throw new E(`Error when checking ${o}: expected ${t[i]} to have ${e[i].length} dimension(s). but got array with shape ${a.shape}`);
for (let l = 0; l < e[i].length; ++l) {
if (l === 0 && !s)
continue;
const c = a.shape[l], u = e[i][l];
if (u != null && u >= 0 && c !== u)
throw new E(`${o} expected a batch of elements where each example has shape [${e[i].slice(1, e[i].length)}] (i.e.,tensor shape [*,${e[i].slice(1, e[i].length)}]) but the ${o} received an input with ${a.shape[0]} examples, each with shape [${a.shape.slice(1, a.shape.length)}] (tensor shape [${a.shape}])`);
}
}
return r;
}
function ET(n, t, e) {
const s = hs(n.map((r) => r.shape[0]));
s.sort();
const o = hs(t.map((r) => r.shape[0]));
if (o.sort(), s.length > 1)
throw new E(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(n.map((r) => r.shape))}`);
if (o.length > 1)
throw new E(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((r) => r.shape))}`);
if (s.length > 0 && o.length > 0 && !Et(s, o))
throw new E(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${o[0]} target sample(s).`);
}
function RT(n, t, e) {
const s = [
ql,
Yl,
br
];
for (let o = 0; o < n.length; ++o) {
const r = n[o], i = t[o], a = e[o];
if (i != null) {
if (i === br && r.shape[r.shape.length - 1] === 1)
throw new E(`You are passing a target array of shape ${r.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);
if (s.indexOf(i) !== -1) {
const l = r.shape.slice(1), c = a.slice(1);
for (let u = 0; u < l.length; ++u) {
const h = l[u], d = c[u];
if (d != null && h !== d)
throw new E(`A target Tensor with shape ${r.shape} was passed for an output of shape ${a}, while using a loss function that expects targets to have the same shape as the output.`);
}
}
}
}
}
function Gp(n, t, e, s = !0, o = "") {
let r;
if (Array.isArray(n)) {
if (n.length !== t.length)
throw new E(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${n.length} Tensors(s).`);
r = n;
} else {
if (t.length > 1)
throw new E(`The model expects ${t.length} ${o} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(n.shape)}.`);
r = [n];
}
if (e != null)
for (let i = 0; i < t.length; ++i) {
if (e[i] == null)
continue;
const a = r[i];
if (a.shape.length !== e[i].length)
throw new E(`Error when checking ${o}: expected ${t[i]} to have ${e[i].length} dimension(s), but got array with shape ${JSON.stringify(a.shape)}`);
for (let l = 0; l < e[i].length; ++l) {
if (l === 0 && !s)
continue;
const c = a.shape[l], u = e[i][l];
if (u != null && u !== c)
throw new E(`Error when checking ${o}: expected ${t[i]} to have shape ${JSON.stringify(e[i])} but got array with shape ${JSON.stringify(a.shape)}.`);
}
}
}
function DT(n, t) {
if (n == null || Array.isArray(n) && n.length === 0)
return t.map((s) => []);
let e;
if (typeof n == "string" || typeof n == "function")
e = [n];
else if (Array.isArray(n) || typeof n == "object")
e = n;
else
throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${n}`);
if (Array.isArray(e))
return t.map((s) => e);
{
const s = [];
for (const o of t) {
let r = e.hasOwnProperty(o) ? e[o] : [];
Array.isArray(r) || (r = [r]), s.push(r);
}
return s;
}
}
const AT = "layers-model";
class Io extends pn {
constructor(t) {
super(t), this.isTraining = !1;
}
/**
* Print a text summary of the model's layers.
*
* The summary includes
* - Name and type of all layers that comprise the model.
* - Output shape(s) of the layers
* - Number of weight parameters of each layer
* - If the model has non-sequential-like topology, the inputs each layer
* receives
* - The total number of trainable and non-trainable parameters of the model.
*
* ```js
* const input1 = tf.input({shape: [10]});
* const input2 = tf.input({shape: [20]});
* const dense1 = tf.layers.dense({units: 4}).apply(input1);
* const dense2 = tf.layers.dense({units: 8}).apply(input2);
* const concat = tf.layers.concatenate().apply([dense1, dense2]);
* const output =
* tf.layers.dense({units: 3, activation: 'softmax'}).apply(concat);
*
* const model = tf.model({inputs: [input1, input2], outputs: output});
* model.summary();
* ```
*
* @param lineLength Custom line length, in number of characters.
* @param positions Custom widths of each of the columns, as either
* fractions of `lineLength` (e.g., `[0.5, 0.75, 1]`) or absolute number
* of characters (e.g., `[30, 50, 65]`). Each number corresponds to
* right-most (i.e., ending) position of a column.
* @param printFn Custom print function. Can be used to replace the default
* `console.log`. For example, you can use `x => {}` to mute the printed
* messages in the console.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
summary(t, e, s = console.log) {
if (!this.built)
throw new E("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");
fT(this, t, e, s);
}
/**
* Configures and prepares the model for training and evaluation. Compiling
* outfits the model with an optimizer, loss, and/or metrics. Calling `fit`
* or `evaluate` on an un-compiled model will throw an error.
*
* @param args a `ModelCompileArgs` specifying the loss, optimizer, and
* metrics to be used for fitting and evaluating this model.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
compile(t) {
if (t.loss == null && (t.loss = []), this.loss = t.loss, typeof t.optimizer == "string")
this.optimizer_ = pT(t.optimizer), this.isOptimizerOwned = !0;
else {
if (!(t.optimizer instanceof vs))
throw new E("User-defined optimizer must be an instance of tf.Optimizer.");
this.optimizer_ = t.optimizer, this.isOptimizerOwned = !1;
}
let e = [];
if (!Array.isArray(t.loss) && typeof t.loss != "string" && typeof t.loss != "function") {
t.loss = t.loss;
for (const i in t.loss)
if (this.outputNames.indexOf(i) === -1)
throw new E(`Unknown entry in loss dictionary: "${i}". Only expected the following keys: ${this.outputNames}`);
for (const i of this.outputNames)
t.loss[i] == null && console.warn(`Output "${i}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${i} during training`), e.push(yc(t.loss[i]));
} else if (Array.isArray(t.loss)) {
if (t.loss.length !== this.outputs.length)
throw new E(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${t.loss}.`);
e = t.loss.map((a) => yc(a));
} else {
const i = yc(t.loss);
this.outputs.forEach((a) => {
e.push(i);
});
}
this.lossFunctions = e, this.feedOutputNames = [], this.feedOutputShapes = [], this.feedLossFns = [];
for (let i = 0; i < this.outputs.length; ++i) {
const a = this.internalOutputShapes[i], l = this.outputNames[i];
this.feedOutputNames.push(l), this.feedOutputShapes.push(a), this.feedLossFns.push(this.lossFunctions[i]);
}
const s = [];
this.metrics = t.metrics, this.metricsNames = ["loss"], this.metricsTensors = [], zs("loss", () => {
for (let i = 0; i < this.outputs.length; ++i) {
if (s.indexOf(i) !== -1)
continue;
const a = this.lossFunctions[i];
this.outputs.length > 1 && (this.metricsTensors.push([a, i]), this.metricsNames.push(this.outputNames[i] + "_loss"));
}
});
const o = DT(t.metrics, this.outputNames), r = (i, a, l) => {
this.outputNames.length > 1 && (a = this.outputNames[i] + "_" + a), this.metricsNames.push(a), this.metricsTensors.push([l, i]);
};
zs("metric", () => {
for (let i = 0; i < this.outputs.length; ++i) {
if (s.indexOf(i) !== -1)
continue;
const a = o[i];
((c) => {
const u = "";
let h, d, p;
for (const f of c) {
if (typeof f == "string" && ["accuracy", "acc", "crossentropy", "ce"].indexOf(f) !== -1) {
const g = this.internalOutputShapes[i];
g[g.length - 1] === 1 || this.lossFunctions[i] === Yl ? ["accuracy", "acc"].indexOf(f) !== -1 ? d = kx : ["crossentropy", "ce"].indexOf(f) !== -1 && (d = sT) : this.lossFunctions[i] === wa ? ["accuracy", "acc"].indexOf(f) !== -1 ? d = oT : ["crossentropy", "ce"].indexOf(f) !== -1 && (d = Nx) : ["accuracy", "acc"].indexOf(f) !== -1 ? d = vx : ["crossentropy", "ce"].indexOf(f) !== -1 && (d = Sx);
let x;
["accuracy", "acc"].indexOf(f) !== -1 ? x = "acc" : ["crossentropy", "ce"].indexOf(f) !== -1 && (x = "ce"), p = d, h = u + x;
} else
p = dT(f), h = u + Xi(f);
let m;
zs(h, () => {
m = p;
}), r(i, h, m);
}
})(a);
}
}), this.collectedTrainableWeights = this.trainableWeights;
}
/**
* Check trainable weights count consistency.
*
* This will raise a warning if `this.trainableWeights` and
* `this.collectedTrainableWeights` are inconsistent (i.e., have different
* numbers of parameters).
* Inconsistency will typically arise when one modifies `model.trainable`
* without calling `model.compile()` again.
*/
checkTrainableWeightsConsistency() {
this.collectedTrainableWeights != null && this.trainableWeights.length !== this.collectedTrainableWeights.length && console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?");
}
/**
* Returns the loss value & metrics values for the model in test mode.
*
* Loss and metrics are specified during `compile()`, which needs to happen
* before calls to `evaluate()`.
*
* Computation is done in batches.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* const result = model.evaluate(
* tf.ones([8, 10]), tf.ones([8, 1]), {batchSize: 4});
* result.print();
* ```
*
* @param x `tf.Tensor` of test data, or an `Array` of `tf.Tensor`s if the
* model has multiple inputs.
* @param y `tf.Tensor` of target data, or an `Array` of `tf.Tensor`s if the
* model has multiple outputs.
* @param args A `ModelEvaluateArgs`, containing optional fields.
*
* @return `Scalar` test loss (if the model has a single output and no
* metrics) or `Array` of `Scalar`s (if the model has multiple outputs
* and/or metrics). The attribute `model.metricsNames`
* will give you the display labels for the scalar outputs.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
evaluate(t, e, s = {}) {
const o = s.batchSize == null ? 32 : s.batchSize;
wc(o);
const r = !0, i = this.standardizeUserDataXY(t, e, r, o);
try {
const a = i[0].concat(i[1]);
this.makeTestFunction();
const l = this.testFunction, c = this.testLoop(l, a, o, s.verbose, s.steps);
return _e(c);
} finally {
dn(i[0], t), dn(i[1], e);
}
}
// TODO(cais): Add code snippet below once real dataset objects are
// available.
/**
* Evaluate model using a dataset object.
*
* Note: Unlike `evaluate()`, this method is asynchronous (`async`).
*
* @param dataset A dataset object. Its `iterator()` method is expected
* to generate a dataset iterator object, the `next()` method of which
* is expected to produce data batches for evaluation. The return value
* of the `next()` call ought to contain a boolean `done` field and a
* `value` field. The `value` field is expected to be an array of two
* `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former
* case is for models with exactly one input and one output (e.g.
* a sequential model). The latter case is for models with multiple
* inputs and/or multiple outputs. Of the two items in the array, the
* first is the input feature(s) and the second is the output target(s).
* @param args A configuration object for the dataset-based evaluation.
* @returns Loss and metric values as an Array of `Scalar` objects.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async evaluateDataset(t, e) {
return this.makeTestFunction(), NT(this, t, e);
}
/**
* Get number of samples provided for training, evaluation or prediction.
*
* @param ins Input `tf.Tensor`.
* @param batchSize Integer batch size, optional.
* @param steps Total number of steps (batches of samples) before
* declaring loop finished. Optional.
* @param stepsName The public API's parameter name for `steps`.
* @returns Number of samples provided.
*/
checkNumSamples(t, e, s, o = "steps") {
let r;
if (s != null) {
if (r = null, e != null)
throw new E(`If ${o} is set, batchSize must be null or undefined.Got batchSize = ${e}`);
} else if (t != null)
Array.isArray(t) ? r = t[0].shape[0] : r = t.shape[0];
else
throw new E(`Either the input data should have a defined shape, or ${o} shoud be specified.`);
return r;
}
/**
* Execute internal tensors of the model with input data feed.
* @param inputs Input data feed. Must match the inputs of the model.
* @param outputs Names of the output tensors to be fetched. Must match
* names of the SymbolicTensors that belong to the graph.
* @returns Fetched values for `outputs`.
*/
execute(t, e) {
if (Array.isArray(e) && e.length === 0)
throw new E("`outputs` is an empty Array, which is not allowed.");
const s = Array.isArray(e), o = s ? e : [e], r = this.retrieveSymbolicTensors(o), i = new as();
if (t instanceof se && (t = [t]), Array.isArray(t)) {
if (t.length !== this.inputs.length)
throw new E(`The number of inputs provided (${t.length}) does not match the number of inputs of this model (${this.inputs.length}).`);
for (let l = 0; l < this.inputs.length; ++l)
i.add(this.inputs[l], t[l]);
} else
for (const l of this.inputs) {
const c = t[l.name];
if (c == null)
throw new E(`No value is provided for the model's input ${l.name}`);
i.add(l, c);
}
const a = ir(r, i);
return s ? a : a[0];
}
/**
* Retrieve the model's internal symbolic tensors from symbolic-tensor names.
*/
retrieveSymbolicTensors(t) {
const e = Js(null, t.length);
let s = t.length;
for (const o of this.layers) {
const r = Array.isArray(o.output) ? o.output : [o.output], i = r.map((a) => a.name);
for (let a = 0; a < t.length; ++a) {
const l = i.indexOf(t[a]);
if (l !== -1 && (e[a] = r[l], s--), s === 0)
break;
}
if (s === 0)
break;
}
if (s > 0) {
const o = [];
throw e.forEach((r, i) => {
r == null && o.push(t[i]);
}), new E(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(o)}`);
}
return e;
}
/**
* Helper method to loop over some data in batches.
*
* Porting Note: Not using the functional approach in the Python equivalent
* due to the imperative backend.
* Porting Note: Does not support step mode currently.
*
* @param ins: input data
* @param batchSize: integer batch size.
* @param verbose: verbosity model
* @returns: Predictions as `tf.Tensor` (if a single output) or an `Array` of
* `tf.Tensor` (if multipe outputs).
*/
predictLoop(t, e = 32, s = !1) {
return _(() => {
const o = this.checkNumSamples(t);
if (s)
throw new gt("Verbose predictLoop() is not implemented yet.");
const r = Cc(o, e), i = this.outputs.map((a) => []);
for (let a = 0; a < r.length; ++a)
_(() => {
const c = r[a][0], u = r[a][1], h = nr(t, c, u), d = [];
if (Array.isArray(h))
for (let f = 0; f < h.length; ++f)
d.push({ key: this.inputs[f], value: h[f] });
else
d.push({ key: this.inputs[0], value: h });
const p = new as(d);
return ir(this.outputs, p);
}).forEach((c, u) => i[u].push(c));
return _e(i.map((a) => Le(a, 0)));
});
}
/**
* Generates output predictions for the input samples.
*
* Computation is done in batches.
*
* Note: the "step" mode of predict() is currently not supported.
* This is because the TensorFlow.js core backend is imperative only.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.predict(tf.ones([8, 10]), {batchSize: 4}).print();
* ```
*
* @param x The input data, as a Tensor, or an `Array` of `tf.Tensor`s if
* the model has multiple inputs.
* @param args A `ModelPredictArgs` object containing optional fields.
*
* @return Prediction results as a `tf.Tensor`(s).
*
* @exception ValueError In case of mismatch between the provided input data
* and the model's expectations, or in case a stateful model receives a
* number of samples that is not a multiple of the batch size.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
predict(t, e = {}) {
const s = Fx(t);
Gp(s, this.inputNames, this.feedInputShapes, !1);
try {
const o = e.batchSize == null ? 32 : e.batchSize;
return wc(o), this.predictLoop(s, o);
} finally {
dn(s, t);
}
}
/**
* Returns predictions for a single batch of samples.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.predictOnBatch(tf.ones([8, 10])).print();
* ```
* @param x: Input samples, as a Tensor (for models with exactly one
* input) or an array of Tensors (for models with more than one input).
* @return Tensor(s) of predictions
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
predictOnBatch(t) {
Gp(t, this.inputNames, this.feedInputShapes, !0);
const e = (Array.isArray(t) ? t[0] : t).shape[0];
return this.predictLoop(t, e);
}
standardizeUserDataXY(t, e, s = !0, o) {
if (this.optimizer_ == null)
throw new sn("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");
const r = [];
for (let i = 0; i < this.feedOutputShapes.length; ++i) {
const a = this.feedOutputShapes[i];
this.feedLossFns[i] === wa ? r.push(a.slice(0, a.length - 1).concat([1])) : r.push(a);
}
if (t = Up(t, this.feedInputNames, this.feedInputShapes, !1, "input"), e = Up(e, this.feedOutputNames, r, !1, "target"), ET(t, e), RT(e, this.feedLossFns, this.feedOutputShapes), this.stateful && o != null && o > 0 && t[0].shape[0] % o !== 0)
throw new E(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${o}. Found: ${t[0].shape[0]} sample(s).`);
return [t, e];
}
async standardizeUserData(t, e, s, o, r = !0, i) {
const [a, l] = this.standardizeUserDataXY(t, e, r, i);
if (s != null)
throw new Error("sample weight is not supported yet.");
let c = null;
if (o != null) {
const u = Rx(o, this.outputNames);
c = [];
for (let h = 0; h < u.length; ++h)
c.push(await Dx(l[h], null, u[h]));
}
return [a, l, c];
}
/**
* Loop over some test data in batches.
* @param f A Function returning a list of tensors.
* @param ins Array of tensors to be fed to `f`.
* @param batchSize Integer batch size or `null` / `undefined`.
* @param verbose verbosity mode.
* @param steps Total number of steps (batches of samples) before
* declaring test finished. Ignored with the default value of `null` /
* `undefined`.
* @returns Array of Scalars.
*/
testLoop(t, e, s, o = 0, r) {
return _(() => {
const i = this.checkNumSamples(e, s, r, "steps"), a = [];
if (o > 0)
throw new gt("Verbose mode is not implemented yet.");
if (r != null)
throw new gt("steps mode in testLoop() is not implemented yet");
{
const l = Cc(i, s), c = We(wn(0, i));
for (let u = 0; u < l.length; ++u) {
const h = l[u][0], d = l[u][1], p = Bs(c, h, d - h), f = ru(e, p), m = t(f);
if (u === 0)
for (let g = 0; g < m.length; ++g)
a.push(Tt(0));
for (let g = 0; g < m.length; ++g) {
const x = m[g];
a[g] = Y(a[g], R(d - h, x));
}
}
for (let u = 0; u < a.length; ++u)
a[u] = ut(a[u], i);
}
return a;
});
}
getDedupedMetricsNames() {
const t = this.metricsNames, e = [];
for (let s = 0; s < t.length; ++s) {
const o = t[s];
let r = o;
if (Tp(t, o) > 1) {
const i = Tp(t.slice(0, s), o);
r += `_${i}`;
}
e.push(r);
}
return e;
}
/**
* Creates a function that performs the following actions:
*
* 1. computes the losses
* 2. sums them to get the total loss
* 3. call the optimizer computes the gradients of the LayersModel's
* trainable weights w.r.t. the total loss and update the variables
* 4. calculates the metrics
* 5. returns the values of the losses and metrics.
*/
makeTrainFunction() {
return (t) => {
const e = [], s = t.slice(0, this.inputs.length), o = t.slice(this.inputs.length, this.inputs.length + this.outputs.length), r = t.slice(this.inputs.length + this.outputs.length, this.inputs.length + this.outputs.length * 2), i = [], a = () => {
const h = [];
for (let m = 0; m < this.inputs.length; ++m)
h.push({ key: this.inputs[m], value: s[m] });
const d = new as(h), p = ir(this.outputs, d, { training: !0 });
let f;
for (let m = 0; m < this.lossFunctions.length; ++m) {
const g = this.lossFunctions[m];
let x = g(o[m], p[m]);
r[m] != null && (x = CT(x, r[m]));
const b = ee(x);
e.push(b), m === 0 ? f = x : f = Y(f, x);
}
for (let m = 0; m < this.metricsTensors.length; ++m) {
let g;
if (this.outputs.length > 1 && m < this.outputs.length)
g = e[m];
else {
const x = this.metricsTensors[m][0], b = this.metricsTensors[m][1];
g = ee(x(o[b], p[b]));
}
Dn(g), i.push(g);
}
return f = ee(f), this.calculateLosses().forEach((m) => {
f = Y(f, m);
}), f;
}, l = this.collectedTrainableWeights.map((h) => h.read()), c = !0;
return [this.optimizer_.minimize(a, c, l)].concat(i);
};
}
/**
* Create a function which, when invoked with an array of `tf.Tensor`s as a
* batch of inputs, returns the prespecified loss and metrics of the model
* under the batch of input data.
*/
makeTestFunction() {
this.testFunction = (t) => _(() => {
const e = [];
let s;
const o = t.slice(0, this.inputs.length), r = t.slice(this.inputs.length, this.inputs.length + this.outputs.length), i = [];
for (let c = 0; c < this.inputs.length; ++c)
i.push({ key: this.inputs[c], value: o[c] });
const a = new as(i), l = ir(this.outputs, a);
for (let c = 0; c < this.lossFunctions.length; ++c) {
const u = this.lossFunctions[c], h = ee(u(r[c], l[c]));
c === 0 ? s = h : s = Y(s, h), e.push(s);
}
for (let c = 0; c < this.metricsTensors.length; ++c) {
const u = this.metricsTensors[c][0], h = this.metricsTensors[c][1], d = ee(u(r[h], l[h]));
e.push(d);
}
return e;
});
}
/**
* Trains the model for a fixed number of epochs (iterations on a
* dataset).
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* for (let i = 1; i < 5 ; ++i) {
* const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
* batchSize: 4,
* epochs: 3
* });
* console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
* }
* ```
*
* @param x `tf.Tensor` of training data, or an array of `tf.Tensor`s if the
* model has multiple inputs. If all inputs in the model are named, you
* can also pass a dictionary mapping input names to `tf.Tensor`s.
* @param y `tf.Tensor` of target (label) data, or an array of `tf.Tensor`s if
* the model has multiple outputs. If all outputs in the model are named,
* you can also pass a dictionary mapping output names to `tf.Tensor`s.
* @param args A `ModelFitArgs`, containing optional fields.
*
* @return A `History` instance. Its `history` attribute contains all
* information collected during training.
*
* @exception ValueError In case of mismatch between the provided input
* data and what the model expects.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async fit(t, e, s = {}) {
if (this.isTraining)
throw new Error("Cannot start training because another fit() call is ongoing.");
this.isTraining = !0;
let o, r, i, a, l, c, u, h, d;
try {
const p = s.batchSize == null ? 32 : s.batchSize;
wc(p);
const f = !1, m = await this.standardizeUserData(t, e, s.sampleWeight, s.classWeight, f, p);
o = m[0], r = m[1], d = m[2];
let g = !1, x;
if (s.validationData != null && s.validationData.length > 0) {
if (g = !0, s.validationData.length === 2)
l = s.validationData[0], c = s.validationData[1];
else
throw s.validationData.length === 3 ? new gt("validationData including sample weights is not supported yet.") : new E(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);
const S = !0, T = await this.standardizeUserData(
l,
c,
null,
/** Unused sample weights. */
null,
/** Unused class weights. */
S,
p
);
u = T[0], h = T[1], x = u.concat(h);
} else if (s.validationSplit != null && s.validationSplit > 0 && s.validationSplit < 1) {
g = !0;
const S = Math.floor(o[0].shape[0] * (1 - s.validationSplit)), T = o[0].shape[0];
u = nr(o, S, T), i = o, o = nr(o, 0, S), h = nr(r, S, T), a = r, r = nr(r, 0, S), x = u.concat(h);
} else
s.validationSteps != null && (g = !0);
const b = o.concat(r).concat(d);
this.checkTrainableWeightsConsistency();
const w = this.makeTrainFunction(), y = this.getDedupedMetricsNames();
let C, $;
g ? (this.makeTestFunction(), C = this.testFunction, $ = y.slice().concat(y.map((S) => "val_" + S))) : (C = null, x = [], $ = y.slice());
const k = Cx(s.callbacks, s.yieldEvery);
return await this.fitLoop(w, b, y, p, s.epochs, s.verbose, k, C, x, s.shuffle, $, s.initialEpoch, null, null);
} finally {
this.isTraining = !1, dn(o, t), dn(r, e), dn(i, t), dn(a, e), dn(u, l), dn(h, c), d != null && $t(d);
}
}
/**
* Abstract fit function for `f(ins)`.
* @param f A Function returning a list of tensors. For training, this
* function is expected to perform the updates to the variables.
* @param ins List of tensors to be fed to `f`.
* @param outLabels List of strings, display names of the outputs of `f`.
* @param batchSize Integer batch size or `== null` if unknown. Default : 32.
* @param epochs Number of times to iterate over the data. Default : 1.
* @param verbose Verbosity mode: 0, 1, or 2. Default: 1.
* @param callbacks List of callbacks to be called during training.
* @param valF Function to call for validation.
* @param valIns List of tensors to be fed to `valF`.
* @param shuffle Whether to shuffle the data at the beginning of every
* epoch. Default : true.
* @param callbackMetrics List of strings, the display names of the metrics
* passed to the callbacks. They should be the concatenation of the
* display names of the outputs of `f` and the list of display names
* of the outputs of `valF`.
* @param initialEpoch Epoch at which to start training (useful for
* resuming a previous training run). Default : 0.
* @param stepsPerEpoch Total number of steps (batches on samples) before
* declaring one epoch finished and starting the next epoch. Ignored with
* the default value of `undefined` or `null`.
* @param validationSteps Number of steps to run validation for (only if
* doing validation from data tensors). Not applicable for tfjs-layers.
* @returns A `History` object.
*/
async fitLoop(t, e, s, o, r, i, a, l, c, u, h, d, p, f) {
o == null && (o = 32), r == null && (r = 1), u == null && (u = !0), d == null && (d = 0);
let m = !1;
if (l != null && c != null && (m = !0), f != null && (m = !0, p == null))
throw new E("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");
const g = this.checkNumSamples(e, o, p, "steps_per_epoch");
let x;
g != null && (x = wn(0, g)), i == null && (i = 1);
const { callbackList: b, history: w } = $x(a, i, r, d, g, p, o, m, h);
b.setModel(this), this.history = w, await b.onTrainBegin(), this.stopTraining_ = !1;
for (let y = d; y < r; ++y) {
await b.onEpochBegin(y);
const C = {};
if (p != null)
throw new gt("stepsPerEpoch mode is not implemented yet.");
{
if (u === "batch")
throw new gt("batch shuffling is not implemneted yet");
u && _1(x);
const $ = We(x), k = Cc(g, o);
for (let v = 0; v < k.length; ++v) {
const S = {};
if (await b.onBatchBegin(v, S), _(() => {
const T = k[v][0], F = k[v][1], L = Bs($, T, F - T);
S.batch = v, S.size = F - T;
const M = ru(e, L), B = t(M);
for (let z = 0; z < s.length; ++z) {
const V = s[z], H = B[z];
S[V] = H, Dn(H);
}
if (v === k.length - 1 && m) {
const z = this.testLoop(l, c, o);
for (let V = 0; V < s.length; ++V) {
const H = s[V], U = z[V];
Dn(U), C["val_" + H] = U;
}
}
}), await b.onBatchEnd(v, S), wx(S), this.stopTraining_)
break;
}
$.dispose();
}
if (await b.onEpochEnd(y, C), this.stopTraining_)
break;
}
return await b.onTrainEnd(), await this.history.syncData(), this.history;
}
// TODO(cais): Add code snippet below when it's possible to instantiate
// actual dataset objects.
/**
* Trains the model using a dataset object.
*
* @param dataset A dataset object. Its `iterator()` method is expected
* to generate a dataset iterator object, the `next()` method of which
* is expected to produce data batches for training. The return value
* of the `next()` call ought to contain a boolean `done` field and a
* `value` field. The `value` field is expected to be an array of two
* `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former
* case is for models with exactly one input and one output (e.g.
* a sequential model). The latter case is for models with multiple
* inputs and/or multiple outputs.
* Of the two items in the array, the first is the input feature(s) and
* the second is the output target(s).
* @param args A `ModelFitDatasetArgs`, containing optional fields.
*
* @return A `History` instance. Its `history` attribute contains all
* information collected during training.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async fitDataset(t, e) {
return kT(this, t, e);
}
/**
* Runs a single gradient update on a single batch of data.
*
* This method differs from `fit()` and `fitDataset()` in the following
* regards:
* - It operates on exactly one batch of data.
* - It returns only the loss and metric values, instead of
* returning the batch-by-batch loss and metric values.
* - It doesn't support fine-grained options such as verbosity and
* callbacks.
*
* @param x Input data. It could be one of the following:
* - A `tf.Tensor`, or an Array of `tf.Tensor`s (in case the model has
* multiple inputs).
* - An Object mapping input names to corresponding `tf.Tensor` (if the
* model has named inputs).
* @param y Target data. It could be either a `tf.Tensor` or multiple
* `tf.Tensor`s. It should be consistent with `x`.
* @returns Training loss or losses (in case the model has
* multiple outputs), along with metrics (if any), as numbers.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async trainOnBatch(t, e) {
const s = await this.standardizeUserData(t, e), o = s[0], r = s[1], a = this.makeTrainFunction()(o.concat(r)), l = [];
for (const c of a) {
const u = await c.data();
l.push(u[0]);
}
return $t(a), dn(s[0], t), dn(s[1], e), _e(l);
}
/**
* Extract weight values of the model.
*
* @param config: An instance of `io.SaveConfig`, which specifies
* model-saving options such as whether only trainable weights are to be
* saved.
* @returns A `NamedTensorMap` mapping original weight names (i.e.,
* non-uniqueified weight names) to their values.
*/
getNamedWeights(t) {
const e = [], s = t != null && t.trainableOnly, o = s ? this.trainableWeights : this.weights, r = this.getWeights(s);
for (let i = 0; i < o.length; ++i)
s && !o[i].trainable || e.push({ name: o[i].originalName, tensor: r[i] });
return e;
}
/**
* Setter used for force stopping of LayersModel.fit() (i.e., training).
*
* Example:
*
* ```js
* const input = tf.input({shape: [10]});
* const output = tf.layers.dense({units: 1}).apply(input);
* const model = tf.model({inputs: [input], outputs: [output]});
* model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
* const xs = tf.ones([8, 10]);
* const ys = tf.zeros([8, 1]);
*
* const history = await model.fit(xs, ys, {
* epochs: 10,
* callbacks: {
* onEpochEnd: async (epoch, logs) => {
* if (epoch === 2) {
* model.stopTraining = true;
* }
* }
* }
* });
*
* // There should be only 3 values in the loss array, instead of 10
* values,
* // due to the stopping after 3 epochs.
* console.log(history.history.loss);
* ```
*/
set stopTraining(t) {
this.stopTraining_ = t;
}
get stopTraining() {
return this.stopTraining_;
}
get optimizer() {
return this.optimizer_;
}
set optimizer(t) {
this.optimizer_ !== t && (this.optimizer_ = t, this.isOptimizerOwned = !1);
}
dispose() {
const t = super.dispose();
if (t.refCountAfterDispose === 0 && this.optimizer != null && this.isOptimizerOwned) {
const e = Vc().numTensors;
this.optimizer_.dispose(), t.numDisposedVariables += e - Vc().numTensors;
}
return t;
}
getLossIdentifiers() {
let t;
if (typeof this.loss == "string")
t = Un(this.loss);
else if (Array.isArray(this.loss)) {
for (const e of this.loss)
if (typeof e != "string")
throw new Error("Serialization of non-string loss is not supported.");
t = this.loss.map((e) => Un(e));
} else {
const e = Object.keys(this.loss);
t = {};
const s = this.loss;
for (const o of e)
if (typeof s[o] == "string")
t[o] = Un(s[o]);
else
throw new Error("Serialization of non-string loss is not supported.");
}
return t;
}
getMetricIdentifiers() {
if (typeof this.metrics == "string" || typeof this.metrics == "function")
return [Un(Xi(this.metrics))];
if (Array.isArray(this.metrics))
return this.metrics.map((t) => Un(Xi(t)));
{
const t = {};
for (const e in this.metrics)
t[e] = Un(Xi(this.metrics[e]));
return t;
}
}
getTrainingConfig() {
return {
loss: this.getLossIdentifiers(),
metrics: this.getMetricIdentifiers(),
optimizer_config: {
class_name: this.optimizer.getClassName(),
config: this.optimizer.getConfig()
}
};
}
loadTrainingConfig(t) {
if (t.weighted_metrics != null)
throw new Error("Loading weight_metrics is not supported yet.");
if (t.loss_weights != null)
throw new Error("Loading loss_weights is not supported yet.");
if (t.sample_weight_mode != null)
throw new Error("Loading sample_weight_mode is not supported yet.");
const e = su(t.optimizer_config), s = Kn(e);
let o;
if (typeof t.loss == "string")
o = Os(t.loss);
else if (Array.isArray(t.loss))
o = t.loss.map((i) => Os(i));
else if (t.loss != null) {
o = {};
for (const i in t.loss)
o[i] = Os(t.loss[i]);
}
let r;
if (Array.isArray(t.metrics))
r = t.metrics.map((i) => Os(i));
else if (t.metrics != null) {
r = {};
for (const i in t.metrics)
r[i] = Os(t.metrics[i]);
}
this.compile({ loss: o, metrics: r, optimizer: s });
}
/**
* Save the configuration and/or weights of the LayersModel.
*
* An `IOHandler` is an object that has a `save` method of the proper
* signature defined. The `save` method manages the storing or
* transmission of serialized data ("artifacts") that represent the
* model's topology and weights onto or via a specific medium, such as
* file downloads, local storage, IndexedDB in the web browser and HTTP
* requests to a server. TensorFlow.js provides `IOHandler`
* implementations for a number of frequently used saving mediums, such as
* `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`
* for more details.
*
* This method also allows you to refer to certain types of `IOHandler`s
* as URL-like string shortcuts, such as 'localstorage://' and
* 'indexeddb://'.
*
* Example 1: Save `model`'s topology and weights to browser [local
* storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
* then load it back.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* console.log('Prediction from original model:');
* model.predict(tf.ones([1, 3])).print();
*
* const saveResults = await model.save('localstorage://my-model-1');
*
* const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');
* console.log('Prediction from loaded model:');
* loadedModel.predict(tf.ones([1, 3])).print();
* ```
*
* Example 2. Saving `model`'s topology and weights to browser
* [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API);
* then load it back.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* console.log('Prediction from original model:');
* model.predict(tf.ones([1, 3])).print();
*
* const saveResults = await model.save('indexeddb://my-model-1');
*
* const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');
* console.log('Prediction from loaded model:');
* loadedModel.predict(tf.ones([1, 3])).print();
* ```
*
* Example 3. Saving `model`'s topology and weights as two files
* (`my-model-1.json` and `my-model-1.weights.bin`) downloaded from
* browser.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* const saveResults = await model.save('downloads://my-model-1');
* ```
*
* Example 4. Send `model`'s topology and weights to an HTTP server.
* See the documentation of `tf.io.http` for more details
* including specifying request parameters and implementation of the
* server.
*
* ```js
* const model = tf.sequential(
* {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
* const saveResults = await model.save('http://my-server/model/upload');
* ```
*
* @param handlerOrURL An instance of `IOHandler` or a URL-like,
* scheme-based string shortcut for `IOHandler`.
* @param config Options for saving the model.
* @returns A `Promise` of `SaveResult`, which summarizes the result of
* the saving, such as byte sizes of the saved artifacts for the model's
* topology and weight values.
*
* @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
*/
async save(t, e) {
if (typeof t == "string") {
const c = Tw(t);
if (c.length === 0)
throw new E(`Cannot find any save handlers for URL '${t}'`);
if (c.length > 1)
throw new E(`Found more than one (${c.length}) save handlers for URL '${t}'`);
t = c[0];
}
if (t.save == null)
throw new E("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");
const s = await dp(this.getNamedWeights(e)), o = !1, r = null, a = {
modelTopology: this.toJSON(r, o),
format: AT,
generatedBy: `TensorFlow.js tfjs-layers v${Ex}`,
convertedBy: null
};
if ((e == null ? !1 : e.includeOptimizer) && this.optimizer != null) {
a.trainingConfig = this.getTrainingConfig();
const c = "optimizer", { data: u, specs: h } = await dp(await this.optimizer.getWeights(), c);
s.specs.push(...h), s.data = Nw([s.data, u]);
}
return this.userDefinedMetadata != null && (zp(this.userDefinedMetadata, this.name, !0), a.userDefinedMetadata = this.userDefinedMetadata), a.weightData = s.data, a.weightSpecs = s.specs, t.save(a);
}
/**
* Set user-defined metadata.
*
* The set metadata will be serialized together with the topology
* and weights of the model during `save()` calls.
*
* @param setUserDefinedMetadata
*/
setUserDefinedMetadata(t) {
zp(t, this.name), this.userDefinedMetadata = t;
}
/**
* Get user-defined metadata.
*
* The metadata is supplied via one of the two routes:
* 1. By calling `setUserDefinedMetadata()`.
* 2. Loaded during model loading (if the model is constructed
* via `tf.loadLayersModel()`.)
*
* If no user-defined metadata is available from either of the
* two routes, this function will return `undefined`.
*/
getUserDefinedMetadata() {
return this.userDefinedMetadata;
}
}
Io.className = "Model";
j(Io);
class Ox extends Io {
}
Ox.className = "Functional";
j(Ox);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class yr extends Io {
constructor(t) {
if (super({ inputs: [], outputs: [] }), t = t || {}, this.trainable = !0, this.built = !1, this.name = t.name != null ? t.name : Kl("sequential_"), t.layers != null)
for (const e of t.layers)
this.add(e);
}
// Helper function to Sequential.add Throws if the new output shape will be
// invalid.
checkShape(t) {
if (t.inboundNodes[0].outputTensors[0].shape.some((s) => s < 0))
throw new E(`Negative dimension size caused by adding layer ${t.name} with input shape [${t.inboundNodes[0].inputTensors[0].shape}]`);
}
/**
* Adds a layer instance on top of the layer stack.
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.dense({units: 8, inputShape: [1]}));
* model.add(tf.layers.dense({units: 4, activation: 'relu6'}));
* model.add(tf.layers.dense({units: 1, activation: 'relu6'}));
* // Note that the untrained model is random at this point.
* model.predict(tf.randomNormal([10, 1])).print();
* ```
* @param layer Layer instance.
*
* @exception ValueError In case the `layer` argument does not know its
* input shape.
* @exception ValueError In case the `layer` argument has multiple output
* tensors, or is already connected somewhere else (forbidden in
* `Sequential` models).
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
add(t) {
const e = t instanceof yr || t instanceof Io;
let s;
if (e) {
if (s = t, s.outputs.length !== 1)
throw new E("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
if (s.inputs.length !== 1)
throw new E("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.");
}
if (this.outputs.length === 0) {
if (t.inboundNodes.length === 0) {
if (t.batchInputShape == null)
throw new E("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");
const o = O2({
batchShape: t.batchInputShape,
dtype: t.dtype,
name: t.name + "_input"
});
t.apply(o);
}
if (e)
this.outputs = s.outputs, this.inputs = s.inputs;
else {
if (t.inboundNodes.length !== 1)
throw new E(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${t.name} which has ${t.inboundNodes.length} pre-existing inbound connections.`);
if (t.inboundNodes[0].outputTensors.length !== 1)
throw new E("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
this.checkShape(t), this.outputs = [t.inboundNodes[0].outputTensors[0]], this.inputs = mx(this.outputs[0]);
}
this.inboundNodes = [], new Xl({
outboundLayer: this,
inboundLayers: [],
nodeIndices: [],
tensorIndices: [],
inputTensors: this.inputs,
outputTensors: this.outputs,
// no model-level masking for now
inputMasks: Js(null, this.inputs.length),
outputMasks: [null],
inputShapes: this.inputs.map((o) => o.shape),
outputShapes: this.outputs[0].shape
});
} else {
const o = t.apply(this.outputs[0]);
if (Array.isArray(o))
throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
this.checkShape(t), this.outputs = [o], this.inboundNodes[0].outputTensors = this.outputs, this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
}
this.layers.push(t), this.built = !1;
}
/**
* Removes the last layer in the model.
*
* @exception TypeError if there are no layers in the model.
*/
pop() {
if (this.layers.length === 0)
throw new TypeError("There are no layers in the model.");
if (this.layers.pop(), this.layers.length === 0)
this.outputs = [], this.inboundNodes = [], this.outboundNodes = [];
else {
const t = this.layers.length - 1;
this.layers[t].outboundNodes = [], this.outputs = [this.layers[t].output], this.inboundNodes[0].outputTensors = this.outputs, this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
}
}
call(t, e) {
return this.model == null && this.build(), this.model.call(t, e);
}
build(t) {
if (St(t), this.inputs.length === 0 || this.outputs.length === 0)
throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");
this.model = new Io({
inputs: this.inputs,
outputs: this.outputs[0],
name: this.name + "_model"
}), this.model.trainable = this.trainable, this.supportsMasking = this.model.supportsMasking, this.inputLayers = this.model.inputLayers, this.inputLayersNodeIndices = this.model.inputLayersNodeIndices, this.inputLayersTensorIndices = this.model.inputLayersTensorIndices, this.outputLayers = this.model.outputLayers, this.outputLayersNodeIndices = this.model.outputLayersNodeIndices, this.outputLayersTensorIndices = this.model.outputLayersTensorIndices, this.nodesByDepth = this.model.nodesByDepth, this.containerNodes = this.model.containerNodes, this.outputNames = this.model.outputNames, this.inputNames = this.model.inputNames, this.built = !0;
}
countParams() {
return this.built || this.build(), super.countParams();
}
/**
* Print a text summary of the Sequential model's layers.
*
* The summary includes
* - Name and type of all layers that comprise the model.
* - Output shape(s) of the layers
* - Number of weight parameters of each layer
* - The total number of trainable and non-trainable parameters of the
* model.
*
* ```js
* const model = tf.sequential();
* model.add(
* tf.layers.dense({units: 100, inputShape: [10], activation: 'relu'}));
* model.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));
*
* model.summary();
* ```
*
* @param lineLength Custom line length, in number of characters.
* @param positions Custom widths of each of the columns, as either
* fractions of `lineLength` (e.g., `[0.5, 0.75, 1]`) or absolute number
* of characters (e.g., `[30, 50, 65]`). Each number corresponds to
* right-most (i.e., ending) position of a column.
* @param printFn Custom print function. Can be used to replace the default
* `console.log`. For example, you can use `x => {}` to mute the printed
* messages in the console.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
summary(t, e, s = console.log) {
this.built || this.build(), super.summary(t, e, s);
}
/**
* Sets the weights of the model.
*
* @param weights Should be a list of Tensors with shapes and types matching
* the output of `model.getWeights()`.
*/
setWeights(t) {
this.model == null && this.build(), this.model.setWeights(t);
}
/**
* Returns the loss value & metrics values for the model in test mode.
*
* Loss and metrics are specified during `compile()`, which needs to happen
* before calls to `evaluate()`.
*
* Computation is done in batches.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* const result = model.evaluate(tf.ones([8, 10]), tf.ones([8, 1]), {
* batchSize: 4,
* });
* result.print();
* ```
*
* @param x `tf.Tensor` of test data, or an `Array` of `tf.Tensor`s if the
* model has multiple inputs.
* @param y `tf.Tensor` of target data, or an `Array` of `tf.Tensor`s if the
* model has multiple outputs.
* @param args A `ModelEvaluateConfig`, containing optional fields.
*
* @return `Scalar` test loss (if the model has a single output and no
* metrics) or `Array` of `Scalar`s (if the model has multiple outputs
* and/or metrics). The attribute `model.metricsNames`
* will give you the display labels for the scalar outputs.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
evaluate(t, e, s = {}) {
if (!this.built)
throw new sn("The model needs to be compiled before being used.");
return this.model.evaluate(t, e, s);
}
// TODO(cais): Add code snippet below once real dataset objects are
// available.
/**
* Evaluate model using a dataset object.
*
* Note: Unlike `evaluate()`, this method is asynchronous (`async`).
*
* @param dataset A dataset object. Its `iterator()` method is expected
* to generate a dataset iterator object, the `next()` method of which
* is expected to produce data batches for evaluation. The return value
* of the `next()` call ought to contain a boolean `done` field and a
* `value` field. The `value` field is expected to be an array of two
* `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former
* case is for models with exactly one input and one output (e.g.
* a sequential model). The latter case is for models with multiple
* inputs and/or multiple outputs. Of the two items in the array, the
* first is the input feature(s) and the second is the output target(s).
* @param args A configuration object for the dataset-based evaluation.
* @returns Loss and metric values as an Array of `Scalar` objects.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async evaluateDataset(t, e) {
if (!this.built)
throw new sn("The model needs to be compiled before being used.");
return this.model.evaluateDataset(t, e);
}
/**
* Generates output predictions for the input samples.
*
* Computation is done in batches.
*
* Note: the "step" mode of predict() is currently not supported.
* This is because the TensorFlow.js core backend is imperative only.
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.predict(tf.ones([2, 10])).print();
* ```
*
* @param x The input data, as a Tensor, or an `Array` of `tf.Tensor`s if
* the model has multiple inputs.
* @param conifg A `ModelPredictConfig` object containing optional fields.
*
* @return `tf.Tensor`(s) of predictions.
*
* @exception ValueError In case of mismatch between the provided input data
* and the model's expectations, or in case a stateful model receives a
* number of samples that is not a multiple of the batch size.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
predict(t, e = {}) {
return this.model == null && this.build(), this.model.predict(t, e);
}
/**
* Returns predictions for a single batch of samples.
*
* @param x: Input samples, as a Tensor, or list of Tensors (if the model
* has multiple inputs).
* @return Tensor(s) of predictions
*/
predictOnBatch(t) {
return this.model == null && this.build(), this.model.predictOnBatch(t);
}
/**
* See `LayersModel.compile`.
*
* @param args
*/
compile(t) {
this.build(), this.model.compile(t), this.optimizer_ = this.model.optimizer, this.isOptimizerOwned = this.model.isOptimizerOwned, this.loss = this.model.loss, this.metrics = this.model.metrics, this.metricsTensors = this.model.metricsTensors, this.metricsNames = this.model.metricsNames;
}
get optimizer() {
return this.model == null ? void 0 : this.model.optimizer;
}
set optimizer(t) {
this.model.optimizer = t;
}
/**
* Trains the model for a fixed number of epochs (iterations on a dataset).
*
* ```js
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [10]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* const history = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
* batchSize: 4,
* epochs: 3
* });
* console.log(history.history.loss[0]);
* ```
*
* @param x `tf.Tensor` of training data, or an array of `tf.Tensor`s if the
* model has multiple inputs. If all inputs in the model are named, you can
* also pass a dictionary mapping input names to `tf.Tensor`s.
* @param y `tf.Tensor` of target (label) data, or an array of `tf.Tensor`s if
* the model has multiple outputs. If all outputs in the model are named, you
* can also pass a dictionary mapping output names to `tf.Tensor`s.
* @param args A `ModelFitConfig`, containing optional fields.
*
* @return A `History` instance. Its `history` attribute contains all
* information collected during training.
*
* @exception ValueError In case of mismatch between the provided input data
* and what the model expects.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async fit(t, e, s = {}) {
if (!this.built)
throw new sn("The model needs to be compiled before being used.");
return this.model.fit(t, e, s);
}
/**
* Trains the model using a dataset object.
*
* ```js
* const xArray = [
* [1, 1, 1, 1, 1, 1, 1, 1, 1],
* [1, 1, 1, 1, 1, 1, 1, 1, 1],
* [1, 1, 1, 1, 1, 1, 1, 1, 1],
* [1, 1, 1, 1, 1, 1, 1, 1, 1],
* ];
* const yArray = [1, 1, 1, 1];
* // Create a dataset from the JavaScript array.
* const xDataset = tf.data.array(xArray);
* const yDataset = tf.data.array(yArray);
* // Zip combines the `x` and `y` Datasets into a single Dataset, the
* // iterator of which will return an object containing of two tensors,
* // corresponding to `x` and `y`. The call to `batch(4)` will bundle
* // four such samples into a single object, with the same keys now pointing
* // to tensors that hold 4 examples, organized along the batch dimension.
* // The call to `shuffle(4)` causes each iteration through the dataset to
* // happen in a different order. The size of the shuffle window is 4.
* const xyDataset = tf.data.zip({xs: xDataset, ys: yDataset})
* .batch(4)
* .shuffle(4);
* const model = tf.sequential({
* layers: [tf.layers.dense({units: 1, inputShape: [9]})]
* });
* model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
* const history = await model.fitDataset(xyDataset, {
* epochs: 4,
* callbacks: {onEpochEnd: (epoch, logs) => console.log(logs.loss)}
* });
* ```
*
* @param dataset A dataset object. Its `iterator()` method is expected to
* generate a dataset iterator object, the `next()` method of which is
* expected to produce data batches for evaluation. The return value of the
* `next()` call ought to contain a boolean `done` field and a `value`
* field.
*
* The `value` field is expected to be an object of with fields
* `xs` and `ys`, which point to the feature tensor and the target tensor,
* respectively. This case is for models with exactly one input and one
* output (e.g. a sequential model). For example:
* ```js
* {value: {xs: xsTensor, ys: ysTensor}, done: false}
* ```
*
* If the model has multiple inputs, the `xs` field of `value` should
* be an object mapping input names to their respective feature tensors.
* For example:
* ```js
* {
* value: {
* xs: {
* input_1: xsTensor1,
* input_2: xsTensor2
* },
* ys: ysTensor
* },
* done: false
* }
* ```
* If the model has multiple outputs, the `ys` field of `value` should
* be an object mapping output names to their respective target tensors.
* For example:
* ```js
* {
* value: {
* xs: xsTensor,
* ys: {
* output_1: ysTensor1,
* output_2: ysTensor2
* },
* },
* done: false
* }
* ```
* @param args A `ModelFitDatasetArgs`, containing optional fields.
*
* @return A `History` instance. Its `history` attribute contains all
* information collected during training.
*
* @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
*/
async fitDataset(t, e) {
if (!this.built)
throw new sn("The model needs to be compiled before being used.");
return this.model.fitDataset(t, e);
}
/**
* Runs a single gradient update on a single batch of data.
*
* This method differs from `fit()` and `fitDataset()` in the following
* regards:
* - It operates on exactly one batch of data.
* - It returns only the loss and metric values, instead of
* returning the batch-by-batch loss and metric values.
* - It doesn't support fine-grained options such as verbosity and
* callbacks.
*
* @param x Input data. It could be one of the following:
* - A `tf.Tensor`, or an Array of `tf.Tensor`s (in case the model has
* multiple inputs).
* - An Object mapping input names to corresponding `tf.Tensor` (if the
* model has named inputs).
* @param y Target data. It could be either a `tf.Tensor` or multiple
* `tf.Tensor`s. It should be consistent with `x`.
* @returns Training loss or losses (in case the model has
* multiple outputs), along with metrics (if any), as numbers.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async trainOnBatch(t, e) {
return this.model.trainOnBatch(t, e);
}
/* See parent class for JsDoc */
/** @nocollapse */
static fromConfig(t, e, s = {}, o = !1) {
let r, i = {};
if (e instanceof Array) {
if (e[0].className == null || e[0].className === "Merge")
throw new E("Legacy serialization format not supported yet.");
r = e;
} else
I(e.layers != null, () => "When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."), r = e.layers, delete e.layers, i = e;
const a = new t(i);
if (!(a instanceof yr))
throw new gt(`Sequential.fromConfig called on non-Sequential input: ${a}`);
for (const l of r) {
const u = Kn(l, void 0, o);
o && u.setFastWeightInitDuringBuild(!0), a.add(u);
}
return a;
}
/**
* Setter used for force stopping of LayersModel.fit() (i.e., training).
*
* Example:
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.dense({units: 1, inputShape: [10]}));
* model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
* const xs = tf.ones([8, 10]);
* const ys = tf.zeros([8, 1]);
*
* const history = await model.fit(xs, ys, {
* epochs: 10,
* callbacks: {
* onEpochEnd: async (epoch, logs) => {
* if (epoch === 2) {
* model.stopTraining = true;
* }
* }
* }
* });
*
* // There should be only 3 values in the loss array, instead of 10 values,
* // due to the stopping after 3 epochs.
* console.log(history.history.loss);
* ```
*/
set stopTraining(t) {
if (this.model == null)
throw new E("Cannot set the stopTraining property of a sequential model before it is compiled.");
this.model.stopTraining = t;
}
get stopTraining() {
if (this.model == null)
throw new E("Cannot get the stopTraining property of a sequential model before it is compiled.");
return this.model.stopTraining;
}
// TODO(cais): Override get trainableWeights() here
// tslint:disable-next-line:no-any
getConfig() {
const t = [];
for (const e of this.layers) {
const s = {};
s.className = e.getClassName(), s.config = e.getConfig(), t.push(s);
}
return { name: this.name, layers: t };
}
}
yr.className = "Sequential";
j(yr);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
let ke = class extends Uo {
getConfig() {
return {};
}
};
class _x extends ke {
/**
* Calculate the activation function.
*
* @param x: Input.
* @param alpha: Scaling factor the negative section.
* @return Output of the ELU activation.
*/
apply(t, e = 1) {
return b2(t, e);
}
}
_x.className = "elu";
j(_x);
class Lx extends ke {
apply(t) {
return Qm(t);
}
}
Lx.className = "selu";
j(Lx);
class Mx extends ke {
apply(t) {
return ro(t);
}
}
Mx.className = "relu";
j(Mx);
class Px extends ke {
apply(t) {
return _(() => mr(6, ro(t)));
}
}
Px.className = "relu6";
j(Px);
class zx extends ke {
apply(t) {
return t;
}
}
zx.className = "linear";
j(zx);
class Bx extends ke {
apply(t) {
return Bo(t);
}
}
Bx.className = "sigmoid";
j(Bx);
class Vx extends ke {
apply(t) {
return w2(t);
}
}
Vx.className = "hardSigmoid";
j(Vx);
class Wx extends ke {
apply(t) {
return $i(t);
}
}
Wx.className = "softplus";
j(Wx);
class Ux extends ke {
apply(t) {
return y2(t);
}
}
Ux.className = "softsign";
j(Ux);
class Gx extends ke {
apply(t) {
return Ll(t);
}
}
Gx.className = "tanh";
j(Gx);
let Rd = class extends ke {
/**
* Calculate the activation function.
*
* @param x Tensor.
* @param axis Integer, axis along which the softmax normalization is applied.
* Invalid if < 2, as softmax across 1 (the batch dimension) is assumed to be
* an error.
*
* @returns a Tensor of the same shape as x
*
* @throws ValueError: In case `dim(x) < 2`.
*/
apply(t, e = -1) {
return Fh(t, e);
}
};
Rd.className = "softmax";
j(Rd);
class Hx extends ke {
/**
* Calculate the activation function of log softmax:
* log( exp(x_i) / sum(exp(x)) )
*
* @param x Tensor.
* @param axis Integer, axis along which the softmax normalization is applied.
* Invalid if < 2, as softmax across 1 (the batch dimension) is assumed to be
* an error.
*
* @returns a Tensor of the same shape as x
*
* @throws ValueError: In case `dim(x) < 2`.
*/
apply(t, e = -1) {
return Hm(t, e);
}
}
Hx.className = "logSoftmax";
j(Hx);
class Kx extends ke {
/**
* Calculate the activation function.
*
* @param x Tensor.
* @returns a Tensor of the same shape as x
*/
apply(t) {
return _(() => _(() => {
const e = Math.sqrt(2), s = R(0.5, Y(1, Bm(ut(t, e))));
return R(t, s);
}));
}
}
Kx.className = "gelu";
j(Kx);
class jx extends ke {
/**
* Calculate the activation function.
*
* @param x Tensor.
* @returns a Tensor of the same shape as x
*/
apply(t) {
return _(() => R(0.5, R(t, Y(1, Ll(R($e(ut(2, Math.PI)), Y(t, R(0.044715, Xs(t, 3)))))))));
}
}
jx.className = "gelu_new";
j(jx);
class Xx extends ke {
/**
* Calculate the activation function.
*
* @param x Tensor.
* @returns a Tensor of the same shape as x
*/
apply(t) {
return _(() => R(t, Ll($i(t))));
}
}
Xx.className = "mish";
j(Xx);
class qx extends ke {
/**
* Calculate the activation function.
*
* @param x Tensor.
* @param alpha Scaling factor for the sigmoid function.
* @returns a Tensor of the same shape as x
*/
apply(t, e = 1) {
return _(() => R(Bo(R(t, e)), t));
}
}
qx.className = "swish";
j(qx);
function ms(n) {
return n.getClassName();
}
function $c(n, t = {}) {
return Ei(n, nn.getMap().classNameMap, t, "activation");
}
function gs(n) {
if (n == null) {
const t = {};
return t.className = "linear", t.config = {}, $c(t);
}
if (typeof n == "string") {
const t = {};
return t.className = n, t.config = {}, $c(t);
} else
return n instanceof ke ? n : $c(n);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function FT(n) {
if (n != null && typeof n != "object")
throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${n}`);
}
class Yx extends Uo {
}
class Jx extends Yx {
constructor(t) {
super(), FT(t), this.l1 = t == null || t.l1 == null ? 0.01 : t.l1, this.l2 = t == null || t.l2 == null ? 0.01 : t.l2, this.hasL1 = this.l1 !== 0, this.hasL2 = this.l2 !== 0;
}
/**
* Porting note: Renamed from __call__.
* @param x Variable of which to calculate the regularization score.
*/
apply(t) {
return _(() => {
let e = he([1]);
return this.hasL1 && (e = Y(e, ct(R(this.l1, Ne(t))))), this.hasL2 && (e = Y(e, ct(R(this.l2, Di(t))))), A(e, []);
});
}
getConfig() {
return { l1: this.l1, l2: this.l2 };
}
/** @nocollapse */
static fromConfig(t, e) {
return new t({ l1: e.l1, l2: e.l2 });
}
}
Jx.className = "L1L2";
j(Jx);
const Hp = {
l1l2: "L1L2"
};
function _t(n) {
return gd(n);
}
function Kp(n, t = {}) {
return Ei(n, nn.getMap().classNameMap, t, "regularizer");
}
function Gt(n) {
if (n == null)
return null;
if (typeof n == "string") {
const e = { className: n in Hp ? Hp[n] : n, config: {} };
return Kp(e);
} else
return n instanceof Yx ? n : Kp(n);
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class Zx extends Ct {
constructor(t) {
super(t ?? {}), this.supportsMasking = !0, t != null && (this.maxValue = t.maxValue);
}
call(t, e) {
t = ft(t);
let s = ro(t);
return this.maxValue != null && (s = Ye(s, 0, this.maxValue)), s;
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = { maxValue: this.maxValue }, e = super.getConfig();
return Object.assign(t, e), t;
}
}
Zx.className = "ReLU";
j(Zx);
class Qx extends Ct {
constructor(t) {
super(t ?? {}), this.DEFAULT_ALPHA = 0.3, t == null && (t = {}), this.alpha = t.alpha == null ? this.DEFAULT_ALPHA : t.alpha;
}
call(t, e) {
const s = ft(t);
return kh(s, this.alpha);
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = { alpha: this.alpha }, e = super.getConfig();
return Object.assign(t, e), t;
}
}
Qx.className = "LeakyReLU";
j(Qx);
class tb extends Ct {
constructor(t) {
if (super(t ?? {}), this.DEFAULT_ALPHA_INITIALIZER = "zeros", t == null && (t = {}), this.supportsMasking = !0, this.alphaInitializer = Ut(t.alphaInitializer || this.DEFAULT_ALPHA_INITIALIZER), this.alphaRegularizer = Gt(t.alphaRegularizer), this.alphaConstraint = ae(t.alphaConstraint), t.sharedAxes == null)
this.sharedAxes = null;
else if (Array.isArray(t.sharedAxes))
this.sharedAxes = t.sharedAxes;
else if (typeof t.sharedAxes == "number")
this.sharedAxes = [t.sharedAxes];
else
throw new E(`Expected sharedAxes to be a number or an array of numbers, but got ${t.sharedAxes}`);
}
build(t) {
t = St(t);
const e = t.slice(1);
if (this.sharedAxes != null)
for (const o of this.sharedAxes)
e[o - 1] = 1;
this.alpha = this.addWeight("alpha", e, "float32", this.alphaInitializer, this.alphaRegularizer, !0, this.alphaConstraint);
const s = {};
if (this.sharedAxes != null)
for (let o = 1; o < t.length; ++o)
s[o] = t[o];
this.inputSpec = [new re({
ndim: t.length,
axes: s
})], this.built = !0;
}
call(t, e) {
return t = ft(t), Rh(t, this.alpha.read());
}
getConfig() {
const t = {
alphaInitializer: Kt(this.alphaInitializer),
alphaRegularizer: _t(this.alphaRegularizer),
alphaConstraint: ie(this.alphaConstraint),
sharedAxes: this.sharedAxes
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
tb.className = "PReLU";
j(tb);
let eb = class extends Ct {
constructor(t) {
if (super(t ?? {}), this.DEFAULT_ALPHA = 1, t == null && (t = {}), t.alpha != null && t.alpha !== this.DEFAULT_ALPHA)
throw new gt(`Non-default alpha value (${t.alpha}) is not supported by the ELU layer yet.`);
this.alpha = t.alpha == null ? this.DEFAULT_ALPHA : t.alpha;
}
call(t, e) {
const s = ft(t);
return zl(s);
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = { alpha: this.alpha }, e = super.getConfig();
return Object.assign(t, e), t;
}
};
eb.className = "ELU";
j(eb);
class nb extends Ct {
constructor(t) {
super(t ?? {}), this.DEFAULT_THETA = 1, t == null && (t = {}), this.theta = t.theta == null ? this.DEFAULT_THETA : t.theta;
}
call(t, e) {
const s = ft(t);
return R(s, st(Je(s, this.theta), "float32"));
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = { theta: this.theta }, e = super.getConfig();
return Object.assign(t, e), t;
}
}
nb.className = "ThresholdedReLU";
j(nb);
class sb extends Ct {
constructor(t) {
super(t ?? {}), this.DEFAULT_AXIS = 1, t == null && (t = {}), this.softmax = new Rd().apply, this.axis = t.axis == null ? this.DEFAULT_AXIS : t.axis;
}
call(t, e) {
return _(() => {
let s = ft(t);
const o = e.mask;
if (o != null) {
const r = R(pt(ks(s.shape), st(o, s.dtype)), Tt(-1e9));
s = Y(s, r);
}
return this.axis instanceof Array ? this.axis.length > 1 ? Ln(pt(s, Km(s, this.axis, !0))) : this.softmax(s, this.axis[0]) : this.softmax(s, this.axis);
});
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = { axis: this.axis }, e = super.getConfig();
return Object.assign(t, e), t;
}
}
sb.className = "Softmax";
j(sb);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function ko(n, t, e) {
if (typeof n == "number")
return Js(n, t);
if (n.length !== t)
throw new E(`The ${e} argument must be an integer or tuple of ${t} integers. Received: ${n.length} elements.`);
for (let s = 0; s < t; ++s) {
const o = n[s];
if (!f2(o))
throw new E(`The ${e} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(n)} including a non-integer number ${o}`);
}
return n;
}
function yn(n, t, e, s, o = 1) {
if (n == null)
return n;
const r = t + (t - 1) * (o - 1);
let i;
return e === "same" ? i = n : i = n - r + 1, Math.floor((i + s - 1) / s);
}
function Tn(n, t, e, s) {
if (n == null)
return null;
if (s === "valid")
n = n * t + fs([e - t, 0]);
else if (s === "same")
n = n * t;
else
throw new E(`Unsupport padding mode: ${s}.`);
return n;
}
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function Dd(n, t) {
return _(() => (Qt(t), t === "channelsFirst" ? It(n, [0, 2, 3, 1]) : n));
}
function ob(n, t) {
return _(() => (Qt(t), t === "channelsFirst" ? It(n, [0, 2, 3, 4, 1]) : n));
}
function OT(n, t, e, s = 1, o = "valid", r, i = 1) {
return _(() => {
if (r == null && (r = Cn()), Qt(r), n.shape.length !== 3)
throw new E(`The input of a conv1dWithBias operation should be 3, but is ${n.shape.length} instead.`);
if (t.shape.length !== 3)
throw new E(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);
if (e != null && e.shape.length !== 1)
throw new E(`The bias for a conv1dWithBias operation should be 1, but is ${e.shape.length} instead`);
if (r === "channelsFirst" && (n = It(n, [0, 2, 1])), o === "causal")
throw new gt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");
let a = _m(n, t, s, o === "same" ? "same" : "valid", "NWC", i);
return e != null && (a = In(a, e)), a;
});
}
function jp(n, t, e, s = [1, 1], o = "valid", r, i, a = null) {
return _(() => {
if (r == null && (r = Cn()), Qt(r), n.rank !== 3 && n.rank !== 4)
throw new E(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${n.rank}.`);
if (t.rank !== 3 && t.rank !== 4)
throw new E(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${n.rank}.`);
let l = Dd(n, r);
if (o === "causal")
throw new gt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");
return l = Uk({
x: l,
filter: t,
strides: s,
pad: o === "same" ? "same" : "valid",
dilations: i,
dataFormat: "NHWC",
bias: e,
activation: a
}), r === "channelsFirst" && (l = It(l, [0, 3, 1, 2])), l;
});
}
function _T(n, t, e, s = [1, 1, 1], o = "valid", r, i) {
return _(() => {
if (r == null && (r = Cn()), Qt(r), n.rank !== 4 && n.rank !== 5)
throw new E(`conv3dWithBias expects input to be of rank 4 or 5, but received ${n.rank}.`);
if (t.rank !== 4 && t.rank !== 5)
throw new E(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${n.rank}.`);
let a = ob(n, r);
if (o === "causal")
throw new gt("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");
return a = o$(a, t, s, o === "same" ? "same" : "valid", "NDHWC", i), e != null && (a = In(a, e)), r === "channelsFirst" && (a = It(a, [0, 4, 1, 2, 3])), a;
});
}
class Jl extends Ct {
constructor(t, e) {
if (super(e), this.bias = null, this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_BIAS_INITIALIZER = "zeros", Jl.verifyArgs(e), this.rank = t, de(this.rank, "rank"), this.rank !== 1 && this.rank !== 2 && this.rank !== 3)
throw new gt(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);
if (this.kernelSize = ko(e.kernelSize, t, "kernelSize"), this.strides = ko(e.strides == null ? 1 : e.strides, t, "strides"), this.padding = e.padding == null ? "valid" : e.padding, Ze(this.padding), this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Qt(this.dataFormat), this.activation = gs(e.activation), this.useBias = e.useBias == null ? !0 : e.useBias, this.biasInitializer = Ut(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.biasConstraint = ae(e.biasConstraint), this.biasRegularizer = Gt(e.biasRegularizer), this.activityRegularizer = Gt(e.activityRegularizer), this.dilationRate = ko(e.dilationRate == null ? 1 : e.dilationRate, t, "dilationRate"), this.rank === 1 && Array.isArray(this.dilationRate) && this.dilationRate.length !== 1)
throw new E(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);
if (this.rank === 2) {
if (typeof this.dilationRate == "number")
this.dilationRate = [this.dilationRate, this.dilationRate];
else if (this.dilationRate.length !== 2)
throw new E(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`);
} else if (this.rank === 3) {
if (typeof this.dilationRate == "number")
this.dilationRate = [this.dilationRate, this.dilationRate, this.dilationRate];
else if (this.dilationRate.length !== 3)
throw new E(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`);
}
}
static verifyArgs(t) {
if (Nn("kernelSize" in t, "required key 'kernelSize' not in config"), typeof t.kernelSize != "number" && !xd(t.kernelSize, "number", 1, 3))
throw new E(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(t.kernelSize)}.`);
}
getConfig() {
const t = {
kernelSize: this.kernelSize,
strides: this.strides,
padding: this.padding,
dataFormat: this.dataFormat,
dilationRate: this.dilationRate,
activation: ms(this.activation),
useBias: this.useBias,
biasInitializer: Kt(this.biasInitializer),
biasRegularizer: _t(this.biasRegularizer),
activityRegularizer: _t(this.activityRegularizer),
biasConstraint: ie(this.biasConstraint)
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
class Go extends Jl {
constructor(t, e) {
super(t, e), this.kernel = null, Go.verifyArgs(e), this.filters = e.filters, de(this.filters, "filters"), this.kernelInitializer = Ut(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.kernelConstraint = ae(e.kernelConstraint), this.kernelRegularizer = Gt(e.kernelRegularizer);
}
build(t) {
t = St(t);
const e = this.dataFormat === "channelsFirst" ? 1 : t.length - 1;
if (t[e] == null)
throw new E(`The channel dimension of the input should be defined. Found ${t[e]}`);
const s = t[e], o = this.kernelSize.concat([s, this.filters]);
this.kernel = this.addWeight("kernel", o, null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint)), this.inputSpec = [{ ndim: this.rank + 2, axes: { [e]: s } }], this.built = !0;
}
call(t, e) {
return _(() => {
t = ft(t);
let s;
const o = this.bias == null ? null : this.bias.read(), r = tx(this.activation.getClassName());
if (r != null && this.rank === 2)
s = jp(t, this.kernel.read(), o, this.strides, this.padding, this.dataFormat, this.dilationRate, r);
else {
if (this.rank === 1)
s = OT(t, this.kernel.read(), o, this.strides[0], this.padding, this.dataFormat, this.dilationRate[0]);
else if (this.rank === 2)
s = jp(t, this.kernel.read(), o, this.strides, this.padding, this.dataFormat, this.dilationRate);
else if (this.rank === 3)
s = _T(t, this.kernel.read(), o, this.strides, this.padding, this.dataFormat, this.dilationRate);
else
throw new gt("convolutions greater than 3D are not implemented yet.");
this.activation != null && (s = this.activation.apply(s));
}
return s;
});
}
computeOutputShape(t) {
t = St(t);
const e = [], s = this.dataFormat === "channelsLast" ? t.slice(1, t.length - 1) : t.slice(2);
for (let r = 0; r < s.length; ++r) {
const i = yn(s[r], this.kernelSize[r], this.padding, this.strides[r], typeof this.dilationRate == "number" ? this.dilationRate : this.dilationRate[r]);
e.push(i);
}
let o = [t[0]];
return this.dataFormat === "channelsLast" ? (o = o.concat(e), o.push(this.filters)) : (o.push(this.filters), o = o.concat(e)), o;
}
getConfig() {
const t = {
filters: this.filters,
kernelInitializer: Kt(this.kernelInitializer),
kernelRegularizer: _t(this.kernelRegularizer),
kernelConstraint: ie(this.kernelConstraint)
}, e = super.getConfig();
return Object.assign(t, e), t;
}
static verifyArgs(t) {
if (!("filters" in t) || typeof t.filters != "number" || t.filters < 1)
throw new E(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(t.filters)}`);
}
}
class _i extends Go {
constructor(t) {
super(2, t), _i.verifyArgs(t);
}
getConfig() {
const t = super.getConfig();
return delete t.rank, t;
}
static verifyArgs(t) {
if (typeof t.kernelSize != "number" && !xd(t.kernelSize, "number", 1, 2))
throw new E(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(t.kernelSize)}.`);
}
}
_i.className = "Conv2D";
j(_i);
class Li extends Go {
constructor(t) {
super(3, t), Li.verifyArgs(t);
}
getConfig() {
const t = super.getConfig();
return delete t.rank, t;
}
static verifyArgs(t) {
if (typeof t.kernelSize != "number" && !(Array.isArray(t.kernelSize) && (t.kernelSize.length === 1 || t.kernelSize.length === 3)))
throw new E(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(t.kernelSize)}.`);
}
}
Li.className = "Conv3D";
j(Li);
class rb extends _i {
constructor(t) {
if (super(t), this.inputSpec = [new re({ ndim: 4 })], this.padding !== "same" && this.padding !== "valid")
throw new E(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`);
}
build(t) {
if (t = St(t), t.length !== 4)
throw new E("Input should have rank 4; Received input shape: " + JSON.stringify(t));
const e = this.dataFormat === "channelsFirst" ? 1 : t.length - 1;
if (t[e] == null)
throw new E("The channel dimension of the inputs should be defined. Found `None`.");
const s = t[e], o = this.kernelSize.concat([this.filters, s]);
this.kernel = this.addWeight("kernel", o, "float32", this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint)), this.inputSpec = [new re({ ndim: 4, axes: { [e]: s } })], this.built = !0;
}
call(t, e) {
return _(() => {
let s = ft(t);
if (s.shape.length !== 4)
throw new E(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);
const o = s.shape, r = o[0];
let i, a;
this.dataFormat === "channelsFirst" ? (i = 2, a = 3) : (i = 1, a = 2);
const l = o[i], c = o[a], u = this.kernelSize[0], h = this.kernelSize[1], d = this.strides[0], p = this.strides[1], f = Tn(l, d, u, this.padding), m = Tn(c, p, h, this.padding), g = [r, f, m, this.filters];
this.dataFormat !== "channelsLast" && (s = It(s, [0, 2, 3, 1]));
let x = Lm(s, this.kernel.read(), g, this.strides, this.padding);
return this.dataFormat !== "channelsLast" && (x = It(x, [0, 3, 1, 2])), this.bias != null && (x = In(x, this.bias.read(), this.dataFormat)), this.activation != null && (x = this.activation.apply(x)), x;
});
}
computeOutputShape(t) {
t = St(t);
const e = t.slice();
let s, o, r;
this.dataFormat === "channelsFirst" ? (s = 1, o = 2, r = 3) : (s = 3, o = 1, r = 2);
const i = this.kernelSize[0], a = this.kernelSize[1], l = this.strides[0], c = this.strides[1];
return e[s] = this.filters, e[o] = Tn(e[o], l, i, this.padding), e[r] = Tn(e[r], c, a, this.padding), e;
}
getConfig() {
const t = super.getConfig();
return delete t.dilationRate, t;
}
}
rb.className = "Conv2DTranspose";
j(rb);
class ib extends Li {
constructor(t) {
if (super(t), this.inputSpec = [new re({ ndim: 5 })], this.padding !== "same" && this.padding !== "valid")
throw new E(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`);
}
build(t) {
if (t = St(t), t.length !== 5)
throw new E("Input should have rank 5; Received input shape: " + JSON.stringify(t));
const e = this.dataFormat === "channelsFirst" ? 1 : t.length - 1;
if (t[e] == null)
throw new E("The channel dimension of the inputs should be defined. Found `None`.");
const s = t[e], o = this.kernelSize.concat([this.filters, s]);
this.kernel = this.addWeight("kernel", o, "float32", this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint)), this.inputSpec = [new re({ ndim: 5, axes: { [e]: s } })], this.built = !0;
}
call(t, e) {
return _(() => {
let s = ft(t);
if (s.shape.length !== 5)
throw new E(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);
const o = s.shape, r = o[0];
let i, a, l;
this.dataFormat === "channelsFirst" ? (l = 2, i = 3, a = 4) : (l = 1, i = 2, a = 3);
const c = o[l], u = o[i], h = o[a], d = this.kernelSize[0], p = this.kernelSize[1], f = this.kernelSize[2], m = this.strides[0], g = this.strides[1], x = this.strides[2], b = Tn(c, m, d, this.padding), w = Tn(u, g, p, this.padding), y = Tn(h, x, f, this.padding), C = [r, b, w, y, this.filters];
this.dataFormat !== "channelsLast" && (s = It(s, [0, 2, 3, 4, 1]));
let $ = a$(s, this.kernel.read(), C, this.strides, this.padding);
return this.dataFormat !== "channelsLast" && ($ = It($, [0, 4, 1, 2, 3])), this.bias !== null && ($ = In($, this.bias.read(), this.dataFormat)), this.activation !== null && ($ = this.activation.apply($)), $;
});
}
computeOutputShape(t) {
t = St(t);
const e = t.slice();
let s, o, r, i;
this.dataFormat === "channelsFirst" ? (s = 1, o = 2, r = 3, i = 4) : (s = 4, o = 1, r = 2, i = 3);
const a = this.kernelSize[0], l = this.kernelSize[1], c = this.kernelSize[2], u = this.strides[0], h = this.strides[1], d = this.strides[2];
return e[s] = this.filters, e[o] = Tn(e[o], u, a, this.padding), e[r] = Tn(e[r], h, l, this.padding), e[i] = Tn(e[i], d, c, this.padding), e;
}
getConfig() {
const t = super.getConfig();
return delete t.dilationRate, t;
}
}
ib.className = "Conv3DTranspose";
j(ib);
class ab extends Go {
constructor(t, e) {
if (super(t, e), this.DEFAULT_DEPTHWISE_INITIALIZER = "glorotUniform", this.DEFAULT_POINTWISE_INITIALIZER = "glorotUniform", this.depthwiseKernel = null, this.pointwiseKernel = null, e.filters == null)
throw new E("The `filters` configuration field is required by SeparableConv, but is unspecified.");
if (e.kernelInitializer != null || e.kernelRegularizer != null || e.kernelConstraint != null)
throw new E("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");
if (e.padding != null && e.padding !== "same" && e.padding !== "valid")
throw new E(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(e.padding)}`);
this.depthMultiplier = e.depthMultiplier == null ? 1 : e.depthMultiplier, this.depthwiseInitializer = Ut(e.depthwiseInitializer || this.DEFAULT_DEPTHWISE_INITIALIZER), this.depthwiseRegularizer = Gt(e.depthwiseRegularizer), this.depthwiseConstraint = ae(e.depthwiseConstraint), this.pointwiseInitializer = Ut(e.depthwiseInitializer || this.DEFAULT_POINTWISE_INITIALIZER), this.pointwiseRegularizer = Gt(e.pointwiseRegularizer), this.pointwiseConstraint = ae(e.pointwiseConstraint);
}
build(t) {
if (t = St(t), t.length < this.rank + 2)
throw new E(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank + 2}, but received input shape: ${JSON.stringify(t)}`);
const e = this.dataFormat === "channelsFirst" ? 1 : t.length - 1;
if (t[e] == null || t[e] < 0)
throw new E(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(t[e])}`);
const s = t[e], o = this.kernelSize.concat([s, this.depthMultiplier]), r = [];
for (let a = 0; a < this.rank; ++a)
r.push(1);
r.push(s * this.depthMultiplier, this.filters);
const i = !0;
this.depthwiseKernel = this.addWeight("depthwise_kernel", o, "float32", this.depthwiseInitializer, this.depthwiseRegularizer, i, this.depthwiseConstraint), this.pointwiseKernel = this.addWeight("pointwise_kernel", r, "float32", this.pointwiseInitializer, this.pointwiseRegularizer, i, this.pointwiseConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, i, this.biasConstraint) : this.bias = null, this.inputSpec = [new re({ ndim: this.rank + 2, axes: { [e]: s } })], this.built = !0;
}
call(t, e) {
return _(() => {
t = ft(t);
let s;
if (this.rank === 1)
throw new gt("1D separable convolution is not implemented yet.");
return this.rank === 2 && (this.dataFormat === "channelsFirst" && (t = It(t, [0, 2, 3, 1])), s = tg(t, this.depthwiseKernel.read(), this.pointwiseKernel.read(), this.strides, this.padding, this.dilationRate, "NHWC")), this.useBias && (s = In(s, this.bias.read(), this.dataFormat)), this.activation != null && (s = this.activation.apply(s)), this.dataFormat === "channelsFirst" && (s = It(s, [0, 3, 1, 2])), s;
});
}
getConfig() {
const t = super.getConfig();
return delete t.rank, delete t.kernelInitializer, delete t.kernelRegularizer, delete t.kernelConstraint, t.depthwiseInitializer = Kt(this.depthwiseInitializer), t.pointwiseInitializer = Kt(this.pointwiseInitializer), t.depthwiseRegularizer = _t(this.depthwiseRegularizer), t.pointwiseRegularizer = _t(this.pointwiseRegularizer), t.depthwiseConstraint = ie(this.depthwiseConstraint), t.pointwiseConstraint = ie(this.pointwiseConstraint), t;
}
}
ab.className = "SeparableConv";
class lb extends ab {
constructor(t) {
super(2, t);
}
}
lb.className = "SeparableConv2D";
j(lb);
class Zl extends Go {
constructor(t) {
super(1, t), Zl.verifyArgs(t), this.inputSpec = [{ ndim: 3 }];
}
getConfig() {
const t = super.getConfig();
return delete t.rank, delete t.dataFormat, t;
}
static verifyArgs(t) {
if (typeof t.kernelSize != "number" && !xd(t.kernelSize, "number", 1, 1))
throw new E(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(t.kernelSize)}.`);
}
}
Zl.className = "Conv1D";
j(Zl);
class cb extends Ct {
constructor(t) {
super(t), typeof t.cropping == "number" ? this.cropping = [[t.cropping, t.cropping], [t.cropping, t.cropping]] : typeof t.cropping[0] == "number" ? this.cropping = [
[t.cropping[0], t.cropping[0]],
[t.cropping[1], t.cropping[1]]
] : this.cropping = t.cropping, this.dataFormat = t.dataFormat === void 0 ? "channelsLast" : t.dataFormat, this.inputSpec = [{ ndim: 4 }];
}
computeOutputShape(t) {
return this.dataFormat === "channelsFirst" ? [
t[0],
t[1],
t[2] - this.cropping[0][0] - this.cropping[0][1],
t[3] - this.cropping[1][0] - this.cropping[1][1]
] : [
t[0],
t[1] - this.cropping[0][0] - this.cropping[0][1],
t[2] - this.cropping[1][0] - this.cropping[1][1],
t[3]
];
}
call(t, e) {
return _(() => {
if (t = ft(t), this.dataFormat === "channelsLast") {
const s = ji(t, this.cropping[0][0], t.shape[1] - this.cropping[0][0] - this.cropping[0][1], 2);
return ji(s, this.cropping[1][0], t.shape[2] - this.cropping[1][1] - this.cropping[1][0], 3);
} else {
const s = ji(t, this.cropping[0][0], t.shape[2] - this.cropping[0][0] - this.cropping[0][1], 3);
return ji(s, this.cropping[1][0], t.shape[3] - this.cropping[1][1] - this.cropping[1][0], 4);
}
});
}
getConfig() {
const t = { cropping: this.cropping, dataFormat: this.dataFormat }, e = super.getConfig();
return Object.assign(t, e), t;
}
}
cb.className = "Cropping2D";
j(cb);
class ub extends Ct {
constructor(t) {
super(t), this.DEFAULT_SIZE = [2, 2], this.inputSpec = [{ ndim: 4 }], this.size = t.size == null ? this.DEFAULT_SIZE : t.size, this.dataFormat = t.dataFormat == null ? "channelsLast" : t.dataFormat, Qt(this.dataFormat), this.interpolation = t.interpolation == null ? "nearest" : t.interpolation, h2(this.interpolation);
}
computeOutputShape(t) {
if (this.dataFormat === "channelsFirst") {
const e = t[2] == null ? null : this.size[0] * t[2], s = t[3] == null ? null : this.size[1] * t[3];
return [t[0], t[1], e, s];
} else {
const e = t[1] == null ? null : this.size[0] * t[1], s = t[2] == null ? null : this.size[1] * t[2];
return [t[0], e, s, t[3]];
}
}
call(t, e) {
return _(() => {
let s = ft(t);
const o = s.shape;
if (this.dataFormat === "channelsFirst") {
s = It(s, [0, 2, 3, 1]);
const r = this.size[0] * o[2], i = this.size[1] * o[3], a = this.interpolation === "nearest" ? Hn.resizeNearestNeighbor(s, [r, i]) : Hn.resizeBilinear(s, [r, i]);
return It(a, [0, 3, 1, 2]);
} else {
const r = this.size[0] * o[1], i = this.size[1] * o[2];
return this.interpolation === "nearest" ? Hn.resizeNearestNeighbor(s, [r, i]) : Hn.resizeBilinear(s, [r, i]);
}
});
}
getConfig() {
const t = {
size: this.size,
dataFormat: this.dataFormat,
interpolation: this.interpolation
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
ub.className = "UpSampling2D";
j(ub);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function LT(n, t, e = [1, 1], s = "valid", o, r) {
return _(() => {
o == null && (o = Cn()), Qt(o);
let i = Dd(n, o);
if (n.rank !== 4)
throw new E(`Input for depthwiseConv2d is required to be 4-D, but is instead ${n.rank}-D`);
if (t.rank !== 4)
throw new E(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);
return i = wh(i, t, e, s === "same" ? "same" : "valid", "NHWC", r), o === "channelsFirst" && (i = It(i, [0, 3, 1, 2])), i;
});
}
class hb extends Jl {
constructor(t) {
super(2, t), this.depthwiseKernel = null, this.depthMultiplier = t.depthMultiplier == null ? 1 : t.depthMultiplier, this.depthwiseInitializer = Ut(t.depthwiseInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.depthwiseConstraint = ae(t.depthwiseConstraint), this.depthwiseRegularizer = Gt(t.depthwiseRegularizer);
}
build(t) {
if (t = St(t), t.length < 4)
throw new E(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(t)}.`);
const e = this.dataFormat === "channelsFirst" ? 1 : 3;
if (t[e] == null || t[e] < 0)
throw new E(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${t[e]}).`);
const s = t[e], o = [
this.kernelSize[0],
this.kernelSize[1],
s,
this.depthMultiplier
];
this.depthwiseKernel = this.addWeight("depthwise_kernel", o, null, this.depthwiseInitializer, this.depthwiseRegularizer, !0, this.depthwiseConstraint), this.useBias ? this.bias = this.addWeight("bias", [s * this.depthMultiplier], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint) : this.bias = null, this.built = !0;
}
call(t, e) {
return _(() => {
t = ft(t);
let s = LT(t, this.depthwiseKernel.read(), this.strides, this.padding, this.dataFormat, null);
return this.useBias && (s = In(s, this.bias.read(), this.dataFormat)), this.activation != null && (s = this.activation.apply(s)), s;
});
}
computeOutputShape(t) {
t = St(t);
const e = this.dataFormat === "channelsFirst" ? t[2] : t[1], s = this.dataFormat === "channelsFirst" ? t[3] : t[2], o = this.dataFormat === "channelsFirst" ? t[1] * this.depthMultiplier : t[3] * this.depthMultiplier, r = yn(e, this.kernelSize[0], this.padding, this.strides[0]), i = yn(s, this.kernelSize[1], this.padding, this.strides[1]);
return this.dataFormat === "channelsFirst" ? [t[0], o, r, i] : [t[0], r, i, o];
}
getConfig() {
const t = super.getConfig();
return t.depthMultiplier = this.depthMultiplier, t.depthwiseInitializer = Kt(this.depthwiseInitializer), t.depthwiseRegularizer = _t(this.depthwiseRegularizer), t.depthwiseConstraint = ie(this.depthwiseRegularizer), t;
}
}
hb.className = "DepthwiseConv2D";
j(hb);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function db(n, t, e, s) {
if (Array.isArray(n)) {
if (t != null || e != null)
throw new E("When inputs is an array, neither initialState or constants should be provided");
s != null && (e = n.slice(n.length - s, n.length), n = n.slice(0, n.length - s)), n.length > 1 && (t = n.slice(1, n.length)), n = n[0];
}
function o(r) {
return r == null || Array.isArray(r) ? r : [r];
}
return t = o(t), e = o(e), { inputs: n, initialState: t, constants: e };
}
function pb(n, t, e, s = !1, o, r, i = !1, a = !1) {
return _(() => {
const l = t.shape.length;
if (l < 3)
throw new E(`Input should be at least 3D, but is ${l}D.`);
const c = [1, 0].concat(wn(2, l));
if (t = It(t, c), r != null)
throw new gt("The rnn() functoin of the deeplearn.js backend does not support constants yet.");
i && console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."), o != null && (o = st(st(o, "bool"), "float32"), o.rank === l - 1 && (o = Oe(o, -1)), o = It(o, c)), s && (t = qs(t, 0), o != null && (o = qs(o, 0)));
const u = [];
let h, d = e;
const p = t.shape[0], f = Ys(t);
let m;
o != null && (m = Ys(o));
for (let x = 0; x < p; ++x) {
const b = f[x], w = _(() => n(b, d));
if (o == null)
h = w[0], d = w[1];
else {
const y = _(() => {
const C = m[x], $ = pt(an(C), C), k = Y(R(w[0], C), R(d[0], $)), v = d.map((S, T) => Y(R(w[1][T], C), R(S, $)));
return { output: k, newStates: v };
});
h = y.output, d = y.newStates;
}
a && u.push(h);
}
let g;
return a && (g = Xn(u, 1)), [h, g, d];
});
}
class Ss extends Ct {
constructor(t) {
super(t);
let e;
if (t.cell == null)
throw new E("cell property is missing for the constructor of RNN.");
if (Array.isArray(t.cell) ? e = new Od({ cells: t.cell }) : e = t.cell, e.stateSize == null)
throw new E("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");
this.cell = e, this.returnSequences = t.returnSequences == null ? !1 : t.returnSequences, this.returnState = t.returnState == null ? !1 : t.returnState, this.goBackwards = t.goBackwards == null ? !1 : t.goBackwards, this._stateful = t.stateful == null ? !1 : t.stateful, this.unroll = t.unroll == null ? !1 : t.unroll, this.supportsMasking = !0, this.inputSpec = [new re({ ndim: 3 })], this.stateSpec = null, this.states_ = null, this.numConstants = null, this.keptStates = [];
}
// Porting Note: This is the equivalent of `RNN.states` property getter in
// PyKeras.
getStates() {
if (this.states_ == null) {
const t = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
return wn(0, t).map((e) => null);
} else
return this.states_;
}
// Porting Note: This is the equivalent of the `RNN.states` property setter in
// PyKeras.
setStates(t) {
this.states_ = t;
}
computeOutputShape(t) {
tu(t) && (t = t[0]), t = t;
let e = this.cell.stateSize;
Array.isArray(e) || (e = [e]);
const s = e[0];
let o;
if (this.returnSequences ? o = [t[0], t[1], s] : o = [t[0], s], this.returnState) {
const r = [];
for (const i of e)
r.push([t[0], i]);
return [o].concat(r);
} else
return o;
}
computeMask(t, e) {
return _(() => {
Array.isArray(e) && (e = e[0]);
const s = this.returnSequences ? e : null;
if (this.returnState) {
const o = this.states.map((r) => null);
return [s].concat(o);
} else
return s;
});
}
/**
* Get the current state tensors of the RNN.
*
* If the state hasn't been set, return an array of `null`s of the correct
* length.
*/
get states() {
if (this.states_ == null) {
const t = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1, e = [];
for (let s = 0; s < t; ++s)
e.push(null);
return e;
} else
return this.states_;
}
set states(t) {
this.states_ = t;
}
build(t) {
if (this.numConstants != null)
throw new gt("Constants support is not implemented in RNN yet.");
tu(t) && (t = t[0]), t = t;
const e = this.stateful ? t[0] : null, s = t.slice(2);
this.inputSpec[0] = new re({ shape: [e, null, ...s] });
const o = [t[0]].concat(t.slice(2));
this.cell.build(o);
let r;
if (Array.isArray(this.cell.stateSize) ? r = this.cell.stateSize : r = [this.cell.stateSize], this.stateSpec != null) {
if (!Et(this.stateSpec.map((i) => i.shape[i.shape.length - 1]), r))
throw new E(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`);
} else
this.stateSpec = r.map((i) => new re({ shape: [null, i] }));
this.stateful && this.resetStates();
}
/**
* Reset the state tensors of the RNN.
*
* If the `states` argument is `undefined` or `null`, will set the
* state tensor(s) of the RNN to all-zero tensors of the appropriate
* shape(s).
*
* If `states` is provided, will set the state tensors of the RNN to its
* value.
*
* @param states Optional externally-provided initial states.
* @param training Whether this call is done during training. For stateful
* RNNs, this affects whether the old states are kept or discarded. In
* particular, if `training` is `true`, the old states will be kept so
* that subsequent backpropgataion through time (BPTT) may work properly.
* Else, the old states will be discarded.
*/
resetStates(t, e = !1) {
_(() => {
if (!this.stateful)
throw new Sn("Cannot call resetStates() on an RNN Layer that is not stateful.");
const s = this.inputSpec[0].shape[0];
if (s == null)
throw new E("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");
if (this.states_ == null)
Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map((o) => he([s, o])) : this.states_ = [he([s, this.cell.stateSize])];
else if (t == null)
$t(this.states_), this.keptStates != null && ($t(this.keptStates), this.keptStates = []), Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map((o) => he([s, o])) : this.states_[0] = he([s, this.cell.stateSize]);
else {
if (Array.isArray(t) || (t = [t]), t.length !== this.states_.length)
throw new E(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);
e === !0 ? this.keptStates.push(this.states_.slice()) : $t(this.states_);
for (let o = 0; o < this.states_.length; ++o) {
const r = t[o], i = Array.isArray(this.cell.stateSize) ? this.cell.stateSize[o] : this.cell.stateSize, a = [s, i];
if (!Et(r.shape, a))
throw new E(`State ${o} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${r.shape}`);
this.states_[o] = r;
}
}
this.states_ = this.states_.map((o) => Dn(o.clone()));
});
}
apply(t, e) {
let s = e == null ? null : e.initialState, o = e == null ? null : e.constants;
e == null && (e = {});
const r = db(t, s, o, this.numConstants);
t = r.inputs, s = r.initialState, o = r.constants;
let i = [], a = [];
if (s != null) {
e.initialState = s, i = i.concat(s), this.stateSpec = [];
for (const c of s)
this.stateSpec.push(new re({ shape: c.shape }));
a = a.concat(this.stateSpec);
}
if (o != null && (e.constants = o, i = i.concat(o), this.numConstants = o.length), i[0] instanceof Pn) {
const c = [t].concat(i), u = this.inputSpec.concat(a), h = this.inputSpec;
this.inputSpec = u;
const d = super.apply(c, e);
return this.inputSpec = h, d;
} else
return super.apply(t, e);
}
// tslint:disable-next-line:no-any
call(t, e) {
return _(() => {
const s = e == null ? null : e.mask, o = e == null ? null : e.training;
let r = e == null ? null : e.initialState;
t = ft(t), r == null && (this.stateful ? r = this.states_ : r = this.getInitialState(t));
const i = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
if (r.length !== i)
throw new E(`RNN Layer has ${i} state(s) but was passed ${r.length} initial state(s).`);
this.unroll && console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");
const a = { training: o }, c = pb((f, m) => {
const g = this.cell.call([f].concat(m), a);
return [g[0], g.slice(1)];
}, t, r, this.goBackwards, s, null, this.unroll, this.returnSequences), u = c[0], h = c[1], d = c[2];
this.stateful && this.resetStates(d, o);
const p = this.returnSequences ? h : u;
return this.returnState ? [p].concat(d) : p;
});
}
getInitialState(t) {
return _(() => {
let e = he(t.shape);
return e = ct(e, [1, 2]), e = Ri(e), Array.isArray(this.cell.stateSize) ? this.cell.stateSize.map((s) => s > 1 ? Zc(e, [1, s]) : e) : this.cell.stateSize > 1 ? [Zc(e, [1, this.cell.stateSize])] : [e];
});
}
get trainableWeights() {
return this.trainable ? this.cell.trainableWeights : [];
}
get nonTrainableWeights() {
return this.trainable ? this.cell.nonTrainableWeights : this.cell.weights;
}
setFastWeightInitDuringBuild(t) {
super.setFastWeightInitDuringBuild(t), this.cell != null && this.cell.setFastWeightInitDuringBuild(t);
}
getConfig() {
const t = super.getConfig(), e = {
returnSequences: this.returnSequences,
returnState: this.returnState,
goBackwards: this.goBackwards,
stateful: this.stateful,
unroll: this.unroll
};
this.numConstants != null && (e.numConstants = this.numConstants);
const s = this.cell.getConfig();
return this.getClassName() === Ss.className && (e.cell = {
className: this.cell.getClassName(),
config: s
}), Object.assign(Object.assign(Object.assign({}, s), t), e);
}
/** @nocollapse */
static fromConfig(t, e, s = {}) {
const o = e.cell, r = Kn(o, s);
return new t(Object.assign(e, { cell: r }));
}
}
Ss.className = "RNN";
j(Ss);
class Ql extends Ct {
}
class Ad extends Ql {
constructor(t) {
super(t), this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", this.units = t.units, de(this.units, "units"), this.activation = gs(t.activation == null ? this.DEFAULT_ACTIVATION : t.activation), this.useBias = t.useBias == null ? !0 : t.useBias, this.kernelInitializer = Ut(t.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = Ut(t.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = Ut(t.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelRegularizer = Gt(t.kernelRegularizer), this.recurrentRegularizer = Gt(t.recurrentRegularizer), this.biasRegularizer = Gt(t.biasRegularizer), this.kernelConstraint = ae(t.kernelConstraint), this.recurrentConstraint = ae(t.recurrentConstraint), this.biasConstraint = ae(t.biasConstraint), this.dropout = Ro([1, fs([0, t.dropout == null ? 0 : t.dropout])]), this.recurrentDropout = Ro([
1,
fs([0, t.recurrentDropout == null ? 0 : t.recurrentDropout])
]), this.dropoutFunc = t.dropoutFunc, this.stateSize = this.units, this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(t) {
t = St(t), this.kernel = this.addWeight("kernel", [t[t.length - 1], this.units], null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units], null, this.recurrentInitializer, this.recurrentRegularizer, !0, this.recurrentConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint) : this.bias = null, this.built = !0;
}
// Porting Note: PyKeras' equivalent of this method takes two tensor inputs:
// `inputs` and `states`. Here, the two tensors are combined into an
// `Tensor[]` Array as the first input argument.
// Similarly, PyKeras' equivalent of this method returns two values:
// `output` and `[output]`. Here the two are combined into one length-2
// `Tensor[]`, consisting of `output` repeated.
call(t, e) {
return _(() => {
if (t = t, t.length !== 2)
throw new E(`SimpleRNNCell expects 2 input Tensors, got ${t.length}.`);
let s = t[1];
t = t[0];
const o = e.training == null ? !1 : e.training;
0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = xs({
ones: () => an(t),
rate: this.dropout,
training: o,
dropoutFunc: this.dropoutFunc
})), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = xs({
ones: () => an(s),
rate: this.recurrentDropout,
training: o,
dropoutFunc: this.dropoutFunc
}));
let r;
const i = this.dropoutMask, a = this.recurrentDropoutMask;
i != null ? r = On(R(t, i), this.kernel.read()) : r = On(t, this.kernel.read()), this.bias != null && (r = In(r, this.bias.read())), a != null && (s = R(s, a));
let l = Y(r, On(s, this.recurrentKernel.read()));
return this.activation != null && (l = this.activation.apply(l)), [l, l];
});
}
getConfig() {
const t = super.getConfig(), e = {
units: this.units,
activation: ms(this.activation),
useBias: this.useBias,
kernelInitializer: Kt(this.kernelInitializer),
recurrentInitializer: Kt(this.recurrentInitializer),
biasInitializer: Kt(this.biasInitializer),
kernelRegularizer: _t(this.kernelRegularizer),
recurrentRegularizer: _t(this.recurrentRegularizer),
biasRegularizer: _t(this.biasRegularizer),
activityRegularizer: _t(this.activityRegularizer),
kernelConstraint: ie(this.kernelConstraint),
recurrentConstraint: ie(this.recurrentConstraint),
biasConstraint: ie(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout
};
return Object.assign(Object.assign({}, t), e);
}
}
Ad.className = "SimpleRNNCell";
j(Ad);
class fb extends Ss {
constructor(t) {
t.cell = new Ad(t), super(t);
}
call(t, e) {
return _(() => {
this.cell.dropoutMask != null && ($t(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && ($t(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
const s = e == null ? null : e.mask, o = e == null ? null : e.training, r = e == null ? null : e.initialState;
return super.call(t, { mask: s, training: o, initialState: r });
});
}
/** @nocollapse */
static fromConfig(t, e) {
return new t(e);
}
}
fb.className = "SimpleRNN";
j(fb);
class Fd extends Ql {
constructor(t) {
if (super(t), this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", t.resetAfter)
throw new E("GRUCell does not support reset_after parameter set to true.");
this.units = t.units, de(this.units, "units"), this.activation = gs(t.activation === void 0 ? this.DEFAULT_ACTIVATION : t.activation), this.recurrentActivation = gs(t.recurrentActivation === void 0 ? this.DEFAULT_RECURRENT_ACTIVATION : t.recurrentActivation), this.useBias = t.useBias == null ? !0 : t.useBias, this.kernelInitializer = Ut(t.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = Ut(t.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = Ut(t.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelRegularizer = Gt(t.kernelRegularizer), this.recurrentRegularizer = Gt(t.recurrentRegularizer), this.biasRegularizer = Gt(t.biasRegularizer), this.kernelConstraint = ae(t.kernelConstraint), this.recurrentConstraint = ae(t.recurrentConstraint), this.biasConstraint = ae(t.biasConstraint), this.dropout = Ro([1, fs([0, t.dropout == null ? 0 : t.dropout])]), this.recurrentDropout = Ro([
1,
fs([0, t.recurrentDropout == null ? 0 : t.recurrentDropout])
]), this.dropoutFunc = t.dropoutFunc, this.implementation = t.implementation, this.stateSize = this.units, this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(t) {
t = St(t);
const e = t[t.length - 1];
this.kernel = this.addWeight("kernel", [e, this.units * 3], null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units * 3], null, this.recurrentInitializer, this.recurrentRegularizer, !0, this.recurrentConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.units * 3], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint) : this.bias = null, this.built = !0;
}
call(t, e) {
return _(() => {
if (t = t, t.length !== 2)
throw new E(`GRUCell expects 2 input Tensors (inputs, h, c), got ${t.length}.`);
const s = e.training == null ? !1 : e.training;
let o = t[1];
t = t[0], 0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = xs({
ones: () => an(t),
rate: this.dropout,
training: s,
count: 3,
dropoutFunc: this.dropoutFunc
})), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = xs({
ones: () => an(o),
rate: this.recurrentDropout,
training: s,
count: 3,
dropoutFunc: this.dropoutFunc
}));
const r = this.dropoutMask, i = this.recurrentDropoutMask;
let a, l, c;
0 < this.dropout && this.dropout < 1 && (t = R(t, r[0]));
let u = On(t, this.kernel.read());
this.useBias && (u = In(u, this.bias.read())), 0 < this.recurrentDropout && this.recurrentDropout < 1 && (o = R(o, i[0]));
const h = this.recurrentKernel.read(), [d, p] = qe(h, [2 * this.units, this.units], h.rank - 1), f = On(o, d), [m, g, x] = qe(u, 3, u.rank - 1), [b, w] = qe(f, 2, f.rank - 1);
a = this.recurrentActivation.apply(Y(m, b)), l = this.recurrentActivation.apply(Y(g, w));
const y = On(R(l, o), p);
c = this.activation.apply(Y(x, y));
const C = Y(R(a, o), R(Y(1, Yt(a)), c));
return [C, C];
});
}
getConfig() {
const t = super.getConfig(), e = {
units: this.units,
activation: ms(this.activation),
recurrentActivation: ms(this.recurrentActivation),
useBias: this.useBias,
kernelInitializer: Kt(this.kernelInitializer),
recurrentInitializer: Kt(this.recurrentInitializer),
biasInitializer: Kt(this.biasInitializer),
kernelRegularizer: _t(this.kernelRegularizer),
recurrentRegularizer: _t(this.recurrentRegularizer),
biasRegularizer: _t(this.biasRegularizer),
activityRegularizer: _t(this.activityRegularizer),
kernelConstraint: ie(this.kernelConstraint),
recurrentConstraint: ie(this.recurrentConstraint),
biasConstraint: ie(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout,
implementation: this.implementation,
resetAfter: !1
};
return Object.assign(Object.assign({}, t), e);
}
}
Fd.className = "GRUCell";
j(Fd);
class mb extends Ss {
constructor(t) {
t.implementation === 0 && console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."), t.cell = new Fd(t), super(t);
}
call(t, e) {
return _(() => {
this.cell.dropoutMask != null && ($t(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && ($t(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
const s = e == null ? null : e.mask, o = e == null ? null : e.training, r = e == null ? null : e.initialState;
return super.call(t, { mask: s, training: o, initialState: r });
});
}
/** @nocollapse */
static fromConfig(t, e) {
return e.implmentation === 0 && (e.implementation = 1), new t(e);
}
}
mb.className = "GRU";
j(mb);
class tc extends Ql {
constructor(t) {
super(t), this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", this.units = t.units, de(this.units, "units"), this.activation = gs(t.activation === void 0 ? this.DEFAULT_ACTIVATION : t.activation), this.recurrentActivation = gs(t.recurrentActivation === void 0 ? this.DEFAULT_RECURRENT_ACTIVATION : t.recurrentActivation), this.useBias = t.useBias == null ? !0 : t.useBias, this.kernelInitializer = Ut(t.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = Ut(t.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = Ut(t.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.unitForgetBias = t.unitForgetBias, this.kernelRegularizer = Gt(t.kernelRegularizer), this.recurrentRegularizer = Gt(t.recurrentRegularizer), this.biasRegularizer = Gt(t.biasRegularizer), this.kernelConstraint = ae(t.kernelConstraint), this.recurrentConstraint = ae(t.recurrentConstraint), this.biasConstraint = ae(t.biasConstraint), this.dropout = Ro([1, fs([0, t.dropout == null ? 0 : t.dropout])]), this.recurrentDropout = Ro([
1,
fs([0, t.recurrentDropout == null ? 0 : t.recurrentDropout])
]), this.dropoutFunc = t.dropoutFunc, this.implementation = t.implementation, this.stateSize = [this.units, this.units], this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(t) {
var e;
t = St(t);
const s = t[t.length - 1];
this.kernel = this.addWeight("kernel", [s, this.units * 4], null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units * 4], null, this.recurrentInitializer, this.recurrentRegularizer, !0, this.recurrentConstraint);
let o;
if (this.useBias) {
if (this.unitForgetBias) {
const r = this.biasInitializer, i = this.units;
o = new (e = class extends cn {
apply(l, c) {
const u = r.apply([i]), h = new yd().apply([i]), d = r.apply([i * 2]);
return Rp(Rp(u, h), d);
}
}, /** @nocollapse */
e.className = "CustomInit", e)();
} else
o = this.biasInitializer;
this.bias = this.addWeight("bias", [this.units * 4], null, o, this.biasRegularizer, !0, this.biasConstraint);
} else
this.bias = null;
this.built = !0;
}
call(t, e) {
return _(() => {
const s = e.training == null ? !1 : e.training;
if (t = t, t.length !== 3)
throw new E(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${t.length}.`);
let o = t[1];
const r = t[2];
t = t[0], 0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = xs({
ones: () => an(t),
rate: this.dropout,
training: s,
count: 4,
dropoutFunc: this.dropoutFunc
})), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = xs({
ones: () => an(o),
rate: this.recurrentDropout,
training: s,
count: 4,
dropoutFunc: this.dropoutFunc
}));
const i = this.dropoutMask, a = this.recurrentDropoutMask;
let l, c, u, h;
0 < this.dropout && this.dropout < 1 && (t = R(t, i[0]));
let d = On(t, this.kernel.read());
0 < this.recurrentDropout && this.recurrentDropout < 1 && (o = R(o, a[0])), d = Y(d, On(o, this.recurrentKernel.read())), this.useBias && (d = In(d, this.bias.read()));
const [p, f, m, g] = qe(d, 4, d.rank - 1);
l = this.recurrentActivation.apply(p), c = this.recurrentActivation.apply(f), u = Y(R(c, r), R(l, this.activation.apply(m))), h = this.recurrentActivation.apply(g);
const x = R(h, this.activation.apply(u));
return [x, x, u];
});
}
getConfig() {
const t = super.getConfig(), e = {
units: this.units,
activation: ms(this.activation),
recurrentActivation: ms(this.recurrentActivation),
useBias: this.useBias,
kernelInitializer: Kt(this.kernelInitializer),
recurrentInitializer: Kt(this.recurrentInitializer),
biasInitializer: Kt(this.biasInitializer),
unitForgetBias: this.unitForgetBias,
kernelRegularizer: _t(this.kernelRegularizer),
recurrentRegularizer: _t(this.recurrentRegularizer),
biasRegularizer: _t(this.biasRegularizer),
activityRegularizer: _t(this.activityRegularizer),
kernelConstraint: ie(this.kernelConstraint),
recurrentConstraint: ie(this.recurrentConstraint),
biasConstraint: ie(this.biasConstraint),
dropout: this.dropout,
recurrentDropout: this.recurrentDropout,
implementation: this.implementation
};
return Object.assign(Object.assign({}, t), e);
}
}
tc.className = "LSTMCell";
j(tc);
class gb extends Ss {
constructor(t) {
t.implementation === 0 && console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."), t.cell = new tc(t), super(t);
}
call(t, e) {
return _(() => {
this.cell.dropoutMask != null && ($t(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && ($t(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
const s = e == null ? null : e.mask, o = e == null ? null : e.training, r = e == null ? null : e.initialState;
return super.call(t, { mask: s, training: o, initialState: r });
});
}
/** @nocollapse */
static fromConfig(t, e) {
return e.implmentation === 0 && (e.implementation = 1), new t(e);
}
}
gb.className = "LSTM";
j(gb);
class Od extends Ql {
constructor(t) {
super(t), this.cells = t.cells;
}
get stateSize() {
const t = [];
for (const e of this.cells.slice().reverse())
Array.isArray(e.stateSize) ? t.push(...e.stateSize) : t.push(e.stateSize);
return t;
}
call(t, e) {
return _(() => {
t = t;
let s = t.slice(1);
const o = [];
for (const a of this.cells.slice().reverse())
Array.isArray(a.stateSize) ? o.push(s.splice(0, a.stateSize.length)) : o.push(s.splice(0, 1));
o.reverse();
const r = [];
let i;
for (let a = 0; a < this.cells.length; ++a) {
const l = this.cells[a];
s = o[a], a === 0 ? i = [t[0]].concat(s) : i = [i[0]].concat(s), i = l.call(i, e), r.push(i.slice(1));
}
s = [];
for (const a of r.slice().reverse())
s.push(...a);
return [i[0]].concat(s);
});
}
build(t) {
tu(t) && (t = t[0]), t = t;
let e;
this.cells.forEach((s, o) => {
zs(`RNNCell_${o}`, () => {
s.build(t), Array.isArray(s.stateSize) ? e = s.stateSize[0] : e = s.stateSize, t = [t[0], e];
});
}), this.built = !0;
}
getConfig() {
const t = super.getConfig(), e = (r) => ({
className: r.getClassName(),
config: r.getConfig()
}), o = { cells: this.cells.map(e) };
return Object.assign(Object.assign({}, t), o);
}
/** @nocollapse */
static fromConfig(t, e, s = {}) {
const o = [];
for (const r of e.cells)
o.push(Kn(r, s));
return new t({ cells: o });
}
get trainableWeights() {
if (!this.trainable)
return [];
const t = [];
for (const e of this.cells)
t.push(...e.trainableWeights);
return t;
}
get nonTrainableWeights() {
const t = [];
for (const e of this.cells)
t.push(...e.nonTrainableWeights);
if (!this.trainable) {
const e = [];
for (const s of this.cells)
e.push(...s.trainableWeights);
return e.concat(t);
}
return t;
}
/**
* Retrieve the weights of a the model.
*
* @returns A flat `Array` of `tf.Tensor`s.
*/
getWeights() {
const t = [];
for (const e of this.cells)
t.push(...e.weights);
return eu(t);
}
/**
* Set the weights of the model.
*
* @param weights An `Array` of `tf.Tensor`s with shapes and types matching
* the output of `getWeights()`.
*/
setWeights(t) {
const e = [];
for (const s of this.cells) {
const o = s.weights.length, r = t.splice(o);
for (let i = 0; i < s.weights.length; ++i)
e.push([s.weights[i], r[i]]);
}
Sd(e);
}
}
Od.className = "StackedRNNCells";
j(Od);
function xs(n) {
const { ones: t, rate: e, training: s = !1, count: o = 1, dropoutFunc: r } = n, i = () => r != null ? r(t(), e) : ax(t(), e), a = () => Ai(i, t, s);
return !o || o <= 1 ? Dn(a().clone()) : Array(o).fill(void 0).map(a).map((c) => Dn(c.clone()));
}
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
var MT = globalThis && globalThis.__rest || function(n, t) {
var e = {};
for (var s in n)
Object.prototype.hasOwnProperty.call(n, s) && t.indexOf(s) < 0 && (e[s] = n[s]);
if (n != null && typeof Object.getOwnPropertySymbols == "function")
for (var o = 0, s = Object.getOwnPropertySymbols(n); o < s.length; o++)
t.indexOf(s[o]) < 0 && Object.prototype.propertyIsEnumerable.call(n, s[o]) && (e[s[o]] = n[s[o]]);
return e;
};
class xb extends Ss {
constructor(t) {
if (t.unroll)
throw new gt("Unrolling is not possible with convolutional RNNs.");
if (Array.isArray(t.cell))
throw new gt("It is not possible at the moment to stack convolutional cells.");
super(t), this.inputSpec = [new re({ ndim: 5 })];
}
call(t, e) {
return _(() => {
if (this.cell.dropoutMask != null && ($t(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && ($t(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null), e && e.constants)
throw new E("ConvRNN2D cell does not support constants");
const s = e == null ? null : e.mask, o = e == null ? null : e.training, r = e == null ? null : e.initialState;
return super.call(t, { mask: s, training: o, initialState: r });
});
}
computeOutputShape(t) {
let e = this.computeSingleOutputShape(t);
return this.returnSequences || (e = [e[0], ...e.slice(2)]), this.returnState && (e = [e, ...Array(2).fill([t[0], ...e.slice(-3)])]), e;
}
getInitialState(t) {
return _(() => {
const { stateSize: e } = this.cell, s = t.shape, o = this.computeSingleOutputShape(s), r = [o[0], ...o.slice(2)], i = he(r);
return Array.isArray(e) ? Array(e.length).fill(i) : [i];
});
}
resetStates(t, e = !1) {
_(() => {
if (!this.stateful)
throw new Sn("Cannot call resetStates() on an RNN Layer that is not stateful.");
const s = this.inputSpec[0].shape, o = this.computeSingleOutputShape(s), r = [o[0], ...o.slice(2)];
if (s[0] == null)
throw new E("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");
if (this.getStates() == null)
Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map(() => he(r)) : this.states_ = [he(r)];
else if (t == null)
$t(this.states_), this.keptStates != null && ($t(this.keptStates), this.keptStates = []), Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map(() => he(r)) : this.states_[0] = he(r);
else {
if (Array.isArray(t) || (t = [t]), t.length !== this.states_.length)
throw new E(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);
e ? this.keptStates.push(this.states_.slice()) : $t(this.states_);
for (let a = 0; a < this.states_.length; ++a) {
const l = t[a], c = r;
if (!Et(l.shape, c))
throw new E(`State ${a} is incompatible with layer ${this.name}: expected shape=${c}, received shape=${l.shape}`);
this.states_[a] = l;
}
}
this.states_ = this.states_.map((a) => Dn(a.clone()));
});
}
computeSingleOutputShape(t) {
const { dataFormat: e, filters: s, kernelSize: o, padding: r, strides: i, dilationRate: a } = this.cell, l = e === "channelsFirst", c = t[l ? 3 : 2], u = t[l ? 4 : 3], h = yn(c, o[0], r, i[0], a[0]), d = yn(u, o[1], r, i[1], a[1]);
return [
...t.slice(0, 2),
...l ? [s, h, d] : [h, d, s]
];
}
}
xb.className = "ConvRNN2D";
class _d extends tc {
constructor(t) {
const { filters: e, kernelSize: s, strides: o, padding: r, dataFormat: i, dilationRate: a } = t;
super(Object.assign(Object.assign({}, t), { units: e })), this.filters = e, de(this.filters, "filters"), this.kernelSize = ko(s, 2, "kernelSize"), this.kernelSize.forEach((l) => de(l, "kernelSize")), this.strides = ko(o || 1, 2, "strides"), this.strides.forEach((l) => de(l, "strides")), this.padding = r || "valid", Ze(this.padding), this.dataFormat = i || "channelsLast", Qt(this.dataFormat), this.dilationRate = ko(a || 1, 2, "dilationRate"), this.dilationRate.forEach((l) => de(l, "dilationRate"));
}
build(t) {
var e;
t = St(t);
const s = this.dataFormat === "channelsFirst" ? 1 : t.length - 1;
if (t[s] == null)
throw new E(`The channel dimension of the input should be defined. Found ${t[s]}`);
const o = t[s], r = 4, i = this.kernelSize.concat([o, this.filters * r]);
this.kernel = this.addWeight("kernel", i, null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint);
const a = this.kernelSize.concat([this.filters, this.filters * r]);
if (this.recurrentKernel = this.addWeight("recurrent_kernel", a, null, this.recurrentInitializer, this.recurrentRegularizer, !0, this.recurrentConstraint), this.useBias) {
let l;
if (this.unitForgetBias) {
const c = this.biasInitializer, u = this.filters;
l = new (e = class extends cn {
apply(d, p) {
const f = c.apply([u]), m = ks([u]), g = c.apply([u * 2]);
return bd([f, m, g]);
}
}, /** @nocollapse */
e.className = "CustomInit", e)();
} else
l = this.biasInitializer;
this.bias = this.addWeight("bias", [this.filters * r], null, l, this.biasRegularizer, !0, this.biasConstraint);
}
this.built = !0;
}
call(t, e) {
return _(() => {
if (t.length !== 3)
throw new E(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${t.length}.`);
const s = e.training || !1, o = t[0], r = t[1], i = t[2], a = 4;
0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = xs({
ones: () => an(o),
rate: this.dropout,
training: s,
count: a,
dropoutFunc: this.dropoutFunc
}));
const l = this.dropoutMask, c = (X, q, Z) => !q || !q[Z] ? X : R(q[Z], X);
let u = c(o, l, 0), h = c(o, l, 1), d = c(o, l, 2), p = c(o, l, 3);
0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = xs({
ones: () => an(r),
rate: this.recurrentDropout,
training: s,
count: a,
dropoutFunc: this.dropoutFunc
}));
const f = this.recurrentDropoutMask;
let m = c(r, f, 0), g = c(r, f, 1), x = c(r, f, 2), b = c(r, f, 3);
const w = 3, [y, C, $, k] = qe(this.kernel.read(), a, w), [v, S, T, F] = this.useBias ? qe(this.bias.read(), a) : [null, null, null, null];
u = this.inputConv(u, y, v, this.padding), h = this.inputConv(h, C, S, this.padding), d = this.inputConv(d, $, T, this.padding), p = this.inputConv(p, k, F, this.padding);
const [L, M, B, z] = qe(this.recurrentKernel.read(), a, w);
m = this.recurrentConv(m, L), g = this.recurrentConv(g, M), x = this.recurrentConv(x, B), b = this.recurrentConv(b, z);
const V = this.recurrentActivation.apply(Y(u, m)), H = this.recurrentActivation.apply(Y(h, g)), U = Y(R(H, i), R(V, this.activation.apply(Y(d, x)))), K = R(this.recurrentActivation.apply(Y(p, b)), this.activation.apply(U));
return [K, K, U];
});
}
getConfig() {
const t = super.getConfig(), e = MT(t, ["units"]), s = {
filters: this.filters,
kernelSize: this.kernelSize,
padding: this.padding,
dataFormat: this.dataFormat,
dilationRate: this.dilationRate,
strides: this.strides
};
return Object.assign(Object.assign({}, e), s);
}
inputConv(t, e, s, o) {
const r = js(t, e, this.strides, o || "valid", this.dataFormat === "channelsFirst" ? "NCHW" : "NHWC", this.dilationRate);
return s ? In(r, s, this.dataFormat) : r;
}
recurrentConv(t, e) {
return js(t, e, 1, "same", this.dataFormat === "channelsFirst" ? "NCHW" : "NHWC");
}
}
_d.className = "ConvLSTM2DCell";
j(_d);
class bb extends xb {
constructor(t) {
const e = new _d(t);
super(Object.assign(Object.assign({}, t), { cell: e }));
}
/** @nocollapse */
static fromConfig(t, e) {
return new t(e);
}
}
bb.className = "ConvLSTM2D";
j(bb);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class Ld extends Ct {
constructor(t) {
super(t), this.rate = Math.max(Math.min(t.rate, 1), 0), this.noiseShape = t.noiseShape, this.seed = t.seed, this.supportsMasking = !0;
}
getNoiseShape(t) {
if (this.noiseShape == null)
return this.noiseShape;
const e = t.shape, s = [];
for (let o = 0; o < this.noiseShape.length; ++o)
s.push(this.noiseShape[o] == null ? e[o] : this.noiseShape[o]);
return s;
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
const s = ft(t);
if (0 < this.rate && this.rate < 1) {
const o = e.training == null ? !1 : e.training, r = this.getNoiseShape(s);
return Ai(() => ax(s, this.rate, r, this.seed), () => s, o);
}
return t;
});
}
getConfig() {
const t = {
rate: this.rate,
noiseShape: this.noiseShape,
seed: this.seed
}, e = super.getConfig();
return Object.assign(t, e), t;
}
dispose() {
return super.dispose();
}
}
Ld.className = "Dropout";
j(Ld);
class yb extends Ld {
constructor(t) {
super(t), this.inputSpec = [{ ndim: 3 }];
}
getNoiseShape(t) {
const e = t.shape;
return [e[0], 1, e[2]];
}
}
yb.className = "SpatialDropout1D";
j(yb);
class wb extends Ct {
constructor(t) {
if (super(t), this.activation = null, this.useBias = !0, this.kernel = null, this.bias = null, this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_BIAS_INITIALIZER = "zeros", t.batchInputShape == null && t.inputShape == null && t.inputDim != null) {
let e = null;
t.batchSize != null && (e = t.batchSize), this.batchInputShape = [e, t.inputDim];
}
this.units = t.units, de(this.units, "units"), this.activation = gs(t.activation), t.useBias != null && (this.useBias = t.useBias), this.kernelInitializer = Ut(t.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.biasInitializer = Ut(t.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelConstraint = ae(t.kernelConstraint), this.biasConstraint = ae(t.biasConstraint), this.kernelRegularizer = Gt(t.kernelRegularizer), this.biasRegularizer = Gt(t.biasRegularizer), this.activityRegularizer = Gt(t.activityRegularizer), this.supportsMasking = !0, this.inputSpec = [{ minNDim: 2 }];
}
build(t) {
t = St(t);
const e = t[t.length - 1];
this.kernel == null && (this.kernel = this.addWeight("kernel", [e, this.units], null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint))), this.inputSpec = [{ minNDim: 2, axes: { [-1]: e } }], this.built = !0;
}
computeOutputShape(t) {
t = St(t);
const e = t.slice();
return e[e.length - 1] = this.units, e;
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
const s = ft(t), o = tx(this.activation.getClassName());
let r;
return o != null ? r = On(s, this.kernel.read(), o, this.bias ? this.bias.read() : null) : (r = On(s, this.kernel.read()), this.bias != null && (r = In(r, this.bias.read())), this.activation != null && (r = this.activation.apply(r))), r;
});
}
getConfig() {
const t = {
units: this.units,
activation: ms(this.activation),
useBias: this.useBias,
kernelInitializer: Kt(this.kernelInitializer),
biasInitializer: Kt(this.biasInitializer),
kernelRegularizer: _t(this.kernelRegularizer),
biasRegularizer: _t(this.biasRegularizer),
activityRegularizer: _t(this.activityRegularizer),
kernelConstraint: ie(this.kernelConstraint),
biasConstraint: ie(this.biasConstraint)
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
wb.className = "Dense";
j(wb);
class Cb extends Ct {
constructor(t) {
t = t || {}, super(t), this.inputSpec = [{ minNDim: 3 }], this.dataFormat = t.dataFormat;
}
computeOutputShape(t) {
t = St(t);
for (const e of t.slice(1))
if (e == null)
throw new E(`The shape of the input to "Flatten" is not fully defined (got ${t.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);
return [t[0], ds(t, 1)];
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
let s = ft(t);
if (this.dataFormat === "channelsFirst" && s.rank > 1) {
const o = [0];
for (let r = 2; r < s.rank; ++r)
o.push(r);
o.push(1), s = It(s, o);
}
return x2(s);
});
}
getConfig() {
const t = {};
this.dataFormat != null && (t.dataFormat = this.dataFormat);
const e = super.getConfig();
return Object.assign(t, e), t;
}
}
Cb.className = "Flatten";
j(Cb);
class $b extends Ct {
constructor(t) {
super(t), this.supportsMasking = !0, this.activation = gs(t.activation);
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
const s = ft(t);
return this.activation.apply(s);
});
}
getConfig() {
const t = { activation: ms(this.activation) }, e = super.getConfig();
return Object.assign(t, e), t;
}
}
$b.className = "Activation";
j($b);
class Ib extends Ct {
constructor(t) {
super(t), this.n = t.n, this.inputSpec = [{ ndim: 2 }];
}
computeOutputShape(t) {
return [t[0], this.n, t[1]];
}
call(t, e) {
return _(() => (t = ft(t), m2(t, this.n)));
}
getConfig() {
const t = {
n: this.n
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
Ib.className = "RepeatVector";
j(Ib);
class kb extends Ct {
constructor(t) {
super(t), this.targetShape = t.targetShape;
for (let e = 0; e < this.targetShape.length; ++e)
this.isUnknown(this.targetShape[e]) && (this.targetShape[e] = null);
}
isUnknown(t) {
return t < 0 || t == null;
}
/**
* Finds and replaces a missing dimension in output shape.
*
* This is a near direct port of the internal Numpy function
* `_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c`.
*
* @param inputShape: Original shape of array begin reshape.
* @param outputShape: Target shape of the array, with at most a single
* `null` or negative number, which indicates an underdetermined dimension
* that should be derived from `inputShape` and the known dimensions of
* `outputShape`.
* @returns: The output shape with `null` replaced with its computed value.
* @throws: ValueError: If `inputShape` and `outputShape` do not match.
*/
fixUnknownDimension(t, e) {
const s = "Total size of new array must be unchanged.", o = e.slice();
let r = 1, i = null;
for (let l = 0; l < o.length; ++l) {
const c = o[l];
if (this.isUnknown(c))
if (i === null)
i = l;
else
throw new E("Can only specifiy one unknown dimension.");
else
r *= c;
}
const a = ds(t);
if (i !== null) {
if (r === 0 || a % r !== 0)
throw new E(s);
o[i] = a / r;
} else if (a !== r)
throw new E(s);
return o;
}
computeOutputShape(t) {
let e = !1;
for (let s = 0; s < t.length; ++s)
if (this.isUnknown(t[s])) {
e = !0;
break;
}
return e ? t.slice(0, 1).concat(this.targetShape) : t.slice(0, 1).concat(this.fixUnknownDimension(t.slice(1), this.targetShape));
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
const s = ft(t), o = s.shape, r = o.slice(0, 1).concat(this.fixUnknownDimension(o.slice(1), this.targetShape));
return A(s, r);
});
}
getConfig() {
const t = {
targetShape: this.targetShape
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
kb.className = "Reshape";
j(kb);
class vb extends Ct {
constructor(t) {
if (super(t), t.dims == null)
throw new Error("Required configuration field `dims` is missing during Permute constructor call.");
if (!Array.isArray(t.dims))
throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${t.dims} instead.`);
const e = wn(1, t.dims.length + 1);
if (!Et(t.dims.slice().sort(), e))
throw new Error("Invalid permutation `dims`: " + JSON.stringify(t.dims) + " `dims` must contain consecutive integers starting from 1.");
this.dims = t.dims, this.dimsIncludingBatch = [0].concat(this.dims), this.inputSpec = [new re({ ndim: this.dims.length + 1 })];
}
computeOutputShape(t) {
t = St(t);
const e = t.slice();
return this.dims.forEach((s, o) => {
e[o + 1] = t[s];
}), e;
}
call(t, e) {
return It(ft(t), this.dimsIncludingBatch);
}
getConfig() {
const t = {
dims: this.dims
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
vb.className = "Permute";
j(vb);
class Sb extends Ct {
constructor(t) {
super(t ?? {}), this.supportsMasking = !0, t != null ? this.maskValue = t.maskValue == null ? 0 : t.maskValue : this.maskValue = 0;
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = super.getConfig(), e = { maskValue: this.maskValue };
return Object.assign(e, t), e;
}
computeMask(t, e) {
const s = ft(t), o = -1;
return Hc(da(s, this.maskValue), o);
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
const s = ft(t), o = -1, r = !0, i = Hc(da(s, this.maskValue), o, r);
return R(s, st(i, s.dtype));
});
}
}
Sb.className = "Masking";
j(Sb);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class Nb extends Ct {
constructor(t) {
if (super(t), this.embeddings = null, this.DEFAULT_EMBEDDINGS_INITIALIZER = "randomUniform", t.batchInputShape == null && t.inputShape == null) {
let e = null;
t.batchSize != null && (e = t.batchSize), t.inputLength == null ? this.batchInputShape = [e, null] : this.batchInputShape = [e].concat(Dt(t.inputLength));
}
this.inputDim = t.inputDim, de(this.inputDim, "inputDim"), this.outputDim = t.outputDim, de(this.outputDim, "outputDim"), this.embeddingsInitializer = Ut(t.embeddingsInitializer || this.DEFAULT_EMBEDDINGS_INITIALIZER), this.embeddingsRegularizer = Gt(t.embeddingsRegularizer), this.activityRegularizer = Gt(t.activityRegularizer), this.embeddingsConstraint = ae(t.embeddingsConstraint), this.maskZero = t.maskZero, this.supportsMasking = t.maskZero, this.inputLength = t.inputLength;
}
build(t) {
this.embeddings = this.addWeight("embeddings", [this.inputDim, this.outputDim], this.dtype, this.embeddingsInitializer, this.embeddingsRegularizer, !0, this.embeddingsConstraint), this.built = !0;
}
// Override warnOnIncompatibleInputShape because an embedding layer allows
// the input to have varying ranks.
warnOnIncompatibleInputShape(t) {
}
computeMask(t, e) {
return _(() => this.maskZero ? (t = ft(t), da(t, kt(t))) : null);
}
computeOutputShape(t) {
if (t = St(t), this.inputLength == null)
return [...t, this.outputDim];
const e = Dt(this.inputLength);
if (e.length !== t.length - 1)
throw new E(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);
{
let s = 0;
for (let o = 0; o < e.length; ++o) {
const r = e[o], i = t[o + 1];
if (r != null && i != null && r !== i)
throw new E(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);
r == null && (e[s] = i), s++;
}
}
return [t[0], ...e, this.outputDim];
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
let s = ft(t);
s.dtype !== "int32" && (s = Fn(s, "int32"));
const o = ix(this.embeddings.read(), A(s, [s.size]));
return A(o, St(this.computeOutputShape(s.shape)));
});
}
getConfig() {
const t = {
inputDim: this.inputDim,
outputDim: this.outputDim,
embeddingsInitializer: Kt(this.embeddingsInitializer),
embeddingsRegularizer: _t(this.embeddingsRegularizer),
activityRegularizer: _t(this.activityRegularizer),
embeddingsConstraint: ie(this.embeddingsConstraint),
maskZero: this.maskZero,
inputLength: this.inputLength
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
Nb.className = "Embedding";
j(Nb);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class lo extends Ct {
constructor(t) {
super(t || {}), this.supportsMasking = !0;
}
/**
* Logic for merging multiple tensors, to be overridden by subclasses.
* @param inputs
*/
mergeFunction(t) {
throw new gt();
}
/**
* Computes the shape of the result of an elementwise operation.
*
* @param shape1: Shape of the first tensor.
* @param shape2: Shape of the second tensor.
* @returns Expected output shape when an elementwise operation is carried
* out on 2 tensors with shapes `shape1` and `shape2`.
* @throws ValueError: If `shape1` and `shape2` are not compatible for
* element-wise operations.
*/
computeElementwiseOpOutputShape(t, e) {
if (t == null || e == null)
return null;
if (t.length < e.length)
return this.computeElementwiseOpOutputShape(e, t);
if (e.length === 0)
return t;
const s = t.slice(0, t.length - e.length);
for (let o = 0; o < e.length; ++o) {
const r = t[t.length - e.length + o], i = e[o];
if (r == null || i == null || r < 0 || i < 0)
s.push(null);
else if (r === 1)
s.push(i);
else if (i === 1)
s.push(r);
else {
if (r !== i)
throw new E("Operands could not be broadcast together with shapes " + JSON.stringify(t) + " " + JSON.stringify(e));
s.push(r);
}
}
return s;
}
build(t) {
if (Array.isArray(t) && !Array.isArray(t[0]) && (t = [St(t)]), t = t, t.length < 2)
throw new E(`A merge layer should be called on an Array of at least 2 inputs. Got ${t.length} input(s).`);
let e = [];
for (const r of t)
r != null && r[0] !== null && e.push(r[0]);
if (e = hs(e), e.length > 1)
throw new E(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(t)}.`);
let s = t[0] == null ? null : t[0].slice(1);
for (let r = 1; r < t.length; ++r) {
const i = t[r] == null ? null : t[r].slice(1);
s = this.computeElementwiseOpOutputShape(s, i);
}
const o = t.map((r) => r.length);
t.indexOf(null) === -1 && hs(o).length === 1 ? this.reshapeRequired = !1 : this.reshapeRequired = !0;
}
call(t, e) {
return _(() => {
if (t = t, this.reshapeRequired) {
const s = [], o = t.map((r) => r.rank);
if (o.indexOf(null) === -1) {
const r = fs(o);
for (let i of t) {
const a = i.rank;
for (let l = 0; l < r - a; ++l)
i = Ri(i, 1);
s.push(i);
}
return this.mergeFunction(s);
} else {
let r = !1;
for (const l of t) {
const c = l.rank;
if (c == null) {
const u = l.shape, h = u[0], d = u.slice(1).concat([h]);
let p = A(l, [h].concat(ds(u.slice(1))));
p = It(p, [1, 0]), p = A(p, d), s.push(p), r = !0;
} else if (c > 1) {
const u = wn(1, c).concat([0]);
s.push(It(l, u)), r = !0;
} else
s.push(l);
}
let i = this.mergeFunction(s);
const a = i.rank;
if (r) {
if (a == null) {
const l = i.shape, c = l.length, u = l[c - 1], h = [u].concat(l.slice(0, l.length - 1));
i = A(It(A(i, [-1, u]), [1, 0]), h);
} else if (a > 1) {
const l = [a - 1].concat(wn(0, a - 1));
i = It(i, l);
}
}
return i;
}
} else
return this.mergeFunction(t);
});
}
computeOutputShape(t) {
t = t;
let e;
t[0] == null ? e = null : e = t[0].slice(1);
for (let o = 1; o < t.length; ++o) {
const r = t[o] == null ? null : t[o].slice(1);
e = this.computeElementwiseOpOutputShape(e, r);
}
let s = [];
for (const o of t)
o != null && o[0] !== null && s.push(o[0]);
return s = hs(s), s.length === 1 ? e = s.concat(e) : e = [null].concat(e), e;
}
computeMask(t, e) {
return _(() => {
if (e == null)
return null;
if (!Array.isArray(e))
throw new E("`mask` should be an Array");
if (!Array.isArray(t))
throw new E("`inputs` should be an Array");
if (e.length !== t.length)
throw new E(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${t.length} vs ${e.length})`);
if (e.every((o) => o == null))
return null;
e = e.map((o) => o == null ? o : Oe(o, 0));
let s = e[0];
for (let o = 1; o < e.length - 1; ++o)
s = jn(s, e[o]);
return s;
});
}
}
class Tb extends lo {
constructor(t) {
super(t);
}
mergeFunction(t) {
return _(() => {
let e = t[0].clone();
for (let s = 1; s < t.length; ++s)
e = Y(e, t[s]);
return e;
});
}
}
Tb.className = "Add";
j(Tb);
class Eb extends lo {
constructor(t) {
super(t);
}
mergeFunction(t) {
return _(() => {
let e = t[0].clone();
for (let s = 1; s < t.length; ++s)
e = R(e, t[s]);
return e;
});
}
}
Eb.className = "Multiply";
j(Eb);
class Rb extends lo {
constructor(t) {
super(t);
}
mergeFunction(t) {
return _(() => {
let e = t[0].clone();
for (let s = 1; s < t.length; ++s)
e = Y(e, t[s]);
return R(1 / t.length, e);
});
}
}
Rb.className = "Average";
j(Rb);
class Db extends lo {
constructor(t) {
super(t);
}
mergeFunction(t) {
return _(() => {
let e = t[0];
for (let s = 1; s < t.length; ++s)
e = Is(e, t[s]);
return e;
});
}
}
Db.className = "Maximum";
j(Db);
class Ab extends lo {
constructor(t) {
super(t);
}
mergeFunction(t) {
return _(() => {
let e = t[0];
for (let s = 1; s < t.length; ++s)
e = mr(e, t[s]);
return e;
});
}
}
Ab.className = "Minimum";
j(Ab);
class Fb extends lo {
constructor(t) {
super(t), this.DEFAULT_AXIS = -1, t == null && (t = {}), this.axis = t.axis == null ? this.DEFAULT_AXIS : t.axis, this.supportsMasking = !0, this.reshapeRequired = !1;
}
build(t) {
if (!(Array.isArray(t) && Array.isArray(t[0])) || t.length === 1)
throw new E("A `Concatenate` layer should be called on a list of at least 2 inputs");
t = t;
let e = !0;
for (const o of t)
if (o != null) {
e = !1;
break;
}
if (e)
return;
const s = [];
for (let o = 0; o < t.length; ++o) {
const r = t[o].slice();
r.splice(this.axis, 1);
let i = !1;
for (const a of s)
if (Et(a, r)) {
i = !0;
break;
}
i || s.push(r);
}
if (s.length > 1)
throw new E("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: " + JSON.stringify(t));
}
mergeFunction(t) {
return _(() => bd(t, this.axis));
}
computeOutputShape(t) {
if (!(Array.isArray(t) && Array.isArray(t[0])))
throw new E("A `Concatenate` layer should be called on a list of inputs.");
const e = t, s = e[0].slice(), o = this.axis < 0 ? s.length + this.axis : this.axis;
for (const r of e.slice(1)) {
if (s[o] == null || r[o] == null) {
s[o] = null;
break;
}
s[o] += r[o];
}
return s;
}
computeMask(t, e) {
if (e == null)
return null;
if (!Array.isArray(e))
throw new E("`mask` should be an array for Concatenate");
if (!Array.isArray(t))
throw new E("`inputs` should be an array for Concatenate");
if (e.length !== t.length)
throw new E(`Mismatch in the length of mask (${e.length}) and the legnth of inputs (${t.length})`);
return _(() => {
let s = !0;
if (e.forEach((i) => {
if (i != null) {
s = !1;
return;
}
}), s)
return null;
const o = [];
for (let i = 0; i < t.length; ++i)
e[i] == null ? o.push(st(an(t[i]), "bool")) : e[i].rank < t[i].rank ? o.push(Oe(e[i], -1)) : o.push(e[i]);
const r = Le(o, this.axis);
return Om(r, -1, !1);
});
}
getConfig() {
const t = {
axis: this.axis
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
Fb.className = "Concatenate";
j(Fb);
function sr(n, t) {
for (; n < 0; )
n += t;
return n;
}
function PT(n, t, e) {
if (n.shape.length > 3 || t.shape.length > 3)
throw new gt("batchDot is not implemented for tensors of 4D or higher rank yet");
if (I(n.shape.length >= 2, () => `batchDot requires the rank of x to be >= 2, but got ${n.shape.length}`), I(n.shape.length >= 2, () => `batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`), typeof e == "number" && (e = [e, e]), n.dtype === "complex64" || t.dtype === "complex64")
throw new gt("batchDot is not implemented for complex64-type Tensors yet.");
const s = n.shape.length, o = t.shape.length;
e == null && (e = [s - 1, o - 2]);
const r = e;
return _(() => {
let i;
if (s > o) {
i = s - o;
const l = [];
for (let c = 0; c < i; ++c)
l.push(1);
t = A(t, t.shape.concat(l));
} else if (o > s) {
i = o - s;
const l = [];
for (let c = 0; c < i; ++c)
l.push(1);
n = A(n, n.shape.concat(l));
} else
i = 0;
let a;
if (n.shape.length === 2 && t.shape.length === 2)
r[0] === r[1] ? a = ct(R(n, t), r[0]) : a = ct(R(It(n, [1, 0]), t), r[1]);
else {
const l = r[0] !== n.shape.length - 1, c = r[1] === t.shape.length - 1;
a = Nt(n, t, l, c);
}
if (i > 0) {
let l;
s > o ? l = s + o - 3 : l = s - 1;
const c = [];
for (let u = l; u < l + i; ++u)
c.push(u);
a = ki(a, c);
}
return a.shape.length === 1 && (a = Oe(a, 1)), a;
});
}
class Ob extends lo {
constructor(t) {
super(t), this.axes = t.axes, this.normalize = t.normalize == null ? !1 : t.normalize, this.supportsMasking = !0, this.reshapeRequired = !1;
}
build(t) {
I(Array.isArray(t) && t.length === 2 && Array.isArray(t[0]) && Array.isArray(t[1]), () => "A `Dot` layer should be called on a list of exactly 2 inputs.");
const e = t[0], s = t[1];
if (e.length > 3 || s.length > 3)
throw new gt("Dot layer does not support tensors of 4D or higher rank yet.");
const o = this.interpretAxes(e, s);
if (e[o[0]] !== s[o[1]])
throw new E(`Dimension incompatibility: ${e[o[0]]} !== ${s[o[1]]}`);
}
mergeFunction(t) {
if (t.length !== 2)
throw new E(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${t.length} input(s).`);
let e = t[0], s = t[1], o;
return Array.isArray(this.axes) ? o = this.axes.map((r, i) => sr(r, t[i].shape.length)) : o = [
sr(this.axes, e.shape.length),
sr(this.axes, s.shape.length)
], this.normalize && (e = ya(e, o[0]), s = ya(s, o[1])), PT(e, s, o);
}
interpretAxes(t, e) {
let s;
return Array.isArray(this.axes) ? s = this.axes : s = [
sr(this.axes, t.length),
sr(this.axes, e.length)
], s;
}
computeOutputShape(t) {
I(Array.isArray(t) && t.length === 2 && Array.isArray(t[0]) && Array.isArray(t[1]), () => "A `Dot` layer should be called on a list of exactly 2 inputs.");
const e = t[0].slice(), s = t[1].slice();
if (e.length > 3 || s.length > 3)
throw new gt("Dot layer does not support tensors of 4D or higher rank yet.");
const o = this.interpretAxes(e, s);
e.splice(o[0], 1), s.splice(o[1], 1), s.splice(0, 1);
const r = e.concat(s);
return r.length === 1 && r.push(1), r;
}
computeMask(t, e) {
return null;
}
getConfig() {
const t = {
axes: this.axes,
normalize: this.normalize
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
Ob.className = "Dot";
j(Ob);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class _b extends Ct {
constructor(t) {
super(t), this.supportsMasking = !0, this.stddev = t.stddev;
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = super.getConfig(), e = { stddev: this.stddev };
return Object.assign(e, t), e;
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
const s = ft(t);
return Ai(() => Y(jl(s.shape, 0, this.stddev), s), () => s, e.training || !1);
});
}
}
_b.className = "GaussianNoise";
j(_b);
class Lb extends Ct {
constructor(t) {
super(t), this.supportsMasking = !0, this.rate = t.rate;
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = super.getConfig(), e = { rate: this.rate };
return Object.assign(e, t), e;
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e);
const s = ft(t);
return this.rate > 0 && this.rate < 1 ? Ai(() => {
const r = Math.sqrt(this.rate / (1 - this.rate));
return R(s, jl(s.shape, 1, r));
}, () => s, e.training || !1) : s;
});
}
}
Lb.className = "GaussianDropout";
j(Lb);
class Mb extends Ct {
constructor(t) {
super(t), this.supportsMasking = !0, this.rate = t.rate, this.noiseShape = t.noiseShape;
}
_getNoiseShape(t) {
return this.noiseShape || ft(t).shape;
}
computeOutputShape(t) {
return t;
}
getConfig() {
const t = super.getConfig(), e = { rate: this.rate };
return Object.assign(e, t), e;
}
call(t, e) {
return _(() => {
if (this.rate < 1 && this.rate > 0) {
const s = this._getNoiseShape(t);
return Ai(() => {
const r = ft(t), i = 1.6732632423543772, a = 1.0507009873554805, l = -i * a;
let c = oo(Ii(s), this.rate);
c = Fn(c, "float32");
const u = ((1 - this.rate) * (1 + this.rate * l ** 2)) ** -0.5, h = -u * l * this.rate, d = Y(R(r, c), R(Y(c, -1), l));
return Y(R(d, u), h);
}, () => ft(t), e.training || !1);
}
return t;
});
}
}
Mb.className = "AlphaDropout";
j(Mb);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function wr(n, t, e, s, o, r = 1e-3) {
let i;
if (n.rank === 2)
i = OC(n, t, e, s, o, r);
else if (n.rank === 3)
i = LC(n, t, e, s, o, r);
else if (n.rank === 4)
i = PC(n, t, e, s, o, r);
else
throw new gt(`batchNormalization is not implemented for array of rank ${n.rank} yet`);
return i;
}
function zT(n, t, e, s, o = 1e-3) {
return _(() => {
const r = Nh(n, s), i = r.mean, a = r.variance;
return [wr(n, i, a, e, t, o), i, a];
});
}
function BT(n, t, e, s, o = 1e-3) {
return _(() => {
const r = Nh(n, s), i = r.mean, a = r.variance, l = [];
for (const f of wn(0, n.rank))
s.indexOf(f) !== -1 ? l.push(1) : l.push(n.shape[f]);
const c = A(i, l), u = A(a, l), h = t == null ? null : A(t, l), d = e == null ? null : A(e, l);
return [wr(n, c, u, d, h, o), i, a];
});
}
function VT(n, t, e, s, o = 1e-3) {
return Et(s.slice().sort(), wn(0, n.rank - 1)) ? zT(n, t, e, s, o) : BT(n, t, e, s, o);
}
class Pb extends Ct {
constructor(t) {
t == null && (t = {}), super(t), this.supportsMasking = !0, this.axis = t.axis == null ? -1 : t.axis, this.momentum = t.momentum == null ? 0.99 : t.momentum, this.epsilon = t.epsilon == null ? 1e-3 : t.epsilon, this.center = t.center == null ? !0 : t.center, this.scale = t.scale == null ? !0 : t.scale, this.betaInitializer = Ut(t.betaInitializer || "zeros"), this.gammaInitializer = Ut(t.gammaInitializer || "ones"), this.movingMeanInitializer = Ut(t.movingMeanInitializer || "zeros"), this.movingVarianceInitializer = Ut(t.movingVarianceInitializer || "ones"), this.betaConstraint = ae(t.betaConstraint), this.gammaConstraint = ae(t.gammaConstraint), this.betaRegularizer = Gt(t.betaRegularizer), this.gammaRegularizer = Gt(t.gammaRegularizer);
}
build(t) {
t = St(t);
const e = this.axis >= 0 ? this.axis : this.axis + t.length, s = t[e];
if (s == null)
throw new E(`Axis ${e} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(t)}.`);
this.inputSpec = [new re({ ndim: t.length, axes: { [e]: s } })];
const o = [s];
this.scale && (this.gamma = this.addWeight("gamma", o, null, this.gammaInitializer, this.gammaRegularizer, !0, this.gammaConstraint)), this.center && (this.beta = this.addWeight("beta", o, null, this.betaInitializer, this.betaRegularizer, !0, this.betaConstraint)), this.movingMean = this.addWeight("moving_mean", o, null, this.movingMeanInitializer, null, !1), this.movingVariance = this.addWeight("moving_variance", o, null, this.movingVarianceInitializer, null, !1), this.built = !0;
}
call(t, e) {
return _(() => {
const s = e.training == null ? !1 : e.training, o = ft(t), r = o.shape, i = r.length, a = wn(0, i), l = this.axis >= 0 ? this.axis : this.axis + i;
a.splice(l, 1);
const c = Js(1, i);
c[l] = r[l];
const u = a.slice();
u.sort();
const h = !Et(u, wn(0, i).slice(0, i - 1)), d = () => {
if (h) {
const b = A(this.movingMean.read(), c), w = A(this.movingVariance.read(), c), y = this.center ? A(this.beta.read(), c) : null, C = this.scale ? A(this.gamma.read(), c) : null;
return wr(o, b, w, y, C, this.epsilon);
} else
return wr(o, this.movingMean.read(), this.movingVariance.read(), this.beta == null ? null : this.beta.read(), this.gamma == null ? null : this.gamma.read(), this.epsilon);
};
if (!s)
return d();
const [p, f, m] = VT(o, this.gamma.read(), this.beta.read(), a, this.epsilon), g = (b, w, y) => {
_(() => {
const C = 1 - y, $ = b.read(), k = R(pt($, w), C);
b.write(pt($, k));
});
};
return (() => {
g(this.movingMean, f, this.momentum), g(this.movingVariance, m, this.momentum);
})(), p;
});
}
getConfig() {
const t = {
axis: this.axis,
momentum: this.momentum,
epsilon: this.epsilon,
center: this.center,
scale: this.scale,
betaInitializer: Kt(this.betaInitializer),
gammaInitializer: Kt(this.gammaInitializer),
movingMeanInitializer: Kt(this.movingMeanInitializer),
movingVarianceInitializer: Kt(this.movingVarianceInitializer),
betaRegularizer: _t(this.betaRegularizer),
gammaRegularizer: _t(this.gammaRegularizer),
betaConstraint: ie(this.betaConstraint),
gammaConstraint: ie(this.gammaConstraint)
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
Pb.className = "BatchNormalization";
j(Pb);
class zb extends Ct {
constructor(t) {
if (t == null && (t = {}), super(t), this.axis = t.axis == null ? -1 : t.axis, typeof this.axis == "number") {
if (!Number.isInteger(this.axis))
throw new Error(`Expected axis to be an integer, but received ${this.axis}`);
} else if (Array.isArray(this.axis)) {
for (const e of this.axis)
if (!Number.isInteger(e))
throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`);
} else
throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);
this.epsilon = t.epsilon == null ? 1e-3 : t.epsilon, this.center = t.center == null ? !0 : t.center, this.scale = t.scale == null ? !0 : t.scale, this.betaInitializer = Ut(t.betaInitializer || "zeros"), this.gammaInitializer = Ut(t.gammaInitializer || "ones"), this.betaRegularizer = Gt(t.betaRegularizer), this.gammaRegularizer = Gt(t.gammaRegularizer), this.supportsMasking = !0;
}
build(t) {
t = St(t);
const e = t.length;
typeof this.axis == "number" && (this.axis = [this.axis]);
for (let r = 0; r < this.axis.length; ++r)
this.axis[r] < 0 && (this.axis[r] += e);
for (const r of this.axis)
if (r < 0 || r >= e)
throw new Error(`Invalid axis: ${r}`);
if (this.axis.length !== hs(this.axis).length)
throw new Error(`Found duplicate axes in: ${this.axis}`);
const s = this.axis.map((r) => t[r]), o = !0;
this.scale ? this.gamma = this.addWeight("gamma", s, "float32", this.gammaInitializer, this.gammaRegularizer, o) : this.gamma = null, this.center ? this.beta = this.addWeight("beta", s, "float32", this.betaInitializer, this.betaRegularizer, o) : this.beta = null, this.built = !0;
}
call(t, e) {
const s = ft(t), o = s.shape, r = o.length;
return _(() => {
let { mean: a, variance: l } = Nh(s, this.axis, !0);
const c = Js(1, r);
for (const m of this.axis)
c[m] = o[m];
const u = (m) => m != null && m.shape.length !== r ? A(m, c) : m;
let h = this.scale ? u(this.gamma.read()) : null, d = this.center ? u(this.beta.read()) : null;
const p = [], f = [];
for (let m = 0; m < r; ++m)
this.axis.indexOf(m) !== -1 ? (p.push(o[m]), f.push(1)) : (p.push(1), f.push(o[m]));
return a = gn(a, p), l = gn(l, p), h != null && (h = gn(h, f)), d != null && (d = gn(d, f)), wr(s, a, l, d, h, this.epsilon);
});
}
getConfig() {
const t = {
axis: this.axis,
epsilon: this.epsilon,
center: this.center,
scale: this.scale,
betaInitializer: Kt(this.betaInitializer),
gammaInitializer: Kt(this.gammaInitializer),
betaRegularizer: _t(this.betaRegularizer),
gammaRegularizer: _t(this.gammaRegularizer)
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
zb.className = "LayerNormalization";
j(zb);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function WT(n, t, e) {
return _(() => {
if (n.rank !== 4)
throw new E(`temporalPadding expects input tensor to be 4-D, but received a ${n.rank}-D tensor.`);
if (t == null && (t = [[1, 1], [1, 1]]), t.length !== 2 || t[0].length !== 2 || t[1].length !== 2)
throw new E("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");
if (e == null && (e = Cn()), e !== "channelsLast" && e !== "channelsFirst")
throw new E(`Unknown data format: ${e}. Supported data formats are 'channelsLast' and 'channelsFirst.`);
let s;
return e === "channelsFirst" ? s = [[0, 0], [0, 0], t[0], t[1]] : s = [[0, 0], t[0], t[1], [0, 0]], Th(n, s);
});
}
class Bb extends Ct {
constructor(t) {
if (t == null && (t = {}), super(t), this.dataFormat = t.dataFormat == null ? Cn() : t.dataFormat, t.padding == null)
this.padding = [[1, 1], [1, 1]];
else if (typeof t.padding == "number")
this.padding = [[t.padding, t.padding], [t.padding, t.padding]];
else {
if (t.padding = t.padding, t.padding.length !== 2)
throw new E(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${t.padding.length} array.`);
let e, s;
if (typeof t.padding[0] == "number")
e = [t.padding[0], t.padding[0]], s = [t.padding[1], t.padding[1]];
else {
if (t.padding = t.padding, t.padding[0].length !== 2)
throw new E(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${t.padding[0].length} array.`);
if (e = t.padding[0], t.padding[1].length !== 2)
throw new E(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${t.padding[1].length} array.`);
s = t.padding[1];
}
this.padding = [e, s];
}
this.inputSpec = [new re({ ndim: 4 })];
}
computeOutputShape(t) {
t = St(t);
let e, s;
return this.dataFormat === "channelsFirst" ? (t[2] != null && t[2] >= 0 ? e = t[2] + this.padding[0][0] + this.padding[0][1] : e = null, t[3] != null && t[3] >= 0 ? s = t[3] + this.padding[1][0] + this.padding[1][1] : s = null, [t[0], t[1], e, s]) : (t[1] != null && t[1] >= 0 ? e = t[1] + this.padding[0][0] + this.padding[0][1] : e = null, t[2] != null && t[2] >= 0 ? s = t[2] + this.padding[1][0] + this.padding[1][1] : s = null, [t[0], e, s, t[3]]);
}
call(t, e) {
return _(() => WT(ft(t), this.padding, this.dataFormat));
}
getConfig() {
const t = {
padding: this.padding,
dataFormat: this.dataFormat
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
Bb.className = "ZeroPadding2D";
j(Bb);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function ec(n, t, e, s, o, r) {
return _(() => {
Qt(o), nx(r), Ze(s), e == null && (e = [1, 1]), s == null && (s = "valid"), o == null && (o = Cn()), r == null && (r = "max"), n = Dd(n, o);
let i;
const a = s === "same" ? "same" : "valid";
return r === "max" ? i = Sh(n, t, e, a) : i = gh(
// TODO(cais): Rank check?
n,
t,
e,
a
), o === "channelsFirst" && (i = It(i, [0, 3, 1, 2])), i;
});
}
function Vb(n, t, e, s, o, r) {
return _(() => {
Qt(o), nx(r), Ze(s), e == null && (e = [1, 1, 1]), s == null && (s = "valid"), o == null && (o = Cn()), r == null && (r = "max"), n = ob(n, o);
let i;
const a = s === "same" ? "same" : "valid";
return r === "max" ? i = $I(n, t, e, a) : i = kC(n, t, e, a), o === "channelsFirst" && (i = It(i, [0, 4, 1, 2, 3])), i;
});
}
class Wb extends Ct {
/**
*
* @param args Parameters for the Pooling layer.
*
* config.poolSize defaults to 2.
*/
constructor(t) {
if (t.poolSize == null && (t.poolSize = 2), super(t), typeof t.poolSize == "number")
this.poolSize = [t.poolSize];
else if (Array.isArray(t.poolSize) && t.poolSize.length === 1 && typeof t.poolSize[0] == "number")
this.poolSize = t.poolSize;
else
throw new E(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.poolSize)}`);
if (de(this.poolSize, "poolSize"), t.strides == null)
this.strides = this.poolSize;
else if (typeof t.strides == "number")
this.strides = [t.strides];
else if (Array.isArray(t.strides) && t.strides.length === 1 && typeof t.strides[0] == "number")
this.strides = t.strides;
else
throw new E(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.strides)}`);
de(this.strides, "strides"), this.padding = t.padding == null ? "valid" : t.padding, Ze(this.padding), this.inputSpec = [new re({ ndim: 3 })];
}
computeOutputShape(t) {
t = St(t);
const e = yn(t[1], this.poolSize[0], this.padding, this.strides[0]);
return [t[0], e, t[2]];
}
call(t, e) {
return _(() => {
this.invokeCallHook(t, e), t = Ri(ft(t), 2);
const s = this.poolingFunction(ft(t), [this.poolSize[0], 1], [this.strides[0], 1], this.padding, "channelsLast");
return ki(s, [2]);
});
}
getConfig() {
const t = {
poolSize: this.poolSize,
padding: this.padding,
strides: this.strides
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
class Ub extends Wb {
constructor(t) {
super(t);
}
poolingFunction(t, e, s, o, r) {
return Qt(r), Ze(o), ec(t, e, s, o, r, "max");
}
}
Ub.className = "MaxPooling1D";
j(Ub);
class Gb extends Wb {
constructor(t) {
super(t);
}
poolingFunction(t, e, s, o, r) {
return Qt(r), Ze(o), ec(t, e, s, o, r, "avg");
}
}
Gb.className = "AveragePooling1D";
j(Gb);
class Hb extends Ct {
constructor(t) {
if (t.poolSize == null && (t.poolSize = [2, 2]), super(t), this.poolSize = Array.isArray(t.poolSize) ? t.poolSize : [t.poolSize, t.poolSize], t.strides == null)
this.strides = this.poolSize;
else if (Array.isArray(t.strides)) {
if (t.strides.length !== 2)
throw new E(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${t.strides.length}.`);
this.strides = t.strides;
} else
this.strides = [t.strides, t.strides];
de(this.poolSize, "poolSize"), de(this.strides, "strides"), this.padding = t.padding == null ? "valid" : t.padding, this.dataFormat = t.dataFormat == null ? "channelsLast" : t.dataFormat, Qt(this.dataFormat), Ze(this.padding), this.inputSpec = [new re({ ndim: 4 })];
}
computeOutputShape(t) {
t = St(t);
let e = this.dataFormat === "channelsFirst" ? t[2] : t[1], s = this.dataFormat === "channelsFirst" ? t[3] : t[2];
return e = yn(e, this.poolSize[0], this.padding, this.strides[0]), s = yn(s, this.poolSize[1], this.padding, this.strides[1]), this.dataFormat === "channelsFirst" ? [t[0], t[1], e, s] : [t[0], e, s, t[3]];
}
call(t, e) {
return _(() => (this.invokeCallHook(t, e), this.poolingFunction(ft(t), this.poolSize, this.strides, this.padding, this.dataFormat)));
}
getConfig() {
const t = {
poolSize: this.poolSize,
padding: this.padding,
strides: this.strides,
dataFormat: this.dataFormat
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
class Kb extends Hb {
constructor(t) {
super(t);
}
poolingFunction(t, e, s, o, r) {
return Qt(r), Ze(o), ec(t, e, s, o, r, "max");
}
}
Kb.className = "MaxPooling2D";
j(Kb);
class jb extends Hb {
constructor(t) {
super(t);
}
poolingFunction(t, e, s, o, r) {
return Qt(r), Ze(o), ec(t, e, s, o, r, "avg");
}
}
jb.className = "AveragePooling2D";
j(jb);
class Xb extends Ct {
constructor(t) {
if (t.poolSize == null && (t.poolSize = [2, 2, 2]), super(t), this.poolSize = Array.isArray(t.poolSize) ? t.poolSize : [t.poolSize, t.poolSize, t.poolSize], t.strides == null)
this.strides = this.poolSize;
else if (Array.isArray(t.strides)) {
if (t.strides.length !== 3)
throw new E(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${t.strides.length}.`);
this.strides = t.strides;
} else
this.strides = [t.strides, t.strides, t.strides];
de(this.poolSize, "poolSize"), de(this.strides, "strides"), this.padding = t.padding == null ? "valid" : t.padding, this.dataFormat = t.dataFormat == null ? "channelsLast" : t.dataFormat, Qt(this.dataFormat), Ze(this.padding), this.inputSpec = [new re({ ndim: 5 })];
}
computeOutputShape(t) {
t = St(t);
let e = this.dataFormat === "channelsFirst" ? t[2] : t[1], s = this.dataFormat === "channelsFirst" ? t[3] : t[2], o = this.dataFormat === "channelsFirst" ? t[4] : t[3];
return e = yn(e, this.poolSize[0], this.padding, this.strides[0]), s = yn(s, this.poolSize[1], this.padding, this.strides[1]), o = yn(o, this.poolSize[2], this.padding, this.strides[2]), this.dataFormat === "channelsFirst" ? [t[0], t[1], e, s, o] : [t[0], e, s, o, t[4]];
}
call(t, e) {
return _(() => (this.invokeCallHook(t, e), this.poolingFunction(ft(t), this.poolSize, this.strides, this.padding, this.dataFormat)));
}
getConfig() {
const t = {
poolSize: this.poolSize,
padding: this.padding,
strides: this.strides,
dataFormat: this.dataFormat
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
class qb extends Xb {
constructor(t) {
super(t);
}
poolingFunction(t, e, s, o, r) {
return Qt(r), Ze(o), Vb(t, e, s, o, r, "max");
}
}
qb.className = "MaxPooling3D";
j(qb);
class Yb extends Xb {
constructor(t) {
super(t);
}
poolingFunction(t, e, s, o, r) {
return Qt(r), Ze(o), Vb(t, e, s, o, r, "avg");
}
}
Yb.className = "AveragePooling3D";
j(Yb);
class Jb extends Ct {
constructor(t) {
super(t), this.inputSpec = [new re({ ndim: 3 })];
}
computeOutputShape(t) {
return [t[0], t[2]];
}
call(t, e) {
throw new gt();
}
}
class Zb extends Jb {
constructor(t) {
super(t || {});
}
call(t, e) {
return _(() => {
const s = ft(t);
return ee(s, 1);
});
}
}
Zb.className = "GlobalAveragePooling1D";
j(Zb);
class Qb extends Jb {
constructor(t) {
super(t || {});
}
call(t, e) {
return _(() => {
const s = ft(t);
return bn(s, 1);
});
}
}
Qb.className = "GlobalMaxPooling1D";
j(Qb);
class t0 extends Ct {
constructor(t) {
super(t), this.dataFormat = t.dataFormat == null ? "channelsLast" : t.dataFormat, Qt(this.dataFormat), this.inputSpec = [new re({ ndim: 4 })];
}
computeOutputShape(t) {
return t = t, this.dataFormat === "channelsLast" ? [t[0], t[3]] : [t[0], t[1]];
}
call(t, e) {
throw new gt();
}
getConfig() {
const t = { dataFormat: this.dataFormat }, e = super.getConfig();
return Object.assign(t, e), t;
}
}
class e0 extends t0 {
call(t, e) {
return _(() => {
const s = ft(t);
return this.dataFormat === "channelsLast" ? ee(s, [1, 2]) : ee(s, [2, 3]);
});
}
}
e0.className = "GlobalAveragePooling2D";
j(e0);
class n0 extends t0 {
call(t, e) {
return _(() => {
const s = ft(t);
return this.dataFormat === "channelsLast" ? bn(s, [1, 2]) : bn(s, [2, 3]);
});
}
}
n0.className = "GlobalMaxPooling2D";
j(n0);
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class s0 extends Ct {
constructor(t) {
super(t), this.layer = t.layer;
}
build(t) {
this.built = !0;
}
// TODO(cais): Implement activityRegularizer getter.
get trainable() {
return this.layer != null ? this.layer.trainable : !1;
}
set trainable(t) {
this.layer != null && (this.layer.trainable = t);
}
get trainableWeights() {
return this.layer.trainableWeights;
}
// TODO(cais): Implement setter for trainableWeights.
get nonTrainableWeights() {
return this.layer.nonTrainableWeights;
}
// TODO(cais): Implement setter for nonTrainableWeights.
get updates() {
return this.layer._updates;
}
// TODO(cais): Implement getUpdatesFor().
get losses() {
return this.layer.losses;
}
// TODO(cais): Implement getLossesFor().
getWeights() {
return this.layer.getWeights();
}
setWeights(t) {
this.layer.setWeights(t);
}
getConfig() {
const t = {
layer: {
className: this.layer.getClassName(),
config: this.layer.getConfig()
}
}, e = super.getConfig();
return Object.assign(t, e), t;
}
setFastWeightInitDuringBuild(t) {
super.setFastWeightInitDuringBuild(t), this.layer != null && this.layer.setFastWeightInitDuringBuild(t);
}
/** @nocollapse */
static fromConfig(t, e, s = {}) {
const o = e.layer, r = Kn(o, s);
delete e.layer;
const i = { layer: r };
return Object.assign(i, e), new t(i);
}
}
class o0 extends s0 {
constructor(t) {
super(t), this.supportsMasking = !0;
}
build(t) {
if (t = St(t), t.length < 3)
throw new E(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(t)}`);
this.inputSpec = [{ shape: t }];
const e = [t[0]].concat(t.slice(2));
this.layer.built || (this.layer.build(e), this.layer.built = !0), super.build(t);
}
computeOutputShape(t) {
t = St(t);
const e = [t[0]].concat(t.slice(2)), s = this.layer.computeOutputShape(e), o = t[1];
return [s[0], o].concat(s.slice(1));
}
call(t, e) {
return _(() => (t = ft(t), pb(
(i, a) => [ft(this.layer.call(i, e)), []],
t,
[],
!1,
null,
null,
!1,
!0
/* needPerStepOutputs */
)[1]));
}
}
o0.className = "TimeDistributed";
j(o0);
function UT(n) {
ao(u2, "BidirectionalMergeMode", n);
}
const GT = "concat";
class r0 extends s0 {
constructor(t) {
super(t);
const e = t.layer.getConfig(), s = {};
s.className = t.layer.getClassName(), s.config = e, this.forwardLayer = Kn(s), e.goBackwards = e.goBackwards !== !0;
const o = {};
if (o.className = t.layer.getClassName(), o.config = e, this.backwardLayer = Kn(o), this.forwardLayer.name = "forward_" + this.forwardLayer.name, this.backwardLayer.name = "backward_" + this.backwardLayer.name, this.mergeMode = t.mergeMode === void 0 ? GT : t.mergeMode, UT(this.mergeMode), t.weights)
throw new gt("weights support is not implemented for Bidirectional layer yet.");
this._stateful = t.layer.stateful, this.returnSequences = t.layer.returnSequences, this.returnState = t.layer.returnState, this.supportsMasking = !0, this._trainable = !0, this.inputSpec = t.layer.inputSpec, this.numConstants = null;
}
get trainable() {
return this._trainable;
}
set trainable(t) {
this._trainable = t, this.forwardLayer != null && (this.forwardLayer.trainable = t), this.backwardLayer != null && (this.backwardLayer.trainable = t);
}
getWeights() {
return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights());
}
setWeights(t) {
const e = t.length, s = Math.floor(e / 2);
this.forwardLayer.setWeights(t.slice(0, s)), this.backwardLayer.setWeights(t.slice(s));
}
computeOutputShape(t) {
let e = this.forwardLayer.computeOutputShape(t);
Array.isArray(e) && Array.isArray(e[0]) || (e = [e]), e = e;
let s, o, r;
return this.returnState && (r = e.slice(1)), s = e[0], s = s, this.mergeMode === "concat" ? (s[s.length - 1] *= 2, o = [s]) : this.mergeMode == null ? o = [s, s.slice()] : o = [s], this.returnState ? this.mergeMode == null ? o.concat(r).concat(r.slice()) : [s].concat(r).concat(r.slice()) : _e(o);
}
apply(t, e) {
let s = e == null ? null : e.initialState, o = e == null ? null : e.constants;
e == null && (e = {});
const r = db(t, s, o, this.numConstants);
if (t = r.inputs, s = r.initialState, o = r.constants, Array.isArray(t) && (s = t.slice(1), t = t[0]), (s == null || s.length === 0) && o == null)
return super.apply(t, e);
const i = [], a = [];
if (s != null) {
const c = s.length;
if (c % 2 > 0)
throw new E("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");
e.initialState = s, i.push(...s);
const u = s.map((h) => new re({ shape: h.shape }));
this.forwardLayer.stateSpec = u.slice(0, c / 2), this.backwardLayer.stateSpec = u.slice(c / 2), a.push(...u);
}
if (o != null)
throw new gt("Support for constants in Bidirectional layers is not implemented yet.");
const l = i[0] instanceof Pn;
for (const c of i)
if (c instanceof Pn !== l)
throw new E("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");
if (l) {
const c = [t].concat(i), u = this.inputSpec.concat(a), h = this.inputSpec;
this.inputSpec = u;
const d = super.apply(c, e);
return this.inputSpec = h, d;
} else
return super.apply(t, e);
}
call(t, e) {
return _(() => {
const s = e.initialState;
let o, r;
if (s == null)
o = this.forwardLayer.call(t, e), r = this.backwardLayer.call(t, e);
else {
const l = s.slice(0, s.length / 2), c = s.slice(s.length / 2);
o = this.forwardLayer.call(t, Object.assign(e, { initialState: l })), r = this.backwardLayer.call(t, Object.assign(e, { initialState: c }));
}
let i;
this.returnState && (Array.isArray(o) && (i = o.slice(1).concat(r.slice(1))), o = o[0], r = r[0]), this.returnSequences && (r = qs(r, 1));
let a;
return this.mergeMode === "concat" ? a = bd([o, r]) : this.mergeMode === "sum" ? a = Y(o, r) : this.mergeMode === "ave" ? a = R(0.5, Y(o, r)) : this.mergeMode === "mul" ? a = R(o, r) : this.mergeMode == null && (a = [o, r]), this.returnState ? this.mergeMode == null ? a.concat(i) : [a].concat(i) : a;
});
}
resetStates(t) {
this.forwardLayer.resetStates(), this.backwardLayer.resetStates();
}
build(t) {
zs(this.forwardLayer.name, () => {
this.forwardLayer.build(t);
}), zs(this.backwardLayer.name, () => {
this.backwardLayer.build(t);
}), this.built = !0;
}
computeMask(t, e) {
Array.isArray(e) && (e = e[0]);
let s;
if (this.returnSequences ? this.mergeMode == null ? s = [e, e] : s = e : this.mergeMode == null ? s = [null, null] : s = null, this.returnState) {
const r = this.forwardLayer.states.map((i) => null);
return Array.isArray(s) ? s.concat(r).concat(r) : [s].concat(r).concat(r);
} else
return s;
}
get trainableWeights() {
return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights);
}
get nonTrainableWeights() {
return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights);
}
// TODO(cais): Implement constraints().
setFastWeightInitDuringBuild(t) {
super.setFastWeightInitDuringBuild(t), this.forwardLayer != null && this.forwardLayer.setFastWeightInitDuringBuild(t), this.backwardLayer != null && this.backwardLayer.setFastWeightInitDuringBuild(t);
}
getConfig() {
const t = {
mergeMode: this.mergeMode
}, e = super.getConfig();
return Object.assign(t, e), t;
}
/** @nocollapse */
static fromConfig(t, e) {
const s = Kn(e.layer);
if (delete e.layer, e.numConstants != null)
throw new gt("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");
const o = e;
return o.layer = s, new t(o);
}
}
r0.className = "Bidirectional";
j(r0);
/**
* @license
* Copyright 2022 CodeSmith LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class i0 extends Ct {
constructor(t) {
super(t), this.scale = t.scale, t.offset ? this.offset = t.offset : this.offset = 0;
}
getConfig() {
const t = {
scale: this.scale,
offset: this.offset
}, e = super.getConfig();
return Object.assign(t, e), t;
}
call(t, e) {
return _(() => (t = ft(t), t.dtype !== "float32" && (t = Fn(t, "float32")), Y(R(t, this.scale), this.offset)));
}
}
i0.className = "Rescaling";
j(i0);
/**
* @license
* Copyright 2022 CodeSmith LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const { resizeBilinear: HT, cropAndResize: KT } = Hn;
class a0 extends Ct {
constructor(t) {
super(t), this.height = t.height, this.width = t.width;
}
centerCrop(t, e, s, o, r, i, a, l) {
return _(() => {
let c, u = !1;
const h = e / i, d = s / a, p = (o + e) / i, f = (r + s) / a, m = [h, d, p, f], g = [];
t.rank === 3 ? (u = !0, c = Xn([t])) : c = t;
for (let C = 0; C < c.shape[0]; C++)
g.push(m);
const x = km(g, [g.length, 4]), b = gr(0, g.length, 1, "int32"), y = KT(c, x, b, [o, r], "nearest");
return Fn(u ? ft(Ys(y)) : y, l);
});
}
upsize(t, e, s, o) {
return _(() => {
const r = HT(t, [e, s]);
return Fn(r, o);
});
}
call(t, e) {
return _(() => {
const s = ft(t), o = s.dtype, r = s.shape, i = r[r.length - 3], a = r[r.length - 2];
let l = 0;
i !== this.height && (l = Math.floor((i - this.height) / 2));
let c = 0;
return a !== this.width && (c = Math.floor((a - this.width) / 2), c === 0 && (c = 1)), l >= 0 && c >= 0 ? this.centerCrop(s, l, c, this.height, this.width, i, a, o) : this.upsize(t, this.height, this.width, o);
});
}
getConfig() {
const t = {
height: this.height,
width: this.width
}, e = super.getConfig();
return Object.assign(t, e), t;
}
computeOutputShape(t) {
t = St(t);
const e = t.length - 3, s = t.length - 2;
return t[e] = this.height, t[s] = this.width, t;
}
}
a0.className = "CenterCrop";
j(a0);
/**
* @license
* Copyright 2022 CodeSmith LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
function jT(n, t, e, s) {
let o = ft(n);
if (o.dtype !== "int32" && (o = Fn(o, "int32")), t === "int")
return o;
const r = o.shape;
if (o.rank === 0 && (o = Oe(o, -1)), t === "oneHot" && o.shape[o.shape.length - 1] !== 1 && (o = Oe(o, -1)), o.rank > 2)
throw new E(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${r} which would result in output rank ${o.rank}.`);
const i = ["multiHot", "oneHot"].includes(t), a = o;
let l;
if (typeof s < "u" && t === "count" ? l = mp(a, s, e, i) : l = mp(a, [], e, i), t !== "tfIdf")
return l;
if (s)
return R(l, s);
throw new E("When outputMode is 'tfIdf', weights must be provided.");
}
/**
* @license
* Copyright 2022 CodeSmith LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class l0 extends Ct {
constructor(t) {
super(t), this.numTokens = t.numTokens, t.outputMode ? this.outputMode = t.outputMode : this.outputMode = "multiHot";
}
getConfig() {
const t = {
numTokens: this.numTokens,
outputMode: this.outputMode
}, e = super.getConfig();
return Object.assign(t, e), t;
}
computeOutputShape(t) {
return t = St(t), t == null ? [this.numTokens] : this.outputMode === "oneHot" && t[t.length - 1] !== 1 ? (t.push(this.numTokens), t) : (t[t.length - 1] = this.numTokens, t);
}
call(t, e) {
return _(() => {
t = ft(t), t.dtype !== "int32" && (t = Fn(t, "int32"));
let s;
if (typeof e.countWeights < "u") {
if (this.outputMode !== "count")
throw new E(`countWeights is not used when outputMode !== count.
Received countWeights=${e.countWeights}`);
s = ft(e.countWeights);
}
const o = bn(t), r = ua(t), i = Je(this.numTokens, o).bufferSync().get(0), a = oo(r, 0).bufferSync().get(0);
if (!(i && a))
throw new E(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);
return jT(t, this.outputMode, this.numTokens, s);
});
}
}
l0.className = "CategoryEncoding";
j(l0);
/**
* @license
* Copyright 2022 CodeSmith LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const XT = ["bilinear", "nearest"], Xp = new Set(XT);
class c0 extends Ct {
constructor(t) {
if (super(t), this.height = t.height, this.width = t.width, t.interpolation)
if (Xp.has(t.interpolation))
this.interpolation = t.interpolation;
else
throw new E(`Invalid interpolation parameter: ${t.interpolation} is not implemented`);
else
this.interpolation = "bilinear";
this.cropToAspectRatio = !!t.cropToAspectRatio;
}
computeOutputShape(t) {
t = St(t);
const e = t[2];
return [this.height, this.width, e];
}
getConfig() {
const t = {
height: this.height,
width: this.width,
interpolation: this.interpolation,
cropToAspectRatio: this.cropToAspectRatio
}, e = super.getConfig();
return Object.assign(t, e), t;
}
call(t, e) {
return _(() => {
const s = [this.height, this.width];
if (this.interpolation === "bilinear")
return Hn.resizeBilinear(t, s, !this.cropToAspectRatio);
if (this.interpolation === "nearest")
return Hn.resizeNearestNeighbor(t, s, !this.cropToAspectRatio);
throw new Error(`Interpolation is ${this.interpolation} but only ${[...Xp]} are supported`);
});
}
}
c0.className = "Resizing";
j(c0);
/**
* @license
* Copyright 2023 CodeSmith LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class u0 {
constructor(t) {
this.seed = t;
}
next() {
if (this.seed !== void 0)
return this.seed++;
}
}
u0.className = "RandomSeed";
/**
* @license
* Copyright 2023 CodeSmith LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
class h0 extends Ct {
constructor(t) {
super(t), this.randomGenerator = new u0(t.seed);
}
getConfig() {
const t = {
seed: this.randomGenerator.seed
}, e = super.getConfig();
return Object.assign(t, e), t;
}
}
h0.className = "BaseRandomLayer";
/**
* @license
* Copyright 2023 CodeSmith LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
const qT = ["bilinear", "nearest"], qp = new Set(qT);
class d0 extends h0 {
constructor(t) {
super(t);
const { factor: e, interpolation: s = "bilinear" } = t;
if (this.factor = e, Array.isArray(this.factor) && this.factor.length === 2)
this.widthLower = this.factor[0], this.widthUpper = this.factor[1];
else if (!Array.isArray(this.factor) && this.factor > 0)
this.widthLower = -this.factor, this.widthUpper = this.factor;
else
throw new E(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);
if (this.widthLower < -1 || this.widthUpper < -1)
throw new E(`factor must have values larger than -1. Got: ${this.factor}`);
if (this.widthUpper < this.widthLower)
throw new E(`factor cannot have upper bound less than lower bound.
Got upper bound: ${this.widthUpper}.
Got lower bound: ${this.widthLower}
`);
if (s)
if (qp.has(s))
this.interpolation = s;
else
throw new E(`Invalid interpolation parameter: ${s} is not implemented`);
}
getConfig() {
const t = {
factor: this.factor,
interpolation: this.interpolation
}, e = super.getConfig();
return Object.assign(t, e), t;
}
computeOutputShape(t) {
t = St(t);
const e = t[2];
return [this.imgHeight, -1, e];
}
call(t, e) {
return _(() => {
const s = ft(t);
this.imgHeight = s.shape[s.shape.length - 3];
const o = s.shape[s.shape.length - 2];
this.widthFactor = Ii([1], 1 + this.widthLower, 1 + this.widthUpper, "float32", this.randomGenerator.next());
let r = this.widthFactor.dataSync()[0] * o;
r = Math.round(r);
const i = [this.imgHeight, r];
switch (this.interpolation) {
case "bilinear":
return Hn.resizeBilinear(t, i);
case "nearest":
return Hn.resizeNearestNeighbor(t, i);
default:
throw new Error(`Interpolation is ${this.interpolation}
but only ${[...qp]} are supported`);
}
});
}
}
d0.className = "RandomWidth";
j(d0);
/**
* @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.
* =============================================================================
*/
const YT = P();
YT.registerFlag("KEEP_INTERMEDIATE_TENSORS", () => !1, (n) => {
n && 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.");
});
/**
* @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 Yp;
(function(n) {
n[n.DT_INVALID = 0] = "DT_INVALID", n[n.DT_FLOAT = 1] = "DT_FLOAT", n[n.DT_DOUBLE = 2] = "DT_DOUBLE", n[n.DT_INT32 = 3] = "DT_INT32", n[n.DT_UINT8 = 4] = "DT_UINT8", n[n.DT_INT16 = 5] = "DT_INT16", n[n.DT_INT8 = 6] = "DT_INT8", n[n.DT_STRING = 7] = "DT_STRING", n[n.DT_COMPLEX64 = 8] = "DT_COMPLEX64", n[n.DT_INT64 = 9] = "DT_INT64", n[n.DT_BOOL = 10] = "DT_BOOL", n[n.DT_QINT8 = 11] = "DT_QINT8", n[n.DT_QUINT8 = 12] = "DT_QUINT8", n[n.DT_QINT32 = 13] = "DT_QINT32", n[n.DT_BFLOAT16 = 14] = "DT_BFLOAT16", n[n.DT_QINT16 = 15] = "DT_QINT16", n[n.DT_QUINT16 = 16] = "DT_QUINT16", n[n.DT_UINT16 = 17] = "DT_UINT16", n[n.DT_COMPLEX128 = 18] = "DT_COMPLEX128", n[n.DT_HALF = 19] = "DT_HALF", n[n.DT_RESOURCE = 20] = "DT_RESOURCE", n[n.DT_VARIANT = 21] = "DT_VARIANT", n[n.DT_UINT32 = 22] = "DT_UINT32", n[n.DT_UINT64 = 23] = "DT_UINT64", n[n.DT_FLOAT_REF = 101] = "DT_FLOAT_REF", n[n.DT_DOUBLE_REF = 102] = "DT_DOUBLE_REF", n[n.DT_INT32_REF = 103] = "DT_INT32_REF", n[n.DT_UINT8_REF = 104] = "DT_UINT8_REF", n[n.DT_INT16_REF = 105] = "DT_INT16_REF", n[n.DT_INT8_REF = 106] = "DT_INT8_REF", n[n.DT_STRING_REF = 107] = "DT_STRING_REF", n[n.DT_COMPLEX64_REF = 108] = "DT_COMPLEX64_REF", n[n.DT_INT64_REF = 109] = "DT_INT64_REF", n[n.DT_BOOL_REF = 110] = "DT_BOOL_REF", n[n.DT_QINT8_REF = 111] = "DT_QINT8_REF", n[n.DT_QUINT8_REF = 112] = "DT_QUINT8_REF", n[n.DT_QINT32_REF = 113] = "DT_QINT32_REF", n[n.DT_BFLOAT16_REF = 114] = "DT_BFLOAT16_REF", n[n.DT_QINT16_REF = 115] = "DT_QINT16_REF", n[n.DT_QUINT16_REF = 116] = "DT_QUINT16_REF", n[n.DT_UINT16_REF = 117] = "DT_UINT16_REF", n[n.DT_COMPLEX128_REF = 118] = "DT_COMPLEX128_REF", n[n.DT_HALF_REF = 119] = "DT_HALF_REF", n[n.DT_RESOURCE_REF = 120] = "DT_RESOURCE_REF", n[n.DT_VARIANT_REF = 121] = "DT_VARIANT_REF", n[n.DT_UINT32_REF = 122] = "DT_UINT32_REF", n[n.DT_UINT64_REF = 123] = "DT_UINT64_REF";
})(Yp || (Yp = {}));
var Jp;
(function(n) {
(function(t) {
t[t.LEGACY = 0] = "LEGACY", t[t.V1 = 1] = "V1", t[t.V2 = 2] = "V2";
})(n.CheckpointFormatVersion || (n.CheckpointFormatVersion = {}));
})(Jp || (Jp = {}));
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
var Zp;
(function(n) {
n[n.FAIL = 0] = "FAIL", n[n.SHORTEST = 1] = "SHORTEST", n[n.LONGEST = 2] = "LONGEST";
})(Zp || (Zp = {}));
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function rt(n, t) {
Array.isArray(n) || (n = [n]), n.forEach((e) => {
e != null && I(e.dtype !== "complex64", () => `${t} does not support complex64 tensors in the CPU backend.`);
});
}
/**
* @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.
* =============================================================================
*/
const JT = lg;
class nc extends wu {
nextDataId() {
return nc.nextDataId++;
}
constructor() {
super(), this.blockSize = 48, this.firstUse = !0, this.data = new Of(this, kn());
}
write(t, e, s) {
this.firstUse && (this.firstUse = !1, P().get("IS_NODE") && je(`
============================
Hi, 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.
============================`));
const o = { id: this.nextDataId() };
return this.data.set(o, { values: t, dtype: s, refCount: 1 }), o;
}
/**
* 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(t, e, s) {
let o;
if (e === "string" && s != null && s.length > 0 && vr(s[0])) {
const r = s.map((i) => us(i));
o = this.write(r, t, e);
} else
o = this.write(s, t, e);
return { dataId: o, shape: t, dtype: e };
}
/** Return refCount of a `TensorData`. */
refCount(t) {
return this.data.has(t) ? this.data.get(t).refCount : 0;
}
/** Increase refCount of a `TensorData`. */
incRef(t) {
const e = this.data.get(t);
e.refCount++;
}
/** Decrease refCount of a `TensorData`. */
decRef(t) {
if (this.data.has(t)) {
const e = this.data.get(t);
e.refCount--;
}
}
move(t, e, s, o, r) {
this.data.set(t, { values: e, dtype: o, refCount: r });
}
numDataIds() {
return this.data.numDataIds();
}
async read(t) {
return this.readSync(t);
}
readSync(t) {
const { dtype: e, complexTensorInfos: s } = this.data.get(t);
if (e === "complex64") {
const o = this.readSync(s.real.dataId), r = this.readSync(s.imag.dataId);
return qn(o, r);
}
return V1(this.data.get(t).values, e);
}
bufferSync(t) {
const e = this.readSync(t.dataId);
if (t.dtype === "string")
try {
const s = e.map((o) => ps(o));
return yt(t.shape, t.dtype, s);
} catch {
throw new Error("Failed to decode encoded string bytes into utf-8");
}
return yt(t.shape, t.dtype, e);
}
makeOutput(t, e, s) {
return kn().makeTensorFromTensorInfo(this.makeTensorInfo(e, s, t), 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(t, e = !1) {
if (this.data.has(t)) {
if (this.data.get(t).refCount--, !e && this.data.get(t).refCount > 0)
return !1;
const { complexTensorInfos: s } = this.data.get(t);
s != null && (this.disposeData(s.real.dataId, !0), this.disposeData(s.imag.dataId, !0)), this.data.delete(t);
}
return !0;
}
disposeIntermediateTensorInfo(t) {
this.disposeData(t.dataId);
}
async time(t) {
const e = Fe();
return t(), { kernelMs: Fe() - e };
}
memory() {
return {
// Unreliable due to automatic gc. The numbers above are cumulative.
unreliable: !0,
reasons: ["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]
};
}
where(t) {
rt([t], "where");
const e = this.readSync(t.dataId);
return JT(t.shape, e);
}
dispose() {
}
floatPrecision() {
return 32;
}
/** Returns the smallest representable number. */
epsilon() {
return super.epsilon();
}
}
nc.nextDataId = 0;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function p0(n) {
const t = new Float32Array(n.length);
for (let e = 0; e < n.length; ++e)
t[e] = Math.abs(n[e]);
return t;
}
const ZT = (n) => {
const { x: t } = n.inputs, e = n.backend;
rt(t, "abs");
let s = new Float32Array(G(t.shape));
const o = e.data.get(t.dataId).values;
return s = p0(o), e.makeOutput(s, t.shape, t.dtype);
}, QT = {
kernelName: Fa,
backendName: "cpu",
kernelFunc: ZT
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function te(n) {
return (t, e, s, o, r) => {
const i = mt(t, e), a = i.length, l = lt(i), c = G(i), u = we(r, c), h = t.length, d = e.length, p = lt(t), f = lt(e), m = To(t, i), g = To(e, i);
if (m.length + g.length === 0)
for (let x = 0; x < u.length; ++x)
u[x] = n(s[x % s.length], o[x % o.length]);
else
for (let x = 0; x < u.length; ++x) {
const b = Mo(x, a, l), w = b.slice(-h);
m.forEach((k) => w[k] = 0);
const y = Rn(w, h, p), C = b.slice(-d);
g.forEach((k) => C[k] = 0);
const $ = Rn(C, d, f);
u[x] = n(s[y], o[$]);
}
return [u, i];
};
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ve(n) {
const { inputs: t, backend: e } = n, { real: s, imag: o } = t, r = e.data.get(s.dataId).values, i = e.data.get(o.dataId).values, a = e.makeTensorInfo(s.shape, "complex64"), l = e.data.get(a.dataId);
return l.complexTensorInfos = {
real: e.makeTensorInfo(s.shape, "float32", r),
imag: e.makeTensorInfo(o.shape, "float32", i)
}, a;
}
const tE = {
kernelName: Fu,
backendName: "cpu",
kernelFunc: Ve
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ka(n, t, e = "float32") {
if (e === "complex64") {
const o = ka(n, t, "float32"), r = ka(n, t, "float32");
return Ve({ inputs: { real: o, imag: r }, backend: n });
}
const s = Ce(G(t), e);
return n.makeTensorInfo(t, e, s);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function zn(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
return e.incRef(s.dataId), { dataId: s.dataId, shape: s.shape, dtype: s.dtype };
}
const eE = {
kernelName: Kr,
backendName: "cpu",
kernelFunc: zn
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Zs(n) {
const { inputs: t, backend: e } = n, { input: s } = t, o = e.data.get(s.dataId).complexTensorInfos.real, r = e.data.get(o.dataId).values;
return e.makeTensorInfo(o.shape, o.dtype, r);
}
const nE = {
kernelName: sh,
backendName: "cpu",
kernelFunc: Zs
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function f0(n, t, e, s) {
if (s === "int32") {
const o = Int32Array.from(n);
return [t, "int32", o];
}
if (s === "bool") {
const o = so([0], e), [r, i] = te((a, l) => a !== l ? 1 : 0)(t, [], n, o, "bool");
return [i, "bool", r];
}
throw new Error(`Error in Cast: failed to cast ${e} to ${s}`);
}
function bs(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { dtype: r } = s;
if (r === "complex64") {
if (o.dtype === "complex64")
return zn({ inputs: { x: o }, backend: e });
const u = ka(e, o.shape, o.dtype), h = bs({ inputs: { x: o }, backend: e, attrs: { dtype: "float32" } }), d = Ve({ inputs: { real: h, imag: u }, backend: e });
return e.disposeIntermediateTensorInfo(u), e.disposeIntermediateTensorInfo(h), d;
}
if (o.dtype === "complex64") {
const u = Zs({ inputs: { input: o }, backend: e }), h = bs({ inputs: { x: u }, backend: e, attrs: { dtype: r } });
return e.disposeIntermediateTensorInfo(u), h;
}
if (!Mf(o.dtype, r)) {
const u = zn({ inputs: { x: o }, backend: e });
return { dataId: u.dataId, shape: u.shape, dtype: r };
}
const i = e.data.get(o.dataId).values, [a, l, c] = f0(i, o.shape, o.dtype, r);
return e.makeTensorInfo(a, l, c);
}
const sE = {
kernelName: Fr,
backendName: "cpu",
kernelFunc: bs
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ce(n, t, e, s) {
return e == null ? ({ inputs: o, backend: r }) => {
const { a: i, b: a } = o, l = r;
rt([i, a], n);
const c = l.data.get(i.dataId).values, u = l.data.get(a.dataId).values, h = i.dtype === "string" ? (
// tslint:disable-next-line: no-any
Yn(c)
) : c, d = i.dtype === "string" ? (
// tslint:disable-next-line: no-any
Yn(u)
) : u, p = s || i.dtype, [f, m] = t(i.shape, a.shape, h, d, p);
return l.makeTensorInfo(m, p, f);
} : ({ inputs: o, backend: r }) => {
const { a: i, b: a } = o, l = r;
if (i.dtype === "complex64" || a.dtype === "complex64") {
const c = bs({ inputs: { x: i }, backend: l, attrs: { dtype: "complex64" } }), u = l.data.get(c.dataId), h = u.complexTensorInfos.real, d = u.complexTensorInfos.imag, p = l.data.get(h.dataId).values, f = l.data.get(d.dataId).values, m = bs({ inputs: { x: a }, backend: l, attrs: { dtype: "complex64" } }), g = l.data.get(m.dataId), x = g.complexTensorInfos.real, b = g.complexTensorInfos.imag, w = l.data.get(x.dataId).values, y = l.data.get(b.dataId).values, [C, $, k] = e(i.shape, a.shape, p, f, w, y), v = l.makeTensorInfo(k, "float32", C), S = l.makeTensorInfo(k, "float32", $), T = Ve({ inputs: { real: v, imag: S }, backend: l });
return l.disposeIntermediateTensorInfo(c), l.disposeIntermediateTensorInfo(m), l.disposeIntermediateTensorInfo(v), l.disposeIntermediateTensorInfo(S), T;
} else {
const c = l.data.get(i.dataId).values, u = l.data.get(a.dataId).values, h = s || i.dtype, [d, p] = t(i.shape, a.shape, c, u, h);
return l.makeTensorInfo(p, h, d);
}
};
}
function Md(n) {
return (t, e, s, o, r, i) => {
const a = mt(t, e), l = G(a), c = a.length, u = lt(a), h = we("float32", l), d = we("float32", l), p = To(t, a), f = To(e, a), m = qn(s, o), g = qn(r, i), x = t.length, b = lt(t), w = e.length, y = lt(e);
if (p.length + f.length === 0)
for (let C = 0; C < h.length; C++) {
const $ = C % m.length, k = C % g.length, v = n(m[$ * 2], m[$ * 2 + 1], g[k * 2], g[k * 2 + 1]);
h[C] = v.real, d[C] = v.imag;
}
else
for (let C = 0; C < h.length; C++) {
const $ = Mo(C, c, u), k = $.slice(-x);
p.forEach((L) => k[L] = 0);
const v = Rn(k, x, b), S = $.slice(-w);
f.forEach((L) => S[L] = 0);
const T = Rn(S, w, y), F = n(m[v * 2], m[v * 2 + 1], g[T * 2], g[T * 2 + 1]);
h[C] = F.real, d[C] = F.imag;
}
return [h, d, a];
};
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const m0 = te((n, t) => n + t), oE = Md((n, t, e, s) => ({ real: n + e, imag: t + s })), Do = ce(Po, m0, oE), rE = {
kernelName: Po,
backendName: "cpu",
kernelFunc: Do
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Pd(n, t, e, s, o) {
const r = G(s), i = Ce(o, e);
for (let a = 0; a < n.length; a++) {
const l = n[a];
if (l < 0)
throw new Error("Input x must be non-negative!");
l >= o || (r > 0 ? i[l] += t[a] : i[l] += 1);
}
return i;
}
function g0(n, t, e, s = !1) {
const o = n.shape[0], r = n.shape[1], i = yt([o, e], t.dtype);
for (let a = 0; a < o; a++)
for (let l = 0; l < r; l++) {
const c = n.get(a, l);
if (c < 0)
throw new Error("Input x must be non-negative!");
c >= e || (s ? i.set(1, a, c) : t.size > 0 ? i.set(i.get(a, c) + t.get(a, l), a, c) : i.set(i.get(a, c) + 1, a, c));
}
return i;
}
/**
* @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.
* =============================================================================
*/
const x0 = te((n, t) => n & t), iE = ce(Au, x0), aE = {
kernelName: Au,
backendName: "cpu",
kernelFunc: iE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Bn(n) {
return (t, e, s) => {
const o = qt(e, t.length);
for (let r = 0; r < t.length; ++r)
o[r] = n(t[r], s);
return o;
};
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function At(n, t, e) {
const s = Bn(t);
return Ns(n, s, e);
}
function Ns(n, t, e) {
return ({ inputs: s, attrs: o, backend: r }) => {
const { x: i } = s;
rt(i, n);
const a = r, l = a.data.get(i.dataId).values;
let c;
if (i.dtype === "string") {
if (!Array.isArray(l))
throw new Error("String tensor's value was not an instance of Array");
c = Yn(l);
} else
c = l;
const u = e || i.dtype, h = t(c, u, o);
return a.makeTensorInfo(i.shape, u, h);
};
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const b0 = Bn((n) => Math.ceil(n)), lE = Ns(Or, b0), cE = {
kernelName: Or,
backendName: "cpu",
kernelFunc: lE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function y0(n, t, e, s) {
const o = qt(e, G(t));
if (s && e !== "string") {
let r = 0;
n.forEach((i) => {
const a = G(i.shape);
o.set(i.vals, r), r += a;
});
} else {
let r = 0;
n.forEach((i) => {
const a = e === "string" ? Yn(i.vals) : i.vals;
let l = 0;
for (let c = 0; c < i.shape[0]; ++c) {
const u = c * t[1] + r;
for (let h = 0; h < i.shape[1]; ++h)
o[u + h] = a[l++];
}
r += i.shape[1];
});
}
return o;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const w0 = te((n, t) => n === t ? 1 : 0), C0 = ce(Xa, w0, null, "bool"), uE = {
kernelName: Xa,
backendName: "cpu",
kernelFunc: C0
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const $0 = Bn((n) => Math.exp(n)), I0 = Ns(Vr, $0, "float32"), hE = {
kernelName: Vr,
backendName: "cpu",
kernelFunc: I0
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const k0 = Bn((n) => Math.expm1(n)), dE = Ns(Wr, k0), pE = {
kernelName: Wr,
backendName: "cpu",
kernelFunc: dE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const v0 = Bn((n) => Math.floor(n)), fE = Ns(Ur, v0), mE = {
kernelName: Ur,
backendName: "cpu",
kernelFunc: fE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const S0 = te((n, t) => Math.floor(n / t)), gE = ce(Gr, S0, null, "int32"), xE = {
kernelName: Gr,
backendName: "cpu",
kernelFunc: gE
};
/**
* @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.
* =============================================================================
*/
function N0(n, t, e, s, o, r, i, a, l) {
const c = yt([s, r], e);
for (let u = 0; u < s; u++) {
const h = [];
let d = 0;
for (let p = 0; p < o; p++) {
const f = n[u * o + p];
d += f * i[p], h.push(f);
}
if (d < 0 || d >= l / r)
throw new Error(`Invalid indices: ${h} does not index into ${a}`);
for (let p = 0; p < r; p++)
c.values[u * r + p] = t.get(...t.indexToLoc(d * r + p));
}
return c;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function T0(n, t, e) {
const s = yt(e, n.dtype);
for (let o = 0; o < s.size; ++o) {
const i = s.indexToLoc(o).slice(), a = i[0], l = i[2], c = t.locToIndex([a, l]);
i[2] = t.values[c];
const u = n.locToIndex(i);
0 <= u && u < n.values.length && (s.values[o] = n.values[u]);
}
return s;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const E0 = te((n, t) => n > t ? 1 : 0), bE = ce(Za, E0, null, "bool"), yE = {
kernelName: Za,
backendName: "cpu",
kernelFunc: bE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const R0 = te((n, t) => n >= t ? 1 : 0), wE = ce(Hr, R0, null, "bool"), CE = {
kernelName: Hr,
backendName: "cpu",
kernelFunc: wE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const D0 = te((n, t) => n < t ? 1 : 0), $E = ce(tl, D0, null, "bool"), IE = {
kernelName: tl,
backendName: "cpu",
kernelFunc: $E
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const A0 = te((n, t) => n <= t ? 1 : 0), kE = ce(el, A0, null, "bool"), vE = {
kernelName: el,
backendName: "cpu",
kernelFunc: kE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function F0(n, t, e) {
const s = (t - n) / (e - 1), o = Ce(e, "float32");
o[0] = n;
for (let r = 1; r < o.length; r++)
o[r] = o[r - 1] + s;
return o;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const O0 = Bn((n) => Math.log(n)), SE = Ns(Yr, O0), NE = {
kernelName: Yr,
backendName: "cpu",
kernelFunc: SE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _0(n, t, e, s) {
const o = we(s, G(e));
for (let r = 0; r < o.length; ++r) {
const i = r * t;
let a = n[i];
for (let l = 0; l < t; ++l) {
const c = n[i + l];
(Number.isNaN(c) || c > a) && (a = c);
}
o[r] = a;
}
return o;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const L0 = te((n, t) => Math.max(n, t)), TE = ce(Zr, L0), EE = {
kernelName: Zr,
backendName: "cpu",
kernelFunc: TE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const M0 = te((n, t) => Math.min(n, t)), RE = ce(Qr, M0), DE = {
kernelName: Qr,
backendName: "cpu",
kernelFunc: RE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const zd = te((n, t) => n * t), AE = Md((n, t, e, s) => ({
real: n * e - t * s,
imag: n * s + t * e
})), sc = ce(ei, zd, AE), FE = {
kernelName: ei,
backendName: "cpu",
kernelFunc: sc
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function P0(n, t, e) {
const s = ws(-1, e);
return zd([], t, s, n, e);
}
function OE(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
rt(s, "neg");
const o = e.data.get(s.dataId).values, [r, i] = P0(o, s.shape, s.dtype);
return e.makeTensorInfo(i, s.dtype, r);
}
const _E = {
kernelName: dl,
backendName: "cpu",
kernelFunc: OE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const z0 = te((n, t) => n !== t ? 1 : 0), LE = ce(pl, z0, null, "bool"), ME = {
kernelName: pl,
backendName: "cpu",
kernelFunc: LE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Bd(n, t, e, s, o) {
const r = t.length, i = G(t), a = lt(t), l = lt(o), c = we(e, G(o));
for (let u = 0; u < i; ++u) {
const h = Mo(u, r, a), d = new Array(h.length);
for (let f = 0; f < d.length; f++)
d[f] = h[s[f]];
const p = Rn(d, r, l);
c[p] = n[u];
}
return c;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Pe(n) {
const { inputs: t, attrs: e, backend: s } = n, { x: o } = t, { perm: r } = e;
rt(o, "transpose");
const i = o.shape.length, a = new Array(i);
for (let h = 0; h < a.length; h++)
a[h] = o.shape[r[h]];
const l = s.data.get(o.dataId).values, c = Bd(l, o.shape, o.dtype, r, a);
return { dataId: s.write(c, a, o.dtype), shape: a, dtype: o.dtype };
}
const PE = {
kernelName: Co,
backendName: "cpu",
kernelFunc: Pe
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function B0(n, t, e, s) {
const [o, r] = pe(n, s), i = Ue(t, "int32"), a = Ce(G(o), i), l = G(r);
for (let c = 0; c < a.length; ++c) {
const u = c * l;
let h = 1;
for (let d = 0; d < l; ++d)
h *= e[u + d];
a[c] = h;
}
return { outVals: a, outShape: o, outDtype: i };
}
function zE(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s;
rt(o, "prod");
const a = o.shape.length, l = wt(r, o.shape), c = jt(l, a);
let u = l, h = o;
const d = [];
c != null && (h = Pe({ inputs: { x: o }, backend: e, attrs: { perm: c } }), d.push(h), u = Zt(u.length, a));
const p = e.data.get(h.dataId).values, { outVals: f, outShape: m, outDtype: g } = B0(h.shape, h.dtype, p, u);
let x = m;
return i && (x = ne(m, l)), d.forEach((b) => e.disposeIntermediateTensorInfo(b)), e.makeTensorInfo(x, g, f);
}
const BE = {
kernelName: yl,
backendName: "cpu",
kernelFunc: zE
};
/**
* @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.
* =============================================================================
*/
function VE(n, t, e) {
n.forEach((s, o) => {
if (s < 0 || s >= e) {
const r = Mo(o, t.length, lt(t)).join(",");
throw new Error(`indices[${r}] = ${s} is not in [0, ${e})`);
}
});
}
function WE(n, t) {
for (let e = 0; e < n.length; ++e) {
const s = n[e], o = e === n.length - 1 ? t : n[e + 1].length;
if (s.length === 0)
throw new Error("Ragged splits may not be empty");
if (s[0] < 0)
throw new Error("Ragged splits must be non-negative");
if (s[s.length - 1] > o)
throw new Error("Ragged splits must not point past values");
for (let r = 1; r < s.length; ++r)
if (s[r - 1] > s[r])
throw new Error("Ragged splits must be sorted in ascending order");
}
}
function UE(n, t, e, s) {
const o = [];
let r = 0;
const i = t.length - 1 + e.length, a = new Array(i).fill(null).map(() => [0]);
WE(e, s);
let l = 1;
for (let c = 0; c < t.length - 1; ++c) {
l *= t[c];
const u = t[c + 1];
for (let h = 1; h < l + 1; ++h)
a[c].push(h * u);
}
for (let c = 0; c < n.length; ++c) {
let u = n[c], h = n[c] + 1;
for (let d = 0; d < e.length; ++d) {
const p = e[d], f = d + t.length - 1;
if (f >= 0) {
const m = a[f], g = m[m.length - 1] - p[u];
for (let x = u; x < h; ++x)
a[f].push(p[x + 1] + g);
}
u = p[u], h = p[h];
}
h !== u && (o.push([u, h]), r += h - u);
}
return { outSplits: a, valueSlices: o, numValues: r };
}
function GE(n) {
const t = [];
for (let e = 0; e < n.length; ++e) {
const s = n[e].length, o = qt("int32", s);
t.push(o), n[e].forEach((r, i) => o[i] = r);
}
return t;
}
function Qp(n, t) {
const e = n.slice(0, t);
for (; e.length < t; )
e.push(1);
for (let s = t; s < n.length; s++)
e[t - 1] *= n[s];
return e;
}
function HE(n, t, e, s, o, r) {
const i = Qp(t, 2)[1], a = Qp(r, 2)[1];
let l = 0;
for (const c of e)
for (let u = c[0]; u < c[1]; ++u) {
for (let h = 0; h < s; ++h)
o[l * a + h] = n[u * i + h];
++l;
}
}
function KE(n, t, e, s, o) {
const r = t.slice();
r[0] = o;
const i = qt(e, G(r)), a = n.length, l = a === 0 ? 0 : a / t[0];
return HE(n, t, s, l, i, r), [i, r];
}
function V0(n, t, e, s, o, r, i, a) {
if (n.length === 0)
throw new Error("paramsNestedSplits must be non empty");
if (t[0].length === 0)
throw new Error("Split tensors must not be scalars");
const l = t[0][0] - 1;
if (VE(r, i, l), s.length === 0)
throw new Error("params.rank must be nonzero");
const c = s[0], { outSplits: u, valueSlices: h, numValues: d } = UE(r, i, n, c), p = GE(u), f = KE(e, s, o, h, d);
return [p, f[0], f[1]];
}
/**
* @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.
* =============================================================================
*/
const tf = 2147483647;
function W0(n, t, e, s, o, r, i) {
if (t.length > 1)
throw new Error("starts must be a scalar or vector");
if (o.length > 1)
throw new Error("limits must be a scalar or vector");
if (i.length > 1)
throw new Error("deltas must be a scalar or vector");
const a = t.length === 0, l = o.length === 0, c = i.length === 0, u = [];
a || u.push(t[0]), l || u.push(o[0]), c || u.push(i[0]);
for (let g = 1; g < u.length; ++g)
if (u[g] !== u[g - 1])
throw new Error("starts, limits, and deltas must have the same shape");
const h = u.length === 0 ? 1 : u[0], d = qt("int32", h + 1);
d[0] = 0;
for (let g = 0; g < h; ++g) {
const x = a ? n[0] : n[g], b = l ? s[0] : s[g], w = c ? r[0] : r[g];
if (w === 0)
throw new Error("Requires delta != 0");
let y;
if (w > 0 && b < x || w < 0 && b > x)
y = 0;
else if (y = Math.ceil(Math.abs((b - x) / w)), y > tf)
throw new Error(`Requires ((limit - start) / delta) <= ${tf}`);
d[g + 1] = d[g] + y;
}
const p = d[h], f = qt(e, p);
let m = 0;
for (let g = 0; g < h; ++g) {
const x = d[g + 1] - d[g];
let b = a ? n[0] : n[g];
const w = c ? r[0] : r[g];
for (let y = 0; y < x; ++y)
f[m++] = b, b += w;
}
return [d, f];
}
/**
* @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 tn = mn;
class va {
constructor(t, e, s, o, r, i, a, l, c, u) {
this.shape = t, this.shapeShape = e, this.values = s, this.valuesShape = o, this.valuesDType = r, this.defaultValue = i, this.defaultValueShape = a, this.rowPartitionValues = l, this.rowPartitionValuesShapes = c, this.rowPartitionTypes = Ng(u), this.raggedRank = Tg(this.rowPartitionTypes);
}
getRowPartitionTypeByDimension(t) {
return this.rowPartitionTypes[0] === tn.FIRST_DIM_SIZE ? this.rowPartitionTypes[t + 1] : this.rowPartitionTypes[t];
}
// Returns the relationship between dimension and dimension + 1.
getRowPartitionTensor(t) {
return this.rowPartitionTypes[0] === tn.FIRST_DIM_SIZE ? this.rowPartitionValues[t + 1] : this.rowPartitionValues[t];
}
getMaxWidth(t) {
const e = this.getRowPartitionTensor(t - 1);
switch (this.getRowPartitionTypeByDimension(t - 1)) {
case tn.VALUE_ROWIDS:
return va.getMaxWidthValueRowID(e);
case tn.ROW_SPLITS:
return va.getMaxWidthRowSplit(e);
default:
throw new Error(`Cannot handle partition type ${tn[this.getRowPartitionTypeByDimension(t - 1)]}`);
}
}
static getMaxWidthRowSplit(t) {
const e = t.length;
if (e === 0 || e === 1)
return 0;
let s = 0;
for (let o = 0; o < e - 1; ++o) {
const r = t[o + 1] - t[o];
r > s && (s = r);
}
return s;
}
static getMaxWidthValueRowID(t) {
const e = t.length;
if (e === 0)
return 0;
let s = 0, o = t[0], r = 0;
for (let i = 1; i < e; ++i) {
const a = t[i];
a !== o && (o = a, r = Math.max(i - s, r), s = i);
}
return Math.max(e - s, r);
}
tensorShapeFromTensor(t, e, s = !0) {
if (e.length === 0) {
if (t[0] === -1)
return [];
throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.");
}
return nf(t, s);
}
calculateOutputSize(t) {
const e = this.valuesShape, s = this.defaultValueShape;
Eg(s, e);
const o = this.tensorShapeFromTensor(this.shape, this.shapeShape), i = Sg(this.raggedRank, o, e);
i[0] < 0 && (i[0] = t);
for (let a = 1; a <= this.raggedRank; ++a)
i[a] < 0 && (i[a] = this.getMaxWidth(a));
return i;
}
/**
* 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(t, e, s) {
const o = Math.min(t, s), r = [];
let i = 0;
for (let a = 0; a < o; ++a, i += e)
r.push(i);
for (let a = o; a < t; ++a)
r.push(-1);
return I(r.length === t, () => "Final length of result must be equal to firstDimension."), r;
}
calculateOutputIndexRowSplit(t, e, s, o) {
const r = t.length, i = [];
for (let a = 0; a < r - 1; ++a) {
const l = t[a + 1] - t[a];
let c = Math.min(o, l), u = e[a];
u === -1 && (c = 0);
for (let h = 0; h < c; ++h)
i.push(u), u += s;
for (let h = 0; h < l - c; ++h)
i.push(-1);
}
if (r > 0 && i.length !== t[r - 1])
throw new Error("Invalid row split size.");
return i;
}
// 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(t, e, s, o) {
const r = t.length, i = [];
if (r === 0)
return [];
let a = 0, l = t[0];
if (l >= e.length)
throw new Error(`Got currentValueRowId=${l}, which is not less than ${e.length}`);
let c = e[l];
i.push(c);
for (let u = 1; u < r; ++u) {
const h = t[u];
if (h === l)
c >= 0 && (++a, a < o ? c += s : c = -1);
else {
if (a = 0, l = h, h >= e.length)
throw new Error(`Got nextValueRowId=${h} which is not less than ${e.length}`);
c = e[h];
}
i.push(c);
}
if (i.length !== t.length)
throw new Error("Invalid row ids.");
return i;
}
calculateOutputIndex(t, e, s, o) {
const r = this.getRowPartitionTensor(t), i = this.getRowPartitionTypeByDimension(t);
switch (i) {
case tn.VALUE_ROWIDS:
return this.calculateOutputIndexValueRowID(r, e, s, o);
case tn.ROW_SPLITS:
if (r.length - 1 > e.length)
throw new Error(`Row partition size is greater than output size: ${r.length - 1} > ${e.length}`);
return this.calculateOutputIndexRowSplit(r, e, s, o);
default:
throw new Error(`Unsupported partition type: ${tn[i]}`);
}
}
getFirstDimensionSize() {
const t = this.rowPartitionValues[0];
if (this.rowPartitionTypes.length === 0)
throw new Error("No row_partition_types given.");
const e = this.rowPartitionTypes[0];
switch (e) {
case tn.FIRST_DIM_SIZE:
return t[0];
case tn.VALUE_ROWIDS:
throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");
case tn.ROW_SPLITS:
return this.rowPartitionValuesShapes[0][0] - 1;
default:
throw new Error(`Cannot handle type ${tn[e]}`);
}
}
compute() {
if (this.rowPartitionValues[0].length <= 0)
throw new Error("Invalid first partition input. Tensor requires at least one element.");
const e = this.getFirstDimensionSize(), s = this.calculateOutputSize(e), o = new Array(this.raggedRank + 1);
o[o.length - 1] = 1;
for (let l = o.length - 2; l >= 0; --l)
o[l] = o[l + 1] * s[l + 1];
const r = nf(s, !1), i = qt(this.valuesDType, G(r));
if (o[0] * s[0] > 0) {
let l = this.calculateFirstParentOutputIndex(e, o[0], s[0]);
for (let c = 1; c <= this.raggedRank; ++c)
l = this.calculateOutputIndex(c - 1, l, o[c], s[c]);
this.setOutput(this.raggedRank, l, i, r);
}
return [r, i];
}
setOutput(t, e, s, o) {
if (s.length === 0)
return;
const r = this.values, i = s;
let a = o.slice();
a = a.slice(t + 1);
const l = G(a), c = e.length;
let u = this.defaultValue;
if (u.length !== l && u.length !== 1) {
const f = this.defaultValueShape;
_(() => {
const m = A(u, f);
u = ur(m, a).dataSync();
});
}
let h = 0, d = 0, p = 0;
for (let f = 0; f <= c; ++f) {
let m = f < c ? e[f] : -1;
if (m === p) {
++p;
continue;
}
if (d < p) {
const g = r.subarray(h * l), x = i.subarray(d * l), b = (p - d) * l;
ef(x, g, b);
}
if (f >= c) {
const g = s.length;
m = Math.floor(g / l);
}
if (m > p)
if (this.defaultValue.length === 1)
i.subarray(p * l, m * l).fill(this.defaultValue[0]), p = m;
else
for (; m > p; ) {
const g = i.slice(p * l);
ef(g, u, l), ++p;
}
m < 0 ? (h = f + 1, d = p) : (h = f, d = p, p = d + 1);
}
}
}
function ef(n, t, e) {
for (let s = 0; s < e; s++)
n[s] = t[s];
}
function nf(n, t) {
const e = [];
for (let s of n) {
if (s < 0) {
if (!t)
throw new Error(`Dimension ${s} must be >= 0`);
if (s < -1)
throw new Error(`Dimension ${s} must be >= -1`);
s = -1;
}
e.push(s);
}
return e;
}
function U0(n, t, e, s, o, r, i, a, l, c) {
return new va(n, t, e, s, o, r, i, a, l, c).compute();
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function G0(n, t, e, s) {
const o = n === t, r = n < t && e < 0, i = t < n && e > 1;
if (o || r || i)
return Ce(0, s);
const a = Math.abs(Math.ceil((t - n) / e)), l = Ce(a, s);
t < n && e === 1 && (e = -1), l[0] = n;
for (let c = 1; c < l.length; c++)
l[c] = l[c - 1] + e;
return l;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const H0 = Bn((n) => 1 / Math.sqrt(n)), jE = Ns(ai, H0), XE = {
kernelName: ai,
backendName: "cpu",
kernelFunc: jE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ms(n, t, e, s, o, r, i, a, l, c) {
const u = [s / o, o], h = n.values, d = t.values;
if (s === 0)
return yt(e, t.dtype);
const p = l instanceof ge ? l : yt(u, t.dtype);
typeof l == "string" || typeof l == "number" ? p.values.fill(l) : typeof l == "boolean" && p.values.fill(+l);
for (let f = 0; f < r; f++) {
const m = [];
let g = 0;
for (let x = 0; x < i; x++) {
const b = h[f * i + x];
m.push(b), g += b * a[x];
}
if (g < 0 || g >= s / o)
throw new Error(`Invalid indices: ${m} does not index into ${e}`);
for (let x = 0; x < o; x++)
c ? p.values[g * o + x] += d[f * o + x] : p.values[g * o + x] = t.rank === 0 ? d[0] : d[f * o + x];
}
return p;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const qE = Bn((n) => 1 / (1 + Math.exp(-n))), K0 = At(di, (n) => 1 / (1 + Math.exp(-n))), YE = {
kernelName: di,
backendName: "cpu",
kernelFunc: K0
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function j0(n, t, e, s, o) {
const r = jh(s, t, e), i = G(e), a = lt(s);
if (r) {
const h = Xh(t, a);
return o === "string" ? n.slice(h, h + i) : n.subarray(h, h + i);
}
const l = o === "string" ? Yn(n) : n, c = yt(s, o, l), u = yt(e, o);
for (let h = 0; h < u.size; ++h) {
const d = u.indexToLoc(h), p = d.map((f, m) => f + t[m]);
u.set(c.get(...p), ...d);
}
return o === "string" ? qg(u.values) : u.values;
}
function Qs(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { begin: r, size: i } = s;
rt(o, "slice");
const [a, l] = Wl(o, r, i);
Hh(o, a, l);
const c = e.data.get(o.dataId).values, u = j0(c, a, l, o.shape, o.dtype);
return e.makeTensorInfo(l, o.dtype, u);
}
const JE = {
kernelName: vl,
backendName: "cpu",
kernelFunc: Qs
};
/**
* @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.
* =============================================================================
*/
function X0(n, t, e, s, o, r, i) {
const a = t[0], l = r[0], c = new Array(l), u = new Array(a), h = t[1];
if (l === 0) {
if (a !== 0)
throw new Error(Lg(a));
const g = qt(e, 0), x = qt(o, 0);
return [
g,
[0, h],
x,
c,
u
];
}
let d = !0, p = 0;
const f = new Array(l).fill(0);
for (let g = 0; g < a; ++g) {
const x = n[g * h];
if (x < 0)
throw new Error(Mg(g, x));
if (x >= l)
throw new Error(Pg(g, x, l));
++f[x], d = d && x >= p, p = x;
}
let m = !0;
for (let g = 0; g < l; ++g) {
const x = f[g] === 0;
c[g] = x, m = m && !x, f[g] = Math.max(f[g], 1), g > 0 && (f[g] += f[g - 1]);
}
if (m && d) {
const g = n, x = s;
for (let b = 0; b < a; ++b)
u[b] = b;
return [
g,
[a, h],
x,
c,
u
];
} else {
const g = f[l - 1], x = qt(e, g * h), b = qt(o, g), w = new Array(l).fill(0);
for (let y = 0; y < a; ++y) {
const C = n[y * h], $ = w[C], k = (C === 0 ? 0 : f[C - 1]) + $;
w[C]++;
for (let v = 0; v < h; ++v)
x[k * h + v] = n[y * h + v];
b[k] = s[y], u[y] = k;
}
for (let y = 0; y < l; ++y)
if (w[y] === 0) {
const $ = y === 0 ? 0 : f[y - 1];
x[$ * h + 0] = y;
for (let k = 1; k < h; ++k)
x[$ * h + k] = 0;
b[$] = i;
}
return [
x,
[g, h],
b,
c,
u
];
}
}
/**
* @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.
* =============================================================================
*/
function q0(n, t, e, s, o) {
const r = G(s), i = t[0], a = o.length, l = [];
let c = 1, u = -1;
for (let g = 0; g < a; ++g) {
const x = o[g];
if (x === -1) {
if (u !== -1)
throw new Error(zg(u, g));
u = g, l.push(1);
} else {
if (x < 0)
throw new Error(Bg(g, x));
c *= x, l.push(x);
}
}
if (u !== -1) {
if (c <= 0)
throw new Error(Vg());
const g = Math.trunc(r / c);
if (c * g !== r)
throw new Error(Wg(s, l));
l[u] = g;
}
if (G(l) !== r)
throw new Error(Ug(s, l));
const d = s.length, p = [];
if (d > 0) {
p[d - 1] = 1;
for (let g = d - 2; g >= 0; --g)
p[g] = p[g + 1] * s[g + 1];
}
const f = [];
if (a > 0) {
f[a - 1] = 1;
for (let g = a - 2; g >= 0; --g)
f[g] = f[g + 1] * l[g + 1];
}
const m = qt(e, i * a);
for (let g = 0; g < i; ++g) {
let x = 0;
for (let b = 0; b < d; ++b)
x += n[g * d + b] * p[b];
for (let b = 0; b < a; ++b)
m[g * a + b] = Math.trunc(x / f[b]), x %= f[b];
}
return [m, [i, a], l];
}
/**
* @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.
* =============================================================================
*/
function Vd(n, t, e, s, o, r = !1, i = 0) {
const a = s.length, l = [t[0], n.length / t[0]], c = l[1], h = a > 0 ? o[a - 1] + 1 : 0;
if (h < 0)
throw new Error(Yc());
const d = t.slice();
d[0] = h;
const p = d.reduce((w, y) => w * y, 1), f = qt(e, p);
if (a === 0)
return h > 0 && f.fill(i), [f, d];
if (h <= 0)
throw new Error(Yc());
let m = 0, g = 1, x = 0, b = o[m];
for (; ; ) {
let w = 0;
if (g < a) {
if (w = o[g], b === w) {
++g;
continue;
}
if (b >= w)
throw new Error(Gg());
}
if (b < 0 || b >= h)
throw new Error(Hg(b, h));
b > x && f.fill(i, x * c, b * c);
for (let y = m; y < g; ++y) {
const C = s[y];
if (C < 0 || C >= l[0])
throw new Error(Kg(y, s[y], l[0]));
for (let $ = 0; $ < c; $++)
f[b * c + $] += n[C * c + $];
}
if (r)
for (let y = 0; y < c; y++)
f[b * c + y] /= g - m;
if (m = g, ++g, x = b + 1, b = w, g > a)
break;
}
return x < h && f.fill(i, x * c, h * c), [f, d];
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ZE = Bn((n) => Math.sqrt(n)), QE = At(fi, (n) => Math.sqrt(n)), tR = {
kernelName: fi,
backendName: "cpu",
kernelFunc: QE
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Y0 = te((n, t) => {
const e = n - t;
return e * e;
}), eR = ce(mi, Y0), nR = {
kernelName: mi,
backendName: "cpu",
kernelFunc: eR
};
/**
* @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.
* =============================================================================
*/
const J0 = Bn((n, t) => {
const { pattern: e, replaceGlobal: s, rewrite: o } = t;
return n.replace(new RegExp(e, s ? "g" : ""), o);
}), sR = Ns(ah, J0), oR = {
kernelName: ah,
backendName: "cpu",
kernelFunc: sR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Z0(n, t, e, s) {
const o = yt(n, t.dtype);
for (let r = 0; r < o.size; r++) {
const i = o.indexToLoc(r), a = new Array(i.length);
for (let l = 0; l < a.length; l++)
a[l] = i[l] * e[l] + s[l];
o.set(t.get(...a), ...i);
}
return o;
}
/**
* @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.
* =============================================================================
*/
class rR {
constructor(t, e, s, o, r, i) {
this.separator = us(t), this.nGramWidths = e, this.leftPad = us(s), this.rightPad = us(o), this.padWidth = r, this.preserveShort = i;
}
getPadWidth(t) {
return Math.min(this.padWidth < 0 ? t - 1 : this.padWidth, t - 1);
}
getNumNGrams(t, e) {
const s = this.getPadWidth(e);
return Math.max(0, t + 2 * s - e + 1);
}
createNGrams(t, e, s, o, r, i) {
for (let a = 0; a < r; ++a) {
const l = this.getPadWidth(i), c = Math.max(0, l - a), u = Math.max(0, l - (r - (a + 1))), h = i - (c + u), d = e + (c > 0 ? 0 : a - l);
let p = 0;
p += c * this.leftPad.length;
for (let b = 0; b < h; ++b)
p += t[d + b].length;
p += u * this.rightPad.length;
const f = c + u + h - 1;
p += f * this.separator.length, s[o + a] = new Uint8Array(p);
const m = s[o + a];
let g = 0;
const x = (b) => b.forEach((w) => m[g++] = w);
for (let b = 0; b < c; ++b)
x(this.leftPad), x(this.separator);
for (let b = 0; b < h - 1; ++b)
x(t[d + b]), x(this.separator);
if (h > 0) {
x(t[d + h - 1]);
for (let b = 0; b < u; ++b)
x(this.separator), x(this.rightPad);
} else {
for (let b = 0; b < u - 1; ++b)
x(this.rightPad), x(this.separator);
x(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(t, e) {
const s = t.length, o = e.length;
if (o > 0) {
let l = e[0];
if (l !== 0)
throw new Error(`First split value must be 0, got ${l}`);
for (let c = 1; c < o; ++c) {
let u = e[c] >= l;
if (u = u && e[c] <= s, !u)
throw new Error(`Invalid split value ${e[c]}, must be in [${l}, ${s}]`);
l = e[c];
}
if (l !== s)
throw new Error(`Last split value must be data size. Expected ${s}, got ${l}`);
}
const r = o - 1, i = qt("int32", o);
if (s === 0 || o === 0) {
const l = new Array(s);
for (let c = 0; c <= r; ++c)
i[c] = 0;
return [l, i];
}
i[0] = 0;
for (let l = 1; l <= r; ++l) {
const c = e[l] - e[l - 1];
let u = 0;
this.nGramWidths.forEach((h) => {
u += this.getNumNGrams(c, h);
}), this.preserveShort && c > 0 && u === 0 && (u = 1), i[l] = i[l - 1] + u;
}
const a = new Array(i[r]);
for (let l = 0; l < r; ++l) {
const c = e[l];
let u = i[l];
if (this.nGramWidths.forEach((h) => {
const d = e[l + 1] - e[l], p = this.getNumNGrams(d, h);
this.createNGrams(t, c, a, u, p, h), u += p;
}), this.preserveShort && u === i[l]) {
const h = e[l + 1] - e[l];
if (h === 0)
continue;
const d = h + 2 * this.padWidth, p = 1;
this.createNGrams(t, c, a, u, p, d);
}
}
return [a, i];
}
}
function Q0(n, t, e, s, o, r, i, a) {
return new rR(e, s, o, r, i, a).compute(n, t);
}
/**
* @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.
* =============================================================================
*/
function iR(n, t, e, s) {
if (!n.length)
return;
if (t.length === 0) {
for (let r = 0; r < n.length; ++r)
s.push(n.subarray(r, r + 1));
return;
}
if (t.length === 1) {
const r = t[0];
let i = n.indexOf(r);
for (; i !== -1; ) {
const a = n.subarray(0, i);
(!e || a.length !== 0) && s.push(a), n = n.subarray(i + 1), i = n.indexOf(r);
}
(!e || n.length !== 0) && s.push(n);
return;
}
let o = 0;
for (let r = 0; r < n.length + 1; r++)
if (r === n.length || t.indexOf(n[r]) !== -1) {
const i = n.subarray(o, r);
(!e || i.length !== 0) && s.push(i), o = r + 1;
}
}
function ty(n, t, e) {
const s = n.length, o = [];
let r = 0, i = 0;
const a = new Array(s);
for (let d = 0; d < s; ++d) {
const p = o.length;
iR(n[d], t, e, o);
const f = o.length - p;
a[d] = f, r += f, i = Math.max(i, f);
}
const l = qt("int32", r * 2), c = new Array(r), u = [s, i];
let h = 0;
for (let d = 0; d < s; ++d)
for (let p = 0; p < a[d]; ++p)
l[h * 2] = d, l[h * 2 + 1] = p, c[h] = o[h], ++h;
return [l, c, u];
}
/**
* @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.
* =============================================================================
*/
function ey(n, t) {
const e = qt("int32", n.length);
for (let s = 0; s < n.length; ++s)
e[s] = ow(n[s]).modulo(t).getLowBitsUnsigned();
return e;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ny = te((n, t) => n - t), aR = Md((n, t, e, s) => ({ real: n - e, imag: t - s })), Wd = ce(gi, ny, aR), lR = {
kernelName: gi,
backendName: "cpu",
kernelFunc: Wd
};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sy(n, t) {
const e = new Array(n.rank);
for (let o = 0; o < e.length; o++)
e[o] = n.shape[o] * t[o];
const s = yt(e, n.dtype);
for (let o = 0; o < s.values.length; ++o) {
const r = s.indexToLoc(o), i = new Array(n.rank);
for (let l = 0; l < i.length; l++)
i[l] = r[l] % n.shape[l];
const a = n.locToIndex(i);
s.values[o] = n.values[a];
}
return s;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ar = (n, t) => {
const e = t.value - n.value;
return e === 0 ? n.index - t.index : e;
};
function oy(n, t, e = 0, s = n.length - 1) {
for (; s > e; ) {
if (s - e > 600) {
const a = s - e + 1, l = t - e + 1, c = Math.log(a), u = 0.5 * Math.exp(2 * c / 3), h = 0.5 * Math.sqrt(c * u * (a - u) / a) * Math.sign(l - a / 2), d = Math.max(e, Math.floor(t - l * u / a + h)), p = Math.min(s, Math.floor(t + (a - l) * u / a + h));
oy(n, t, d, p);
}
const o = n[t];
let r = e, i = s;
for (xo(n, e, t), ar(n[s], o) > 0 && xo(n, e, s); r < i; ) {
for (xo(n, r, i), r++, i--; ar(n[r], o) < 0; )
r = r + 1;
for (; ar(n[i], o) > 0; )
i = i - 1;
}
ar(n[e], o) === 0 ? xo(n, e, i) : (i = i + 1, xo(n, i, s)), i <= t && (e = i + 1), t <= i && (s = i - 1);
}
}
function ry(n, t, e, s, o) {
const r = t[t.length - 1], [i, a] = [n.length / r, r], l = we(e, i * s), c = we("int32", i * s);
for (let h = 0; h < i; h++) {
const d = h * a, p = n.subarray(d, d + a);
let f = new Array(p.length);
p.forEach((b, w) => f[w] = { value: b, index: w }), s < f.length && (oy(f, s), f = f.slice(0, s)), o && f.sort(ar);
const m = h * s, g = l.subarray(m, m + s), x = c.subarray(m, m + s);
for (let b = 0; b < s; b++)
g[b] = f[b].value, x[b] = f[b].index;
}
const u = t.slice();
return u[u.length - 1] = s, [
yt(u, e, l),
yt(u, "int32", c)
];
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function iy(n, t, e, s) {
const o = wt(t, e)[0], r = [1, e[0], 1];
for (let f = 0; f < o; f++)
r[0] *= e[f];
r[1] = e[o];
for (let f = o + 1; f < e.length; f++)
r[2] *= e[f];
const i = /* @__PURE__ */ new Map(), a = new Int32Array(e[o]), l = new ge(r, s, n), c = [], u = r[0] === 1 && r[2] === 1;
for (let f = 0; f < e[o]; f++) {
let m;
if (u)
m = n[f].toString();
else {
const x = [];
for (let b = 0; b < r[0]; b++)
for (let w = 0; w < r[2]; w++)
x.push(l.get(b, f, w));
m = x.join(",");
}
const g = i.get(m);
if (g != null)
a[f] = g;
else {
const x = i.size;
i.set(m, x), a[f] = x, c.push(f);
}
}
const h = r.slice();
h[1] = i.size;
const d = new ge(h, s);
c.forEach((f, m) => {
for (let g = 0; g < r[0]; g++)
for (let x = 0; x < r[2]; x++)
d.set(l.get(g, f, x), g, m, x);
});
const p = e.slice();
return p[o] = h[1], {
outputValues: d.values,
outputShape: p,
indices: a
};
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const cR = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
addImpl: m0,
bincountImpl: Pd,
bincountReduceImpl: g0,
bitwiseAndImpl: x0,
castImpl: f0,
ceilImpl: b0,
concatImpl: y0,
equalImpl: w0,
expImpl: $0,
expm1Impl: k0,
floorDivImpl: S0,
floorImpl: v0,
gatherNdImpl: N0,
gatherV2Impl: T0,
greaterEqualImpl: R0,
greaterImpl: E0,
lessEqualImpl: A0,
lessImpl: D0,
linSpaceImpl: F0,
logImpl: O0,
maxImpl: _0,
maximumImpl: L0,
minimumImpl: M0,
multiplyImpl: zd,
negImpl: P0,
notEqualImpl: z0,
prodImpl: B0,
raggedGatherImpl: V0,
raggedRangeImpl: W0,
raggedTensorToTensorImpl: U0,
rangeImpl: G0,
rsqrtImpl: H0,
scatterImpl: Ms,
sigmoidImpl: qE,
simpleAbsImpl: p0,
sliceImpl: j0,
sparseFillEmptyRowsImpl: X0,
sparseReshapeImpl: q0,
sparseSegmentReductionImpl: Vd,
sqrtImpl: ZE,
squaredDifferenceImpl: Y0,
staticRegexReplaceImpl: J0,
stridedSliceImpl: Z0,
stringNGramsImpl: Q0,
stringSplitImpl: ty,
stringToHashBucketFastImpl: ey,
subImpl: ny,
tileImpl: sy,
topKImpl: ry,
transposeImpl: Bd,
uniqueImpl: iy
}, Symbol.toStringTag, { value: "Module" }));
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
vm(
"cpu",
() => new nc(),
1
/* priority */
);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ay = At(zr, (n) => n >= 0 ? n : Math.exp(n) - 1), uR = {
kernelName: zr,
backendName: "cpu",
kernelFunc: ay
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ly(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { alpha: r } = s;
rt([o], "leakyRelu");
const i = G(o.shape), a = e.data.get(o.dataId).values, l = we("float32", i);
for (let c = 0; c < a.length; c++)
l[c] = a[c] < 0 ? r * a[c] : a[c];
return e.makeTensorInfo(o.shape, "float32", l);
}
const hR = {
kernelName: Qa,
backendName: "cpu",
kernelFunc: ly
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const dR = te((n, t) => n < 0 ? t * n : n);
function cy(n) {
const { inputs: t, backend: e } = n, { x: s, alpha: o } = t;
rt([s, o], "prelu");
const r = e.data.get(s.dataId).values, i = e.data.get(o.dataId).values, [a, l] = dR(s.shape, o.shape, r, i, "float32");
return e.makeTensorInfo(l, "float32", a);
}
const pR = {
kernelName: bl,
backendName: "cpu",
kernelFunc: cy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const uy = At(oi, (n) => Math.max(0, n)), fR = {
kernelName: oi,
backendName: "cpu",
kernelFunc: uy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const hy = At(ri, (n) => Math.min(Math.max(0, n), 6)), mR = {
kernelName: ri,
backendName: "cpu",
kernelFunc: hy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Sa(n, t, e, s, o) {
if (e === "linear")
return zn({ inputs: { x: t }, backend: n });
if (e === "relu")
return uy({ inputs: { x: t }, backend: n });
if (e === "elu")
return ay({ inputs: { x: t }, backend: n });
if (e === "relu6")
return hy({ inputs: { x: t }, backend: n });
if (e === "prelu")
return cy({ inputs: { x: t, alpha: s }, backend: n });
if (e === "leakyrelu")
return ly({ inputs: { x: t }, backend: n, attrs: { alpha: o } });
if (e === "sigmoid")
return K0({ inputs: { x: t }, backend: n });
throw new Error(`Activation ${e} has not been implemented for the CPU backend.`);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Bt(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { shape: r } = s, i = G(o.shape), a = Lf(r, i), l = G(a);
I(i === l, () => `The new shape (${a}) has ${l} elements and the old shape (${o.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`), e.incRef(o.dataId);
const c = e.data.get(o.dataId);
if (c.complexTensorInfos != null) {
const u = c.complexTensorInfos.real, h = c.complexTensorInfos.imag;
u.shape = a, h.shape = a;
}
return { dataId: o.dataId, shape: a, dtype: o.dtype };
}
const gR = {
kernelName: wl,
backendName: "cpu",
kernelFunc: Bt
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function dy(n) {
const { inputs: t, backend: e, attrs: s } = n, { a: o, b: r } = t, { transposeA: i, transposeB: a } = s;
rt([o, r], "matMul");
const l = o.shape.length, c = r.shape.length, u = i ? o.shape[l - 2] : o.shape[l - 1], h = a ? r.shape[c - 1] : r.shape[c - 2], d = i ? o.shape[l - 1] : o.shape[l - 2], p = a ? r.shape[c - 2] : r.shape[c - 1], f = o.shape.slice(0, -2), m = r.shape.slice(0, -2), g = G(f), x = G(m), w = mt(o.shape.slice(0, -2), r.shape.slice(0, -2)).concat([d, p]);
I(u === h, () => `Error in matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${o.shape} and ${r.shape} and transposeA=${i} and transposeB=${a} must match.`);
const y = i ? [g, u, d] : [g, d, u], C = a ? [x, p, h] : [x, h, p], $ = Bt({ inputs: { x: o }, backend: e, attrs: { shape: y } }), k = Bt({ inputs: { x: r }, backend: e, attrs: { shape: C } }), v = i ? $.shape[1] : $.shape[2], S = i ? $.shape[2] : $.shape[1], T = a ? k.shape[1] : k.shape[2], F = Math.max(g, x), L = e.data.get($.dataId).values, M = e.data.get(k.dataId).values, B = lt($.shape), z = lt(k.shape), [V, H, U] = i ? [B[0], 1, B[1]] : [B[0], B[1], 1], [K, X, q] = a ? [1, z[1], z[0]] : [z[1], 1, z[0]], Z = S * T, J = yt([F, S, T], $.dtype), et = J.values, Q = e.blockSize;
for (let ot = 0; ot < F; ot++) {
const at = ot % g, dt = ot % x;
for (let ht = 0; ht < S; ht += Q) {
const xt = Math.min(ht + Q, S);
for (let bt = 0; bt < T; bt += Q) {
const Rt = Math.min(bt + Q, T);
for (let Lt = 0; Lt < v; Lt += Q) {
const Xt = Math.min(Lt + Q, v);
for (let Mt = ht; Mt < xt; Mt++)
for (let Ft = bt; Ft < Rt; Ft++) {
let Ht = 0;
for (let Wt = Lt; Wt < Xt; Wt++) {
const Vn = (
// tslint:disable-next-line: max-line-length
L[at * V + Mt * H + Wt * U]
), fe = (
// tslint:disable-next-line: max-line-length
M[Wt * K + Ft * X + dt * q]
);
Ht += Vn * fe;
}
et[ot * Z + (Mt * T + Ft)] += Ht;
}
}
}
}
}
return e.disposeIntermediateTensorInfo($), e.disposeIntermediateTensorInfo(k), e.makeTensorInfo(w, J.dtype, J.values);
}
const xR = {
kernelName: Pa,
backendName: "cpu",
kernelFunc: dy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function bR(n) {
const { inputs: t, backend: e, attrs: s } = n, { a: o, b: r, bias: i, preluActivationWeights: a } = t, { transposeA: l, transposeB: c, activation: u, leakyreluAlpha: h } = s;
let d, p, f;
const m = [];
d = dy({ inputs: { a: o, b: r }, attrs: { transposeA: l, transposeB: c }, backend: e }), i && (p = Do({ inputs: { a: d, b: i }, backend: e }), m.push(d), d = p), u && (f = Sa(e, d, u, a, h), m.push(d), d = f);
for (const x of m)
e.disposeIntermediateTensorInfo(x);
return d;
}
const yR = {
kernelName: ia,
backendName: "cpu",
kernelFunc: bR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const wR = At(Sr, (n) => Math.acos(n)), CR = {
kernelName: Sr,
backendName: "cpu",
kernelFunc: wR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const $R = At(Nr, (n) => Math.acosh(n)), IR = {
kernelName: Nr,
backendName: "cpu",
kernelFunc: $R
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kR(n) {
const { inputs: t, backend: e } = n, s = t;
rt(t, "addN");
const o = s.map((a) => e.data.get(a.dataId).values), r = yt(s[0].shape, s[0].dtype), i = r.values;
for (let a = 0; a < s.length; a++) {
const l = o[a];
for (let c = 0; c < i.length; c++)
i[c] += l[c];
}
return e.makeTensorInfo(r.shape, r.dtype, r.values);
}
const vR = {
kernelName: Su,
backendName: "cpu",
kernelFunc: kR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function SR(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s;
rt(o, "all");
const a = wt(r, o.shape);
let l = a;
const c = jt(l, o.shape.length);
let u = o;
c != null && (u = Pe({ inputs: { x: o }, backend: e, attrs: { perm: c } }), l = Zt(l.length, o.shape.length)), be("all", l, u.shape.length);
const [h, d] = pe(u.shape, l), p = G(d), f = Ce(G(h), u.dtype), m = e.data.get(u.dataId).values;
for (let x = 0; x < f.length; ++x) {
const b = x * p;
let w = m[b];
for (let y = 0; y < p; ++y) {
const C = m[b + y];
w = w && C;
}
f[x] = w;
}
c != null && e.disposeIntermediateTensorInfo(u);
const g = e.makeTensorInfo(h, u.dtype, f);
if (i) {
const x = ne(h, a), b = Bt({ inputs: { x: g }, backend: e, attrs: { shape: x } });
return e.disposeIntermediateTensorInfo(g), b;
}
return g;
}
const NR = {
kernelName: Nu,
backendName: "cpu",
kernelFunc: SR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function TR(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s;
rt(o, "any");
const a = wt(r, o.shape);
let l = a;
const c = jt(l, o.shape.length);
let u = o;
c != null && (u = Pe({ inputs: { x: o }, backend: e, attrs: { perm: c } }), l = Zt(l.length, o.shape.length)), be("any", l, u.shape.length);
const [h, d] = pe(u.shape, l), p = G(d), f = Ce(G(h), u.dtype), m = e.data.get(u.dataId).values;
for (let x = 0; x < f.length; ++x) {
const b = x * p;
let w = m[b];
for (let y = 0; y < p; ++y) {
const C = m[b + y];
w = w || C;
}
f[x] = w;
}
c != null && e.disposeIntermediateTensorInfo(u);
const g = e.makeTensorInfo(h, u.dtype, f);
if (i) {
const x = ne(h, a), b = Bt({ inputs: { x: g }, backend: e, attrs: { shape: x } });
return e.disposeIntermediateTensorInfo(g), b;
}
return g;
}
const ER = {
kernelName: Tu,
backendName: "cpu",
kernelFunc: TR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function RR(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r } = s;
rt(o, "argMax");
let i = wt(r, o.shape);
const a = jt(i, o.shape.length);
let l = o;
const c = [];
a != null && (l = Pe({ inputs: { x: o }, backend: e, attrs: { perm: a } }), c.push(l), i = Zt(i.length, l.shape.length)), i = [i[0]], be("argMax", i, l.shape.length);
const [u, h] = pe(l.shape, i), d = G(u), p = Ce(d, "int32"), f = G(h), m = e.data.get(l.dataId).values;
for (let g = 0; g < p.length; ++g) {
const x = g * f;
let b = m[x], w = 0;
for (let y = 0; y < f; ++y) {
const C = m[x + y];
C > b && (b = C, w = y);
}
p[g] = w;
}
return c.forEach((g) => e.disposeIntermediateTensorInfo(g)), e.makeTensorInfo(u, "int32", p);
}
const DR = {
kernelName: Oa,
backendName: "cpu",
kernelFunc: RR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function AR(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r } = s;
rt(o, "argMin");
let i = wt(r, o.shape);
const a = jt(i, o.shape.length);
let l = o;
const c = [];
a != null && (l = Pe({ inputs: { x: o }, backend: e, attrs: { perm: a } }), c.push(l), i = Zt(i.length, l.shape.length)), i = [i[0]], be("argMin", i, l.shape.length);
const [u, h] = pe(l.shape, i), d = G(u), p = Ce(d, "int32"), f = G(h), m = e.data.get(l.dataId).values;
for (let g = 0; g < p.length; ++g) {
const x = g * f;
let b = m[x], w = 0;
for (let y = 0; y < f; ++y) {
const C = m[x + y];
C < b && (b = C, w = y);
}
p[g] = w;
}
return c.forEach((g) => e.disposeIntermediateTensorInfo(g)), e.makeTensorInfo(u, "int32", p);
}
const FR = {
kernelName: _a,
backendName: "cpu",
kernelFunc: AR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const OR = At(Tr, (n) => Math.asin(n)), _R = {
kernelName: Tr,
backendName: "cpu",
kernelFunc: OR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const LR = At(Er, (n) => Math.asinh(n)), MR = {
kernelName: Er,
backendName: "cpu",
kernelFunc: LR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const PR = At(Rr, (n) => Math.atan(n)), zR = {
kernelName: Rr,
backendName: "cpu",
kernelFunc: PR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const BR = te((n, t) => Math.atan2(n, t)), VR = ce(Ar, BR), WR = {
kernelName: Ar,
backendName: "cpu",
kernelFunc: VR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const UR = At(Dr, (n) => Math.atanh(n)), GR = {
kernelName: Dr,
backendName: "cpu",
kernelFunc: UR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ud(n, t, e, s, o, r) {
const i = o.strideHeight, a = o.strideWidth, l = o.dilationHeight, c = o.dilationWidth, u = o.effectiveFilterHeight, h = o.effectiveFilterWidth, d = o.padInfo.top, p = o.padInfo.left, f = r === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, m = yt(o.outShape, e), g = m.values, x = o.outShape[1] * o.outShape[2] * o.outShape[3], b = o.outShape[2] * o.outShape[3], w = o.outShape[3];
for (let y = 0; y < o.batchSize; ++y) {
const C = y * x, $ = y * s[0];
for (let k = 0; k < o.inChannels; ++k)
for (let v = 0; v < o.outHeight; ++v) {
const S = v * i - d, T = Math.max(0, S), F = Math.min(o.inHeight, u + S), L = C + v * b;
for (let M = 0; M < o.outWidth; ++M) {
const B = M * a - p, z = Math.max(0, B), V = Math.min(o.inWidth, h + B);
let H = f, U = 0, K = 0;
for (let q = T; q < F; q += l) {
const Z = $ + q * s[1];
for (let J = z; J < V; J += c) {
const et = Z + J * s[2], Q = n[et + k];
r === "max" && Q > H ? H = Q : r === "avg" && (U += Q, K++);
}
if (isNaN(H))
break;
}
const X = L + M * w + k;
g[X] = r === "avg" ? U / K : H;
}
}
}
return m;
}
function py(n, t, e, s, o = !1, r = !1) {
const i = yt(s.outShape, "int32"), a = s.strideHeight, l = s.strideWidth, c = s.dilationHeight, u = s.dilationWidth, h = s.effectiveFilterHeight, d = s.effectiveFilterWidth, p = s.padInfo.top, f = s.padInfo.left, m = yt(t, e, n);
for (let g = 0; g < s.batchSize; ++g)
for (let x = 0; x < s.inChannels; ++x)
for (let b = 0; b < s.outHeight; ++b) {
const w = b * a - p;
let y = w;
for (; y < 0; )
y += c;
const C = Math.min(s.inHeight, h + w);
for (let $ = 0; $ < s.outWidth; ++$) {
const k = $ * l - f;
let v = k;
for (; v < 0; )
v += u;
const S = Math.min(s.inWidth, d + k);
let T = Number.NEGATIVE_INFINITY, F = -1;
for (let L = y; L < C; L += c) {
const M = L - w;
for (let B = v; B < S; B += u) {
const z = B - k, V = m.get(g, L, B, x);
V > T && (T = V, o ? F = r ? ((g * s.inHeight + L) * s.inWidth + B) * s.inChannels + x : (L * s.inWidth + B) * s.inChannels + x : F = M * d + z);
}
}
i.set(F, g, b, $, x);
}
}
return i;
}
function fy(n, t, e, s, o, r) {
const i = o.strideDepth, a = o.strideHeight, l = o.strideWidth, c = o.dilationDepth, u = o.dilationHeight, h = o.dilationWidth, d = o.effectiveFilterDepth, p = o.effectiveFilterHeight, f = o.effectiveFilterWidth, m = o.padInfo.front, g = o.padInfo.top, x = o.padInfo.left, b = r === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, w = yt(o.outShape, e), y = w.values, C = o.outShape[1] * o.outShape[2] * o.outShape[3] * o.outShape[4], $ = o.outShape[2] * o.outShape[3] * o.outShape[4], k = o.outShape[3] * o.outShape[4], v = o.outShape[4];
for (let S = 0; S < o.batchSize; ++S) {
const T = S * C, F = S * s[0];
for (let L = 0; L < o.inChannels; ++L)
for (let M = 0; M < o.outDepth; ++M) {
const B = M * i - m;
let z = B;
for (; z < 0; )
z += c;
const V = Math.min(o.inDepth, d + B), H = T + M * $;
for (let U = 0; U < o.outHeight; ++U) {
const K = U * a - g;
let X = K;
for (; X < 0; )
X += u;
const q = Math.min(o.inHeight, p + K), Z = H + U * k;
for (let J = 0; J < o.outWidth; ++J) {
const et = J * l - x;
let Q = et;
for (; Q < 0; )
Q += h;
const ot = Math.min(o.inWidth, f + et), at = Z + J * v;
let dt = b, ht = 0, xt = 0;
for (let Rt = z; Rt < V; Rt += c) {
const Lt = F + Rt * s[1];
for (let Xt = X; Xt < q; Xt += u) {
const Mt = Lt + Xt * s[2];
for (let Ft = Q; Ft < ot; Ft += h) {
const Ht = Mt + Ft * s[3], Wt = n[Ht + L];
if (r === "max" && Wt > dt ? dt = Wt : r === "avg" && (ht += Wt, xt++), isNaN(dt))
break;
}
if (isNaN(dt))
break;
}
if (isNaN(dt))
break;
}
const bt = at + L;
y[bt] = r === "avg" ? ht / Math.max(xt, 1) : dt;
}
}
}
}
return w;
}
function HR(n, t) {
const e = yt(t.outShape, "int32"), s = t.strideDepth, o = t.strideHeight, r = t.strideWidth, i = t.dilationDepth, a = t.dilationHeight, l = t.dilationWidth, c = t.effectiveFilterDepth, u = t.effectiveFilterHeight, h = t.effectiveFilterWidth, d = t.padInfo.front, p = t.padInfo.top, f = t.padInfo.left;
for (let m = 0; m < t.batchSize; ++m)
for (let g = 0; g < t.inChannels; ++g)
for (let x = 0; x < t.outDepth; ++x) {
const b = x * s - d;
let w = b;
for (; w < 0; )
w += i;
const y = Math.min(t.inDepth, c + b);
for (let C = 0; C < t.outHeight; ++C) {
const $ = C * o - p;
let k = $;
for (; k < 0; )
k += a;
const v = Math.min(t.inHeight, u + $);
for (let S = 0; S < t.outWidth; ++S) {
const T = S * r - f;
let F = T;
for (; F < 0; )
F += l;
const L = Math.min(t.inWidth, h + T);
let M = Number.NEGATIVE_INFINITY, B = -1;
for (let z = w; z < y; z += i) {
const V = z - b;
for (let H = k; H < v; H += a) {
const U = H - $;
for (let K = F; K < L; K += l) {
const X = K - T, q = n.get(m, z, H, K, g);
q >= M && (M = q, B = V * u * h + U * u + X);
}
}
}
e.set(B, m, x, C, S, g);
}
}
}
return e;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function KR(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t;
rt(o, "avgPool");
const { filterSize: r, strides: i, pad: a, dimRoundingMode: l } = s, c = 1;
I(Ie(i, c), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);
const u = ln(o.shape, r, i, c, a, l);
let h;
if (u.filterWidth === 1 && u.filterHeight === 1 && Et(u.inShape, u.outShape))
h = zn({ inputs: { x: o }, backend: e });
else {
const d = e.data.get(o.dataId).values, p = lt(o.shape), f = Ud(d, o.shape, o.dtype, p, u, "avg");
h = e.makeTensorInfo(u.outShape, o.dtype, f.values);
}
return h;
}
const jR = {
kernelName: La,
backendName: "cpu",
kernelFunc: KR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function XR(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { filterSize: r, strides: i, pad: a, dimRoundingMode: l, dataFormat: c } = s;
rt(o, "avgPool3d");
const u = Zn(o.shape, r, i, 1, a, l, c), h = e.data.get(o.dataId).values, d = fy(h, o.shape, o.dtype, lt(o.shape), u, "avg");
return e.makeTensorInfo(d.shape, "float32", d.values);
}
const qR = {
kernelName: Ma,
backendName: "cpu",
kernelFunc: XR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function YR(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, input: r } = t, { filterSize: i, strides: a, pad: l, dimRoundingMode: c } = s;
rt([o, r], "avgPool3DGrad");
const u = Zn(r.shape, i, a, 1, l, c), h = u.strideDepth, d = u.strideHeight, p = u.strideWidth, f = u.filterDepth, m = u.filterHeight, g = u.filterWidth, x = u.dilationDepth, b = u.dilationHeight, w = u.dilationWidth, y = u.effectiveFilterDepth, C = u.effectiveFilterHeight, $ = u.effectiveFilterWidth, k = y - 1 - u.padInfo.front, v = $ - 1 - u.padInfo.left, S = C - 1 - u.padInfo.top, T = yt(r.shape, "float32"), F = 1 / (f * m * g), L = e.bufferSync(o);
for (let M = 0; M < u.batchSize; ++M)
for (let B = 0; B < u.inChannels; ++B)
for (let z = 0; z < u.inDepth; ++z)
for (let V = 0; V < u.inHeight; ++V)
for (let H = 0; H < u.inWidth; ++H) {
const U = z - k, K = V - S, X = H - v;
let q = 0;
for (let Z = 0; Z < y; Z += x) {
const J = (U + Z) / h;
if (!(J < 0 || J >= u.outDepth || Math.floor(J) !== J))
for (let et = 0; et < C; et += b) {
const Q = (K + et) / d;
if (!(Q < 0 || Q >= u.outHeight || Math.floor(Q) !== Q))
for (let ot = 0; ot < $; ot += w) {
const at = (X + ot) / p;
if (at < 0 || at >= u.outWidth || Math.floor(at) !== at)
continue;
const dt = L.get(M, J, Q, at, B);
q += dt;
}
}
}
T.set(q * F, M, z, V, H, B);
}
return e.makeTensorInfo(T.shape, T.dtype, T.values);
}
const JR = {
kernelName: Ru,
backendName: "cpu",
kernelFunc: YR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ZR(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, input: r } = t, i = r;
rt([o, r], "avgPoolGrad");
const { filterSize: a, strides: l, pad: c } = s, u = ln(i.shape, a, l, 1, c), h = u.strideHeight, d = u.strideWidth, p = u.filterHeight, f = u.filterWidth, m = u.dilationHeight, g = u.dilationWidth, x = u.effectiveFilterHeight, b = u.effectiveFilterWidth, w = b - 1 - u.padInfo.left, y = x - 1 - u.padInfo.top, C = yt(i.shape, "float32"), $ = 1 / (p * f), k = e.data.get(o.dataId).values, v = yt(o.shape, "float32", k);
for (let S = 0; S < u.batchSize; ++S)
for (let T = 0; T < u.inChannels; ++T)
for (let F = 0; F < u.inHeight; ++F)
for (let L = 0; L < u.inWidth; ++L) {
const M = F - y, B = L - w;
let z = 0;
for (let V = 0; V < x; V += m) {
const H = (M + V) / h;
if (!(H < 0 || H >= u.outHeight || Math.floor(H) !== H))
for (let U = 0; U < b; U += g) {
const K = (B + U) / d;
if (K < 0 || K >= u.outWidth || Math.floor(K) !== K)
continue;
const X = v.get(S, H, K, T);
z += X;
}
}
C.set(z * $, S, F, L, T);
}
return e.makeTensorInfo(C.shape, C.dtype, C.values);
}
const QR = {
kernelName: Eu,
backendName: "cpu",
kernelFunc: ZR
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function tD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, scale: r, offset: i, mean: a, variance: l } = t;
I(a.shape.length === l.shape.length, () => "Batch normalization gradient requires mean and variance to have equal ranks."), I(i == null || a.shape.length === i.shape.length, () => "Batch normalization gradient requires mean and offset to have equal ranks."), I(r == null || a.shape.length === r.shape.length, () => "Batch normalization gradient requires mean and scale to have equal ranks."), rt([o, a, l, r, i], "batchNorm");
let { varianceEpsilon: c } = s;
c == null && (c = 1e-3);
const u = e.data.get(o.dataId).values, h = e.data.get(a.dataId).values, d = e.data.get(l.dataId).values, p = r ? e.data.get(r.dataId).values : new Float32Array([1]), f = i ? e.data.get(i.dataId).values : new Float32Array([0]), m = new Float32Array(u.length), g = f.length, x = p.length, b = d.length, w = h.length;
let y = 0, C = 0, $ = 0, k = 0;
for (let v = 0; v < u.length; ++v)
m[v] = f[y++] + (u[v] - h[C++]) * p[$++] / Math.sqrt(d[k++] + c), y >= g && (y = 0), C >= w && (C = 0), $ >= x && ($ = 0), k >= b && (k = 0);
return e.makeTensorInfo(o.shape, o.dtype, m);
}
const eD = {
kernelName: Ya,
backendName: "cpu",
kernelFunc: tD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { blockShape: r, crops: i } = s;
rt([o], "batchToSpaceND");
const a = r.reduce((x, b) => x * b), l = Si(o.shape, r, a), c = Ni(l.length, r.length), u = Ti(o.shape, r, a), h = Qh(i, r.length), d = td(u, i, r.length), p = Bt({ inputs: { x: o }, backend: e, attrs: { shape: l } }), f = Pe({ inputs: { x: p }, backend: e, attrs: { perm: c } }), m = Bt({ inputs: { x: f }, backend: e, attrs: { shape: u } }), g = Qs({
inputs: { x: m },
backend: e,
attrs: { begin: h, size: d }
});
return e.disposeIntermediateTensorInfo(p), e.disposeIntermediateTensorInfo(f), e.disposeIntermediateTensorInfo(m), g;
}
const sD = {
kernelName: za,
backendName: "cpu",
kernelFunc: nD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function oD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, weights: r } = t, { size: i } = s, a = e.data.get(o.dataId).values, l = e.data.get(r.dataId).values, c = Pd(a, l, r.dtype, r.shape, i);
return e.makeTensorInfo([i], r.dtype, c);
}
const rD = {
kernelName: Du,
backendName: "cpu",
kernelFunc: oD
};
/**
* @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.
* =============================================================================
*/
function iD(n) {
const { inputs: t, backend: e } = n, { s0: s, s1: o } = t, r = e.data.get(s.dataId).values, i = e.data.get(o.dataId).values, a = mt(Array.from(r), Array.from(i));
return e.makeTensorInfo([a.length], "int32", Int32Array.from(a));
}
const aD = {
kernelName: Wf,
backendName: "cpu",
kernelFunc: iD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const lD = At(_r, (n, t) => {
const e = t;
return n > e.clipValueMax ? e.clipValueMax : n < e.clipValueMin ? e.clipValueMin : n;
}), cD = {
kernelName: _r,
backendName: "cpu",
kernelFunc: lD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const uD = (n) => {
const { x: t } = n.inputs, e = n.backend, s = new Float32Array(G(t.shape)), o = e.data.get(t.dataId), r = o.complexTensorInfos.real, i = o.complexTensorInfos.imag, a = e.data.get(r.dataId).values, l = e.data.get(i.dataId).values;
for (let c = 0; c < a.length; c++) {
const u = a[c], h = l[c];
s[c] = Math.hypot(u, h);
}
return e.makeOutput(s, t.shape, "float32");
}, hD = {
kernelName: Ba,
backendName: "cpu",
kernelFunc: uD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ao(n) {
const { inputs: t, backend: e } = n, { input: s } = t, o = e.data.get(s.dataId).complexTensorInfos.imag, r = e.data.get(o.dataId).values;
return e.makeTensorInfo(o.shape, o.dtype, r);
}
const dD = {
kernelName: qu,
backendName: "cpu",
kernelFunc: Ao
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Fo(n) {
const { inputs: t, backend: e, attrs: s } = n, { axis: o } = s, r = wt(o, t[0].shape)[0], i = t.map((m) => m.shape);
Yh(i, r);
let a = An(t.map((m) => m.shape), r);
if (G(a) === 0)
return e.makeTensorInfo(a, t[0].dtype, []);
const l = t.filter((m) => G(m.shape) > 0);
if (l.length === 1)
return zn({ inputs: { x: l[0] }, backend: e });
if (l[0].dtype === "complex64") {
const m = l.map((y) => Zs({ inputs: { input: y }, backend: e })), g = l.map((y) => Ao({ inputs: { input: y }, backend: e })), x = Fo({ inputs: m, backend: e, attrs: { axis: r } }), b = Fo({ inputs: g, backend: e, attrs: { axis: r } }), w = Ve({ inputs: { real: x, imag: b }, backend: e });
return m.forEach((y) => e.disposeIntermediateTensorInfo(y)), g.forEach((y) => e.disposeIntermediateTensorInfo(y)), e.disposeIntermediateTensorInfo(x), e.disposeIntermediateTensorInfo(b), w;
}
const c = l.map((m) => {
const x = [-1, G(m.shape.slice(r))];
return Bt({ inputs: { x: m }, backend: e, attrs: { shape: x } });
}), u = c.map((m) => ({ vals: e.data.get(m.dataId).values, shape: m.shape }));
a = An(
c.map((m) => m.shape),
1
/* axis */
);
const h = c[0].shape[0] === 1, d = y0(u, a, t[0].dtype, h), p = An(l.map((m) => m.shape), r), f = e.makeTensorInfo(p, t[0].dtype, d);
return c.forEach((m) => e.disposeIntermediateTensorInfo(m)), f;
}
const pD = {
kernelName: Va,
backendName: "cpu",
kernelFunc: Fo
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function my(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r } = t, { strides: i, pad: a, dataFormat: l, dilations: c, dimRoundingMode: u } = s;
rt([o, r], "conv2d");
const h = Qn(l), d = xe(o.shape, r.shape, i, c, a, u, !1, h), p = d.filterHeight, f = d.filterWidth, m = d.dilationHeight, g = d.dilationWidth, x = d.padInfo.left, b = d.padInfo.top, w = d.dataFormat === "channelsLast", y = new ge(d.outShape, o.dtype), C = lt(o.shape), $ = lt(r.shape), k = C[0], v = w ? C[1] : C[2], S = w ? C[2] : 1, T = w ? 1 : C[1], F = y.strides[0], L = w ? y.strides[1] : y.strides[2], M = w ? y.strides[2] : 1, B = w ? 1 : y.strides[1], z = e.data.get(o.dataId).values, V = e.data.get(r.dataId).values, H = y.values;
for (let U = 0; U < d.batchSize; ++U) {
const K = U * k, X = U * F;
for (let q = 0; q < d.outHeight; ++q) {
const Z = X + q * L, J = q * d.strideHeight - b;
for (let et = 0; et < p; ++et) {
const Q = J + et * m;
if (Q < 0 || Q >= d.inHeight)
continue;
const ot = et * $[0], at = K + Q * v;
for (let dt = 0; dt < d.outWidth; ++dt) {
const ht = Z + dt * M, xt = dt * d.strideWidth - x;
for (let bt = 0; bt < f; ++bt) {
const Rt = xt + bt * g;
if (Rt < 0 || Rt >= d.inWidth)
continue;
const Lt = ot + bt * $[1], Xt = at + Rt * S;
let Mt = Lt;
for (let Ft = 0; Ft < d.inChannels; ++Ft) {
const Ht = z[Xt + Ft * T];
for (let Wt = 0; Wt < d.outChannels; ++Wt)
H[ht + Wt * B] += Ht * V[Mt + Wt];
Mt += d.outChannels;
}
}
}
}
}
}
return e.makeTensorInfo(y.shape, y.dtype, H);
}
const fD = {
kernelName: Wa,
backendName: "cpu",
kernelFunc: my
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function mD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, dy: r } = t, { strides: i, pad: a, dataFormat: l, dimRoundingMode: c, filterShape: u } = s;
rt([o, r], "conv2dBackpropFilter");
const h = Qn(l), d = xe(o.shape, u, i, 1, a, c, !1, h), { strideHeight: p, strideWidth: f, filterHeight: m, filterWidth: g } = d, x = d.dataFormat === "channelsLast", b = new ge(d.filterShape, "float32"), w = d.padInfo.left, y = d.padInfo.top, C = e.data.get(o.dataId).values, $ = e.data.get(r.dataId).values, k = new ge(o.shape, o.dtype, C), v = new ge(r.shape, r.dtype, $);
for (let S = 0; S < m; ++S) {
const T = Math.max(0, Math.ceil((y - S) / p)), F = Math.min(d.outHeight, (d.inHeight + y - S) / p);
for (let L = 0; L < g; ++L) {
const M = Math.max(0, Math.ceil((w - L) / f)), B = Math.min(d.outWidth, (d.inWidth + w - L) / f);
for (let z = 0; z < d.inChannels; ++z)
for (let V = 0; V < d.outChannels; ++V) {
let H = 0;
for (let U = 0; U < d.batchSize; ++U)
for (let K = T; K < F; ++K) {
const X = S + K * p - y;
for (let q = M; q < B; ++q) {
const Z = L + q * f - w;
x ? H += k.get(U, X, Z, z) * v.get(U, K, q, V) : H += k.get(U, z, X, Z) * v.get(U, V, K, q);
}
}
b.set(H, S, L, z, V);
}
}
}
return e.makeTensorInfo(b.shape, b.dtype, b.values);
}
const gD = {
kernelName: Ou,
backendName: "cpu",
kernelFunc: mD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function xD(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, filter: r } = t, { inputShape: i, strides: a, pad: l, dataFormat: c, dimRoundingMode: u } = s;
rt([o, r], "conv2dBackpropInput");
const h = lt(r.shape), d = lt(o.shape);
let p = Qn(c);
const f = xe(i, r.shape, a, 1, l, u, !1, p), m = new ge(f.inShape, "float32"), g = m.values, x = e.data.get(o.dataId).values, b = e.data.get(r.dataId).values, [w, y, C] = h, { batchSize: $, filterHeight: k, filterWidth: v, inChannels: S, inHeight: T, inWidth: F, outChannels: L, outHeight: M, outWidth: B, strideHeight: z, strideWidth: V } = f;
p = f.dataFormat;
const H = k - 1 - f.padInfo.top, U = v - 1 - f.padInfo.left, K = p === "channelsLast", X = m.strides[0], q = K ? m.strides[1] : m.strides[2], Z = K ? m.strides[2] : 1, J = K ? 1 : m.strides[1], et = d[0], Q = K ? d[1] : d[2], ot = K ? d[2] : 1, at = K ? 1 : d[1];
for (let dt = 0; dt < $; ++dt)
for (let ht = 0; ht < S; ++ht)
for (let xt = 0; xt < T; ++xt) {
const bt = xt - H, Rt = Math.max(0, Math.ceil(bt / z)), Lt = Math.min(M, (k + bt) / z);
for (let Xt = 0; Xt < F; ++Xt) {
const Mt = Xt - U, Ft = Math.max(0, Math.ceil(Mt / V)), Ht = Math.min(B, (v + Mt) / V);
let Wt = 0;
for (let fe = Rt; fe < Lt; ++fe) {
const es = fe * z - bt;
for (let Ke = Ft; Ke < Ht; ++Ke) {
const Es = Ke * V - Mt, hn = et * dt + Q * fe + ot * Ke, Wn = w * (k - 1 - es) + y * (v - 1 - Es) + C * ht;
for (let ns = 0; ns < L; ++ns) {
const ss = x[hn + at * ns], os = b[Wn + ns];
Wt += ss * os;
}
}
}
const Vn = X * dt + q * xt + Z * Xt + J * ht;
g[Vn] = Wt;
}
}
return e.makeTensorInfo(m.shape, m.dtype, m.values);
}
const bD = {
kernelName: Ua,
backendName: "cpu",
kernelFunc: xD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r } = t, { strides: i, pad: a, dilations: l } = s;
rt([o, r], "conv3d");
const c = Cs(o.shape, r.shape, i, l, a), { filterDepth: u, filterHeight: h, filterWidth: d, dilationDepth: p, dilationHeight: f, dilationWidth: m, padInfo: g } = c, x = g.front, b = g.left, w = g.top, y = new ge(c.outShape, o.dtype), C = e.data.get(o.dataId).values, $ = e.data.get(r.dataId).values, k = y.values, v = lt(o.shape), S = lt(r.shape);
for (let T = 0; T < c.batchSize; ++T) {
const F = T * v[0], L = T * y.strides[0];
for (let M = 0; M < c.outDepth; ++M) {
const B = L + M * y.strides[1], z = M * c.strideDepth - x;
for (let V = 0; V < u; ++V) {
const H = z + V * p;
if (H < 0 || H >= c.inDepth)
continue;
const U = V * S[0], K = F + H * v[1];
for (let X = 0; X < c.outHeight; ++X) {
const q = B + X * y.strides[2], Z = X * c.strideHeight - w;
for (let J = 0; J < h; ++J) {
const et = Z + J * f;
if (et < 0 || et >= c.inHeight)
continue;
const Q = U + J * S[1], ot = K + et * v[2];
for (let at = 0; at < c.outWidth; ++at) {
const dt = q + at * c.outChannels, ht = at * c.strideWidth - b;
for (let xt = 0; xt < d; ++xt) {
const bt = ht + xt * m;
if (bt < 0 || bt >= c.inWidth)
continue;
const Rt = Q + xt * S[2], Lt = ot + bt * c.inChannels;
let Xt = Rt;
for (let Mt = 0; Mt < c.inChannels; ++Mt) {
const Ft = C[Lt + Mt];
for (let Ht = 0; Ht < c.outChannels; ++Ht)
k[dt + Ht] += Ft * $[Xt + Ht];
Xt += c.outChannels;
}
}
}
}
}
}
}
}
return e.makeTensorInfo(y.shape, y.dtype, y.values);
}
const wD = {
kernelName: Ga,
backendName: "cpu",
kernelFunc: yD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function CD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, dy: r } = t, { strides: i, pad: a, filterShape: l } = s;
rt([o, r], "conv3dBackpropFilterV2");
const c = lt(o.shape), u = lt(r.shape), h = Cs(o.shape, l, i, 1, a), d = h.strideDepth, p = h.strideHeight, f = h.strideWidth, m = h.filterDepth, g = h.filterHeight, x = h.filterWidth, b = new ge(h.filterShape, "float32"), w = b.values, [y, C, $, k] = b.strides, v = e.data.get(r.dataId).values, [S, T, F, L] = u, M = e.data.get(o.dataId).values, [B, z, V, H] = c, U = h.padInfo.front, K = h.padInfo.left, X = h.padInfo.top;
for (let q = 0; q < m; ++q) {
const Z = Math.max(0, Math.ceil((U - q) / d)), J = Math.min(h.outDepth, (h.inDepth + U - q) / d), et = q * y;
for (let Q = 0; Q < g; ++Q) {
const ot = Math.max(0, Math.ceil((X - Q) / p)), at = Math.min(h.outHeight, (h.inHeight + X - Q) / p), dt = Q * C + et;
for (let ht = 0; ht < x; ++ht) {
const xt = Math.max(0, Math.ceil((K - ht) / f)), bt = Math.min(h.outWidth, (h.inWidth + K - ht) / f), Rt = ht * $ + dt;
for (let Lt = 0; Lt < h.inChannels; ++Lt) {
const Xt = Lt * k + Rt;
for (let Mt = 0; Mt < h.outChannels; ++Mt) {
let Ft = 0;
for (let Ht = 0; Ht < h.batchSize; ++Ht) {
const Wt = Ht * B, Vn = Ht * S;
for (let fe = Z; fe < J; ++fe) {
const Ke = (q + fe * d - U) * z + Wt, Es = fe * T + Vn;
for (let hn = ot; hn < at; ++hn) {
const ns = (Q + hn * p - X) * V + Ke, ss = hn * F + Es;
for (let os = xt; os < bt; ++os) {
const cc = (ht + os * f - K) * H + ns, uc = os * L + ss;
Ft += M[cc + Lt] * v[uc + Mt];
}
}
}
}
w[Xt + Mt] = Ft;
}
}
}
}
}
return e.makeTensorInfo(b.shape, b.dtype, b.values);
}
const $D = {
kernelName: _u,
backendName: "cpu",
kernelFunc: CD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ID(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, filter: r } = t, { pad: i, strides: a, inputShape: l } = s;
rt([o], "conv3dBackpropInputV2");
const c = lt(o.shape), u = lt(r.shape), h = Cs(l, r.shape, a, 1, i), d = new ge(h.inShape, "float32"), p = d.values, [f, m, g, x] = d.strides, b = e.data.get(o.dataId).values, [w, y, C, $] = c, k = e.data.get(r.dataId).values, [v, S, T, F] = u, { batchSize: L, filterDepth: M, filterHeight: B, filterWidth: z, inChannels: V, inDepth: H, inHeight: U, inWidth: K, outChannels: X, outDepth: q, outHeight: Z, outWidth: J, strideDepth: et, strideHeight: Q, strideWidth: ot } = h, at = M - 1 - h.padInfo.front, dt = B - 1 - h.padInfo.top, ht = z - 1 - h.padInfo.left;
for (let xt = 0; xt < L; ++xt)
for (let bt = 0; bt < V; ++bt)
for (let Rt = 0; Rt < H; ++Rt) {
const Lt = Rt - at, Xt = Math.max(0, Math.ceil(Lt / et)), Mt = Math.min(q, (M + Lt) / et);
for (let Ft = 0; Ft < U; ++Ft) {
const Ht = Ft - dt, Wt = Math.max(0, Math.ceil(Ht / Q)), Vn = Math.min(Z, (B + Ht) / Q);
for (let fe = 0; fe < K; ++fe) {
const es = fe - ht, Ke = Math.max(0, Math.ceil(es / ot)), Es = Math.min(J, (z + es) / ot);
let hn = 0;
for (let Wn = Xt; Wn < Mt; ++Wn) {
const ns = Wn * et - Lt;
for (let ss = Wt; ss < Vn; ++ss) {
const os = ss * Q - Ht;
for (let Qo = Ke; Qo < Es; ++Qo) {
const cc = Qo * ot - es, uc = w * xt + y * Wn + C * ss + $ * Qo, f1 = v * (M - 1 - ns) + S * (B - 1 - os) + T * (z - 1 - cc) + F * bt;
for (let Ui = 0; Ui < X; ++Ui) {
const m1 = b[uc + Ui], g1 = k[f1 + Ui];
hn += m1 * g1;
}
}
}
}
p[f * xt + m * Rt + g * Ft + x * fe + bt] = hn;
}
}
}
return e.makeTensorInfo(d.shape, d.dtype, d.values);
}
const kD = {
kernelName: Lu,
backendName: "cpu",
kernelFunc: ID
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const vD = At(Lr, (n) => Math.cos(n)), SD = {
kernelName: Lr,
backendName: "cpu",
kernelFunc: vD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ND = At(Mr, (n) => Math.cosh(n)), TD = {
kernelName: Mr,
backendName: "cpu",
kernelFunc: ND
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ED(n) {
const { inputs: t, backend: e, attrs: s } = n, { image: o, boxes: r, boxInd: i } = t, { cropSize: a, method: l, extrapolationValue: c } = s, [u, h, d, p] = o.shape, f = r.shape[0], [m, g] = a, x = yt([f, m, g, p], "float32"), b = e.data.get(r.dataId).values, w = e.data.get(i.dataId).values, y = e.data.get(o.dataId).values, C = lt(o.shape), $ = lt(x.shape);
for (let k = 0; k < f; k++) {
const v = k * 4, S = b[v], T = b[v + 1], F = b[v + 2], L = b[v + 3], M = w[k];
if (M >= u)
continue;
const B = m > 1 ? (F - S) * (h - 1) / (m - 1) : 0, z = g > 1 ? (L - T) * (d - 1) / (g - 1) : 0;
for (let V = 0; V < m; V++) {
const H = m > 1 ? S * (h - 1) + V * B : 0.5 * (S + F) * (h - 1);
if (H < 0 || H > h - 1) {
for (let U = 0; U < g; U++)
for (let K = 0; K < p; K++) {
const X = K + U * $[2] + V * $[1] + k * $[0];
x.values[X] = c;
}
continue;
}
if (l === "bilinear") {
const U = Math.floor(H), K = Math.ceil(H), X = H - U;
for (let q = 0; q < g; q++) {
const Z = g > 1 ? T * (d - 1) + q * z : 0.5 * (T + L) * (d - 1);
if (Z < 0 || Z > d - 1) {
for (let ot = 0; ot < p; ot++) {
const at = ot + q * $[2] + V * $[1] + k * $[0];
x.values[at] = c;
}
continue;
}
const J = Math.floor(Z), et = Math.ceil(Z), Q = Z - J;
for (let ot = 0; ot < p; ot++) {
let at = ot + J * C[2] + U * C[1] + M * C[0];
const dt = y[at];
at = ot + et * C[2] + U * C[1] + M * C[0];
const ht = y[at];
at = ot + J * C[2] + K * C[1] + M * C[0];
const xt = y[at];
at = ot + et * C[2] + K * C[1] + M * C[0];
const bt = y[at], Rt = dt + (ht - dt) * Q, Lt = xt + (bt - xt) * Q;
at = ot + q * $[2] + V * $[1] + k * $[0], x.values[at] = Rt + (Lt - Rt) * X;
}
}
} else
for (let U = 0; U < g; ++U) {
const K = g > 1 ? T * (d - 1) + U * z : 0.5 * (T + L) * (d - 1);
if (K < 0 || K > d - 1) {
for (let Z = 0; Z < p; Z++) {
const J = Z + U * $[2] + V * $[1] + k * $[0];
x.values[J] = c;
}
continue;
}
const X = Math.round(K), q = Math.round(H);
for (let Z = 0; Z < p; Z++) {
const J = Z + X * C[2] + q * C[1] + M * C[0], et = Z + U * $[2] + V * $[1] + k * $[0];
x.values[et] = y[J];
}
}
}
}
return e.makeTensorInfo(x.shape, x.dtype, x.values);
}
const RD = {
kernelName: Pu,
backendName: "cpu",
kernelFunc: ED
};
/**
* @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.
* =============================================================================
*/
function DD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, exclusive: i, reverse: a } = s;
rt(o, "cumprod");
const l = jt([r], o.shape.length);
let c = o;
l != null && (c = Pe({ inputs: { x: o }, backend: e, attrs: { perm: l } }));
const u = Zt(1, o.shape.length)[0];
if (u !== c.shape.length - 1)
throw new Error(`backend.cumprod in CPU expects an inner-most axis=${c.shape.length - 1} but got axis=${u}`);
const h = Ue(c.dtype, "int32"), d = Iu(G(c.shape), h), p = e.data.get(c.dataId).values, f = c.shape[c.shape.length - 1], m = a ? (x, b) => x + f - b - 1 : (x, b) => x + b;
for (let x = 0; x < p.length; x += f)
for (let b = 0; b < f; b++) {
const w = m(x, b);
if (b === 0)
d[w] = i ? 1 : p[w];
else {
const y = m(x, b - 1);
d[w] = i ? p[y] * d[y] : p[w] * d[y];
}
}
const g = e.makeTensorInfo(c.shape, h, d);
if (l != null) {
const x = $s(l), b = Pe({ inputs: { x: g }, backend: e, attrs: { perm: x } });
return e.disposeIntermediateTensorInfo(g), e.disposeIntermediateTensorInfo(c), b;
}
return g;
}
const AD = {
kernelName: Mu,
backendName: "cpu",
kernelFunc: DD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function FD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, exclusive: i, reverse: a } = s;
rt(o, "cumsum");
const l = jt([r], o.shape.length);
let c = o;
l != null && (c = Pe({ inputs: { x: o }, backend: e, attrs: { perm: l } }));
const u = Zt(1, o.shape.length)[0];
if (u !== c.shape.length - 1)
throw new Error(`backend.cumsum in CPU expects an inner-most axis=${c.shape.length - 1} but got axis=${u}`);
const h = Ue(c.dtype, "int32"), d = Ce(G(c.shape), h), p = e.data.get(c.dataId).values, f = c.shape[c.shape.length - 1], m = a ? (x, b) => x + f - b - 1 : (x, b) => x + b;
for (let x = 0; x < p.length; x += f)
for (let b = 0; b < f; b++) {
const w = m(x, b);
if (b === 0)
d[w] = i ? 0 : p[w];
else {
const y = m(x, b - 1);
d[w] = i ? p[y] + d[y] : p[w] + d[y];
}
}
const g = e.makeTensorInfo(c.shape, h, d);
if (l != null) {
const x = $s(l), b = Pe({ inputs: { x: g }, backend: e, attrs: { perm: x } });
return e.disposeIntermediateTensorInfo(g), e.disposeIntermediateTensorInfo(c), b;
}
return g;
}
const OD = {
kernelName: Ha,
backendName: "cpu",
kernelFunc: FD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _D(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, weights: r } = t, { size: i, binaryOutput: a } = s;
if (o.shape.length === 1) {
const l = e.data.get(o.dataId).values, c = e.data.get(r.dataId).values, u = Pd(l, c, r.dtype, r.shape, i);
return e.makeTensorInfo([i], r.dtype, u);
} else if (o.shape.length === 2) {
const l = e.bufferSync(o), c = e.bufferSync(r), u = g0(l, c, i, a);
return e.makeTensorInfo(u.shape, r.dtype, u.values);
}
throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`);
}
const LD = {
kernelName: zu,
backendName: "cpu",
kernelFunc: _D
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function MD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { blockSize: r, dataFormat: i } = s;
I(i === "NHWC", () => `Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);
const a = o.shape[0], l = o.shape[1], c = o.shape[2], u = o.shape[3], h = l * r, d = c * r, p = u / (r * r), f = e.data.get(o.dataId).values, m = new Float32Array(a * h * d * p);
let g = 0;
for (let x = 0; x < a; ++x)
for (let b = 0; b < h; ++b) {
const w = Math.floor(b / r), y = b % r;
for (let C = 0; C < d; ++C) {
const $ = Math.floor(C / r), k = C % r, v = (y * r + k) * p;
for (let S = 0; S < p; ++S) {
const F = S + v + u * ($ + c * (w + l * x));
m[g++] = f[F];
}
}
}
return e.makeTensorInfo([a, h, d, p], o.dtype, m);
}
const PD = {
kernelName: Bu,
backendName: "cpu",
kernelFunc: MD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function gy(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r } = t, { strides: i, pad: a, dilations: l, dimRoundingMode: c } = s;
rt([o, r], "depthwiseConv2DNative");
const u = lt(o.shape), h = lt(r.shape);
let d = l;
d == null && (d = [1, 1]), I(Ie(i, d), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);
const p = xe(
o.shape,
r.shape,
i,
d,
a,
c,
!0
/* depthwise */
), { filterHeight: f, filterWidth: m, dilationHeight: g, dilationWidth: x, padInfo: b } = p, w = b.left, y = b.top, C = p.outChannels / p.inChannels, $ = new ge(p.outShape, o.dtype), k = e.data.get(o.dataId).values, v = e.data.get(r.dataId).values, S = $.values;
for (let T = 0; T < p.batchSize; ++T) {
const F = T * u[0], L = T * $.strides[0];
for (let M = 0; M < p.outHeight; ++M) {
const B = L + M * $.strides[1], z = M * p.strideHeight - y;
for (let V = 0; V < f; ++V) {
const H = z + V * g;
if (H < 0 || H >= p.inHeight)
continue;
const U = V * h[0], K = F + H * u[1];
for (let X = 0; X < p.outWidth; ++X) {
const q = B + X * $.strides[2], Z = X * p.strideWidth - w;
for (let J = 0; J < m; ++J) {
const et = Z + J * x;
if (et < 0 || et >= p.inWidth)
continue;
const Q = U + J * h[1], ot = K + et * p.inChannels;
let at = q, dt = Q;
for (let ht = 0; ht < p.inChannels; ++ht) {
const xt = k[ot + ht];
for (let bt = 0; bt < C; ++bt)
S[at + bt] += xt * v[dt + bt];
at += C, dt += C;
}
}
}
}
}
}
return e.makeTensorInfo($.shape, $.dtype, $.values);
}
const zD = {
kernelName: Ka,
backendName: "cpu",
kernelFunc: gy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function BD(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, dy: r } = t, { strides: i, dilations: a, pad: l, dimRoundingMode: c, filterShape: u } = s;
rt([o, r], "depthwiseConv2dNativeBackpropFilter");
const h = xe(
o.shape,
u,
i,
a,
l,
c,
!0
/* depthwise */
), { strideHeight: d, strideWidth: p, filterHeight: f, filterWidth: m } = h, g = new ge(h.filterShape, "float32"), x = h.padInfo.left, b = h.padInfo.top, w = h.outChannels / h.inChannels, y = e.data.get(o.dataId).values, C = new ge(o.shape, o.dtype, y), $ = e.data.get(r.dataId).values, k = new ge(r.shape, r.dtype, $);
for (let v = 0; v < f; ++v) {
const S = Math.max(0, Math.ceil((b - v) / d)), T = Math.min(h.outHeight, (h.inHeight + b - v) / d);
for (let F = 0; F < m; ++F) {
const L = Math.max(0, Math.ceil((x - F) / p)), M = Math.min(h.outWidth, (h.inWidth + x - F) / p);
for (let B = 0; B < h.outChannels; ++B) {
const z = Math.trunc(B / w), V = B % w;
let H = 0;
for (let U = 0; U < h.batchSize; ++U)
for (let K = S; K < T; ++K) {
const X = v + K * d - b;
for (let q = L; q < M; ++q) {
const Z = F + q * p - x;
H += C.get(U, X, Z, z) * k.get(U, K, q, B);
}
}
g.set(H, v, F, z, V);
}
}
}
return e.makeTensorInfo(g.shape, g.dtype, g.values);
}
const VD = {
kernelName: Vu,
backendName: "cpu",
kernelFunc: BD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function WD(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, filter: r } = t, { strides: i, dilations: a, pad: l, dimRoundingMode: c, inputShape: u } = s;
rt([o, r], "depthwiseConv2DNativeBackpropInput");
const h = lt(o.shape), d = lt(r.shape), p = xe(
u,
r.shape,
i,
a,
l,
c,
!0
/* depthwise */
), f = new ge(p.inShape, "float32"), m = f.values, [g, x, b] = f.strides, w = e.data.get(o.dataId).values, [y, C, $] = h, k = e.data.get(r.dataId).values, [v, S, T] = d, { batchSize: F, filterHeight: L, filterWidth: M, inChannels: B, inHeight: z, inWidth: V, outChannels: H, outHeight: U, outWidth: K, strideHeight: X, strideWidth: q } = p, Z = L - 1 - p.padInfo.top, J = M - 1 - p.padInfo.left, et = H / B;
for (let Q = 0; Q < F; ++Q)
for (let ot = 0; ot < B; ++ot)
for (let at = 0; at < z; ++at) {
const dt = at - Z, ht = Math.max(0, Math.ceil(dt / X)), xt = Math.min(U, (L + dt) / X);
for (let bt = 0; bt < V; ++bt) {
const Rt = bt - J, Lt = Math.max(0, Math.ceil(Rt / q)), Xt = Math.min(K, (M + Rt) / q);
let Mt = 0;
for (let Ft = ht; Ft < xt; ++Ft) {
const Ht = Ft * X - dt;
for (let Wt = Lt; Wt < Xt; ++Wt) {
const Vn = Wt * q - Rt, fe = y * Q + C * Ft + $ * Wt, es = v * (L - 1 - Ht) + S * (M - 1 - Vn) + T * ot;
for (let Ke = 0; Ke < et; ++Ke) {
const Es = ot * et + Ke, hn = w[fe + Es], Wn = k[es + Ke];
Mt += hn * Wn;
}
}
}
m[g * Q + x * at + b * bt + ot] = Mt;
}
}
return e.makeTensorInfo(f.shape, f.dtype, f.values);
}
const UD = {
kernelName: Wu,
backendName: "cpu",
kernelFunc: WD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function GD(n) {
const { inputs: t, backend: e } = n, { x: s } = t, o = G(s.shape), r = e.data.get(s.dataId).values, i = yt([o, o], s.dtype), a = i.values;
for (let c = 0; c < r.length; c++)
a[c * o + c] = r[c];
const l = [...s.shape, ...s.shape];
return e.makeTensorInfo(l, i.dtype, i.values);
}
const HD = {
kernelName: Uf,
backendName: "cpu",
kernelFunc: GD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const KD = {
kernelName: ja,
backendName: "cpu",
kernelFunc: ({ inputs: n, backend: t, attrs: e }) => {
const { x: s, filter: o } = n, { strides: r, pad: i, dilations: a } = e, l = t, c = l.data.get(s.dataId).values, u = s.shape.length, h = l.data.get(o.dataId).values, d = o.shape.length, { batchSize: p, inHeight: f, inWidth: m, inChannels: g, outHeight: x, outWidth: b, padInfo: w, strideHeight: y, strideWidth: C, filterHeight: $, filterWidth: k, dilationHeight: v, dilationWidth: S, outShape: T } = Ci(s.shape, o.shape, r, i, "NHWC", a), F = G(T), L = T.length, M = qt(s.dtype, F);
for (let z = 0; z < p; ++z)
for (let V = 0; V < x; ++V) {
const H = V * y - w.top;
for (let U = 0; U < b; ++U) {
const K = U * C - w.left;
for (let X = 0; X < g; ++X) {
let q = Number.MIN_SAFE_INTEGER;
for (let J = 0; J < $; ++J) {
const et = H + J * v;
if (et >= 0 && et < f)
for (let Q = 0; Q < k; ++Q) {
const ot = K + Q * S;
if (ot >= 0 && ot < m) {
const at = Rn([z, et, ot, X], u, lt(s.shape)), dt = Rn([J, Q, X], d, lt(o.shape)), ht = c[at] + h[dt];
ht > q && (q = ht);
}
}
}
const Z = Rn([z, V, U, X], L, lt(T));
M[Z] = q;
}
}
}
return { dataId: l.write(so(M, s.dtype), T, s.dtype), shape: T, dtype: s.dtype };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const jD = {
kernelName: Oc,
backendName: "cpu",
kernelFunc: ({ inputs: n, backend: t, attrs: e }) => {
const { x: s, filter: o, dy: r } = n, { strides: i, pad: a, dilations: l } = e, c = t, u = xn(s.shape, c.data.get(s.dataId).values), h = xn(o.shape, c.data.get(o.dataId).values), { batchSize: d, inHeight: p, inWidth: f, inChannels: m, outHeight: g, outWidth: x, padInfo: b, strideHeight: w, strideWidth: y, filterHeight: C, filterWidth: $, dilationHeight: k, dilationWidth: v, outShape: S } = Ci(s.shape, o.shape, i, a, "NHWC", l);
I(r.rank === S.length, () => `Error in ${Oc}, dy must have the same rank as output ${S.length}, but got ${r.rank}`);
const T = xn(S, c.data.get(r.dataId).values), F = zf(o.shape, o.dtype);
for (let M = 0; M < d; ++M)
for (let B = 0; B < g; ++B) {
const z = B * w - b.top;
for (let V = 0; V < x; ++V) {
const H = V * y - b.left;
for (let U = 0; U < m; ++U) {
let K = Number.MIN_SAFE_INTEGER, X = 0, q = 0;
for (let Z = 0; Z < C; ++Z) {
const J = z + Z * k;
if (J >= 0 && J < p)
for (let et = 0; et < $; ++et) {
const Q = H + et * v;
if (Q >= 0 && Q < f) {
const ot = u[M][J][Q][U] + h[Z][et][U];
ot > K && (K = ot, X = Z, q = et);
}
}
}
F[X][q][U] += T[M][B][V][U];
}
}
}
return { dataId: c.write(so(F, s.dtype), o.shape, o.dtype), shape: o.shape, dtype: o.dtype };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const XD = {
kernelName: Fc,
backendName: "cpu",
kernelFunc: ({ inputs: n, backend: t, attrs: e }) => {
const { x: s, filter: o, dy: r } = n, { strides: i, pad: a, dilations: l } = e, c = t, u = xn(s.shape, c.data.get(s.dataId).values), h = xn(o.shape, c.data.get(o.dataId).values), { batchSize: d, inHeight: p, inWidth: f, inChannels: m, outHeight: g, outWidth: x, padInfo: b, strideHeight: w, strideWidth: y, filterHeight: C, filterWidth: $, dilationHeight: k, dilationWidth: v, outShape: S } = Ci(s.shape, o.shape, i, a, "NHWC", l);
I(r.rank === S.length, () => `Error in ${Fc}, dy must have the same rank as output ${S.length}, but got ${r.rank}`);
const T = xn(S, c.data.get(r.dataId).values), F = zf(s.shape, s.dtype);
for (let M = 0; M < d; ++M)
for (let B = 0; B < g; ++B) {
const z = B * w - b.top;
for (let V = 0; V < x; ++V) {
const H = V * y - b.left;
for (let U = 0; U < m; ++U) {
let K = Number.MIN_SAFE_INTEGER, X = z < 0 ? 0 : z, q = H < 0 ? 0 : H;
for (let Z = 0; Z < C; ++Z) {
const J = z + Z * k;
if (J >= 0 && J < p)
for (let et = 0; et < $; ++et) {
const Q = H + et * v;
if (Q >= 0 && Q < f) {
const ot = u[M][J][Q][U] + h[Z][et][U];
ot > K && (K = ot, X = J, q = Q);
}
}
}
F[M][X][q][U] += T[M][B][V][U];
}
}
}
return { dataId: c.write(so(F, s.dtype), s.shape, s.dtype), shape: s.shape, dtype: s.dtype };
}
};
/**
* @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.
* =============================================================================
*/
function qD(n) {
const { inputs: t, backend: e, attrs: s } = n, { image: o } = t, { canvas: r, options: i } = s, { contextOptions: a, imageOptions: l } = i || {}, c = l?.alpha || 1, u = a?.contextType || "2d";
if (u !== "2d")
throw new Error(`Context type ${a.contextType} is not supported by the CPU backend.`);
const h = r.getContext(u, a?.contextAttributes || {});
if (h == null)
throw new Error(`Could not get the context with ${u} type.`);
const [d, p] = o.shape.slice(0, 2), f = o.shape.length === 2 ? 1 : o.shape[2], m = e.data.get(o.dataId).values, g = o.dtype === "float32" ? 255 : 1, x = new Uint8ClampedArray(p * d * 4);
for (let w = 0; w < d * p; ++w) {
const y = [0, 0, 0, 255 * c];
for (let $ = 0; $ < f; $++) {
const k = m[w * f + $];
if (o.dtype === "float32") {
if (k < 0 || k > 1)
throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${k}.`);
} else if (o.dtype === "int32" && (k < 0 || k > 255))
throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${k}.`);
f === 1 ? (y[0] = k * g, y[1] = k * g, y[2] = k * g) : y[$] = k * g;
}
const C = w * 4;
x[C + 0] = Math.round(y[0]), x[C + 1] = Math.round(y[1]), x[C + 2] = Math.round(y[2]), x[C + 3] = Math.round(y[3]);
}
r.width = p, r.height = d;
const b = new ImageData(x, p, d);
return h.putImageData(b, 0, 0), o;
}
const YD = {
kernelName: q1,
backendName: "cpu",
kernelFunc: qD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Mi(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s;
rt(o, "sum");
let a;
o.dtype === "bool" ? a = bs({ inputs: { x: o }, backend: e, attrs: { dtype: "int32" } }) : a = zn({ inputs: { x: o }, backend: e });
const l = a.shape.length, c = wt(r, a.shape), u = jt(c, l);
let h = c, d = a;
u != null && (d = Pe({ inputs: { x: a }, backend: e, attrs: { perm: u } }), h = Zt(h.length, l)), be("sum", h, d.shape.length);
const [p, f] = pe(d.shape, h), m = Ue(d.dtype, "int32");
let g = ka(e, p, m);
const x = G(f), b = e.data.get(g.dataId).values, w = e.data.get(d.dataId).values;
for (let y = 0; y < b.length; ++y) {
const C = y * x;
let $ = 0;
for (let k = 0; k < x; ++k)
$ += w[C + k];
b[y] = $;
}
if (i) {
const y = ne(g.shape, c), C = g;
g = Bt({ inputs: { x: g }, backend: e, attrs: { shape: y } }), e.disposeIntermediateTensorInfo(C);
}
return e.disposeIntermediateTensorInfo(a), u != null && e.disposeIntermediateTensorInfo(d), g;
}
const JD = {
kernelName: Sl,
backendName: "cpu",
kernelFunc: Mi
};
/**
* @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.
* =============================================================================
*/
function ZD(n) {
const { inputs: t, backend: e, attrs: s } = n, { equation: o } = s, r = t, { allDims: i, summedDims: a, idDims: l } = ld(o, r.length);
ud(i.length, l, r);
const { path: c, steps: u } = hd(a, l), h = u.length;
let d = null, p = i.length;
const f = [];
for (let m = 0; m < h; ++m) {
for (const g of u[m]) {
const { permutationIndices: x, expandDims: b } = cd(p, l[g]);
let w;
dd(x) ? w = r[g] : (w = Pe({ inputs: { x: r[g] }, backend: e, attrs: { perm: x } }), f.push(w));
const y = w.shape.slice();
for (let C = 0; C < b.length; ++C)
y.splice(b[C], 0, 1);
Et(w.shape, y) || (w = Bt({ inputs: { x: w }, backend: e, attrs: { shape: y } }), f.push(w)), d === null ? d = w : (d = sc({ inputs: { a: w, b: d }, backend: e }), f.push(d));
}
m < h - 1 && (c[m] >= 0 && (d = Mi({
inputs: { x: d },
backend: e,
attrs: {
axis: c[m] - (i.length - p),
keepDims: !1
}
}), f.push(d)), p--);
}
for (const m of f)
m !== d && e.disposeIntermediateTensorInfo(m);
return d;
}
const QD = {
kernelName: Uu,
backendName: "cpu",
kernelFunc: ZD
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function tA(n) {
const { inputs: t, backend: e } = n, { dy: s, y: o } = t;
rt([s, o], "eluGrad");
const r = new Float32Array(G(o.shape)), i = e.data.get(o.dataId).values, a = e.data.get(s.dataId).values;
for (let l = 0; l < i.length; ++l) {
const c = i[l];
c >= 0 ? r[l] = a[l] : r[l] = a[l] * (c + 1);
}
return e.makeTensorInfo(o.shape, "float32", r);
}
const eA = {
kernelName: Gu,
backendName: "cpu",
kernelFunc: tA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const nA = ed, sA = nd, oA = sd, rA = od, iA = rd, aA = id, lA = At(Br, (n) => {
const t = Math.sign(n), e = Math.abs(n), s = 1 / (1 + nA * e);
return t * (1 - ((((aA * s + iA) * s + rA) * s + oA) * s + sA) * s * Math.exp(-e * e));
}), cA = {
kernelName: Br,
backendName: "cpu",
kernelFunc: lA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Na(n) {
const { inputs: t, backend: e, attrs: s } = n, { input: o } = t, { dim: r } = s, i = o.shape.length, a = o.shape.slice();
let l = r;
return r < 0 && (I(-(i + 1) <= r, () => `Axis must be in the interval [${-(i + 1)}, ${i}]`), l = i + r + 1), a.splice(l, 0, 1), Bt({ inputs: { x: o }, backend: e, attrs: { shape: a } });
}
const uA = {
kernelName: qa,
backendName: "cpu",
kernelFunc: Na
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const hA = te((n, t) => n / t), Gd = ce(Pr, hA), au = {
kernelName: Pr,
backendName: "cpu",
kernelFunc: Gd
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function xy(n, t, e) {
const s = n.shape, o = s[0], r = s[1], i = e.data.get(n.dataId), a = i.complexTensorInfos.real, l = i.complexTensorInfos.imag, c = [o, r], u = G(c), h = we("float32", u), d = we("float32", u);
for (let g = 0; g < o; g++) {
const x = Qs({
inputs: { x: a },
backend: e,
attrs: { begin: [g, 0], size: [1, r] }
}), b = Qs({
inputs: { x: l },
backend: e,
attrs: { begin: [g, 0], size: [1, r] }
}), w = Ve({ inputs: { real: x, imag: b }, backend: e }), { real: y, imag: C } = dA(w, t, e), $ = qn(y, C);
for (let k = 0; k < r; k++) {
const v = ad($, k);
h[g * r + k] = v.real, d[g * r + k] = v.imag;
}
e.disposeIntermediateTensorInfo(x), e.disposeIntermediateTensorInfo(b), e.disposeIntermediateTensorInfo(w);
}
const p = e.makeTensorInfo(c, "float32", h), f = e.makeTensorInfo(c, "float32", d), m = Ve({ inputs: { real: p, imag: f }, backend: e });
return e.disposeIntermediateTensorInfo(p), e.disposeIntermediateTensorInfo(f), m;
}
function dA(n, t, e) {
const s = G(n.shape), o = e.data.get(n.dataId), r = e.data.get(o.complexTensorInfos.real.dataId).values, i = e.data.get(o.complexTensorInfos.imag.dataId).values;
if (pA(s)) {
const a = lu(r, i, s, t, e), l = [n.shape[0], n.shape[1]];
if (t) {
const c = e.makeTensorInfo(l, "float32", a.real), u = e.makeTensorInfo(l, "float32", a.imag), h = e.makeTensorInfo([], "float32", ws(s, "float32")), d = zn({ inputs: { x: h }, backend: e }), p = au.kernelFunc({ inputs: { a: c, b: h }, backend: e }), f = au.kernelFunc({ inputs: { a: u, b: d }, backend: e }), m = e.data.get(p.dataId).values, g = e.data.get(f.dataId).values;
return e.disposeIntermediateTensorInfo(c), e.disposeIntermediateTensorInfo(u), e.disposeIntermediateTensorInfo(h), e.disposeIntermediateTensorInfo(d), e.disposeIntermediateTensorInfo(p), e.disposeIntermediateTensorInfo(f), { real: m, imag: g };
}
return a;
} else {
const a = qn(r, i), l = fA(a, s, t);
return Rg(l);
}
}
function pA(n) {
return (n & n - 1) === 0;
}
function lu(n, t, e, s, o) {
if (e === 1)
return { real: n, imag: t };
const r = qn(n, t), i = e / 2, a = Dg(r), l = a.real, c = a.imag, u = [l.length], h = o.makeTensorInfo(u, "float32", l), d = o.makeTensorInfo(u, "float32", c), p = Ve({ inputs: { real: h, imag: d }, backend: o }), f = Ag(r), m = f.real, g = f.imag, x = [m.length], b = o.makeTensorInfo(x, "float32", m), w = o.makeTensorInfo(x, "float32", g), y = Ve({ inputs: { real: b, imag: w }, backend: o }), C = lu(l, c, i, s, o), $ = C.real, k = C.imag, v = [$.length], S = o.makeTensorInfo(v, "float32", $), T = o.makeTensorInfo(v, "float32", k), F = Ve({
inputs: { real: S, imag: T },
backend: o
}), L = lu(m, g, i, s, o), M = L.real, B = L.imag, z = [M.length], V = o.makeTensorInfo(z, "float32", M), H = o.makeTensorInfo(z, "float32", B), U = Ve({ inputs: { real: V, imag: H }, backend: o }), K = Og(e, s), X = [K.real.length], q = o.makeTensorInfo(X, "float32", K.real), Z = o.makeTensorInfo(X, "float32", K.imag), J = Ve({ inputs: { real: q, imag: Z }, backend: o }), et = sc({ inputs: { a: J, b: U }, backend: o }), Q = Do({
inputs: { a: F, b: et },
backend: o
}), ot = Wd({
inputs: { a: F, b: et },
backend: o
}), at = Zs({ inputs: { input: Q }, backend: o }), dt = Zs({ inputs: { input: ot }, backend: o }), ht = Ao({ inputs: { input: Q }, backend: o }), xt = Ao({ inputs: { input: ot }, backend: o }), bt = Fo({
inputs: [at, dt],
backend: o,
attrs: { axis: 0 }
}), Rt = Fo({
inputs: [ht, xt],
backend: o,
attrs: { axis: 0 }
}), Lt = o.data.get(bt.dataId).values, Xt = o.data.get(Rt.dataId).values;
return o.disposeIntermediateTensorInfo(h), o.disposeIntermediateTensorInfo(d), o.disposeIntermediateTensorInfo(p), o.disposeIntermediateTensorInfo(b), o.disposeIntermediateTensorInfo(w), o.disposeIntermediateTensorInfo(y), o.disposeIntermediateTensorInfo(S), o.disposeIntermediateTensorInfo(T), o.disposeIntermediateTensorInfo(F), o.disposeIntermediateTensorInfo(V), o.disposeIntermediateTensorInfo(H), o.disposeIntermediateTensorInfo(U), o.disposeIntermediateTensorInfo(q), o.disposeIntermediateTensorInfo(Z), o.disposeIntermediateTensorInfo(J), o.disposeIntermediateTensorInfo(et), o.disposeIntermediateTensorInfo(Q), o.disposeIntermediateTensorInfo(ot), o.disposeIntermediateTensorInfo(at), o.disposeIntermediateTensorInfo(ht), o.disposeIntermediateTensorInfo(dt), o.disposeIntermediateTensorInfo(xt), o.disposeIntermediateTensorInfo(bt), o.disposeIntermediateTensorInfo(Rt), { real: Lt, imag: Xt };
}
function fA(n, t, e) {
const s = new Float32Array(t * 2);
for (let o = 0; o < t; o++) {
let r = 0, i = 0;
for (let a = 0; a < t; a++) {
const l = _g(o * a, t, e), c = ad(n, a);
r += c.real * l.real - c.imag * l.imag, i += c.real * l.imag + c.imag * l.real;
}
e && (r /= t, i /= t), Fg(s, r, i, o);
}
return s;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function mA(n) {
const { inputs: t, backend: e } = n, { input: s } = t, o = G(s.shape), r = s.shape[s.shape.length - 1], i = o / r, a = Bt({
inputs: { x: s },
backend: e,
attrs: { shape: [i, r] }
}), l = xy(a, !1, e), c = Bt({ inputs: { x: l }, backend: e, attrs: { shape: s.shape } });
return e.disposeIntermediateTensorInfo(a), e.disposeIntermediateTensorInfo(l), c;
}
const gA = {
kernelName: Hu,
backendName: "cpu",
kernelFunc: mA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Hd(n) {
const { backend: t, attrs: e } = n, { shape: s, value: o, dtype: r } = e, i = r || Lo(o), a = qt(i, G(s));
return bA(a, o, i), t.makeTensorInfo(s, i, a);
}
const xA = {
kernelName: Ku,
backendName: "cpu",
kernelFunc: Hd
};
function bA(n, t, e) {
n.fill(t);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const yA = {
kernelName: ju,
backendName: "cpu",
kernelFunc: ({ inputs: n, attrs: t, backend: e }) => {
const { image: s } = n, o = e, r = we(s.dtype, G(s.shape)), [i, a, l, c] = s.shape, u = o.data.get(s.dataId).values;
for (let d = 0; d < i; d++) {
const p = d * l * a * c;
for (let f = 0; f < a; f++) {
const m = f * (l * c);
for (let g = 0; g < l; g++) {
const x = g * c;
for (let b = 0; b < c; b++) {
const w = Math.round(l - g - 1), y = p + m + x + b;
let C = u[y];
if (w >= 0 && w < l) {
const $ = w * c, k = p + m + $ + b;
C = u[k];
}
r[y] = C;
}
}
}
}
return { dataId: o.write(r, s.shape, s.dtype), shape: s.shape, dtype: s.dtype };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function wA(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r, bias: i, preluActivationWeights: a } = t, { strides: l, pad: c, dataFormat: u, dilations: h, dimRoundingMode: d, activation: p, leakyreluAlpha: f } = s;
let m = my({
inputs: { x: o, filter: r },
backend: e,
attrs: { strides: l, pad: c, dataFormat: u, dilations: h, dimRoundingMode: d }
});
if (i) {
const g = m;
if (u === "NCHW" && i.shape.length === 1 && i.shape[0] !== 1) {
const x = Bt({ inputs: { x: i }, backend: e, attrs: { shape: [i.shape[0], 1, 1] } });
m = Do({ inputs: { a: m, b: x }, backend: e }), e.disposeIntermediateTensorInfo(x);
} else
m = Do({ inputs: { a: m, b: i }, backend: e });
e.disposeIntermediateTensorInfo(g);
}
if (p) {
const g = m;
if (u === "NCHW" && p === "prelu" && a.shape.length === 1 && a.shape[0] !== 1) {
const x = Bt({
inputs: { x: a },
backend: e,
attrs: { shape: [a.shape[0], 1, 1] }
});
m = Sa(e, m, p, x, f), e.disposeIntermediateTensorInfo(x);
} else
m = Sa(e, m, p, a, f);
e.disposeIntermediateTensorInfo(g);
}
return m;
}
const CA = {
kernelName: aa,
backendName: "cpu",
kernelFunc: wA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function $A(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r, bias: i, preluActivationWeights: a } = t, { strides: l, pad: c, dataFormat: u, dilations: h, dimRoundingMode: d, activation: p, leakyreluAlpha: f } = s;
let m = gy({
inputs: { x: o, filter: r },
backend: e,
attrs: { strides: l, pad: c, dataFormat: u, dilations: h, dimRoundingMode: d }
});
if (i) {
const g = m;
m = Do({ inputs: { a: m, b: i }, backend: e }), e.disposeIntermediateTensorInfo(g);
}
if (p) {
const g = m;
m = Sa(e, m, p, a, f), e.disposeIntermediateTensorInfo(g);
}
return m;
}
const IA = {
kernelName: lm,
backendName: "cpu",
kernelFunc: $A
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kA(n) {
const { inputs: t, backend: e } = n, { params: s, indices: o } = t, r = G(s.shape), i = o.shape, a = i[i.length - 1], [l, c, u, h] = Gh(s, o);
if (c === 0)
return e.makeTensorInfo(l, s.dtype, []);
const d = e.data.get(o.dataId).values, p = e.bufferSync(s), f = N0(d, p, s.dtype, c, a, u, h, s.shape, r);
return e.makeTensorInfo(l, s.dtype, f.values);
}
const vA = {
kernelName: Gf,
backendName: "cpu",
kernelFunc: kA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function SA(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, indices: r } = t, { axis: i, batchDims: a } = s;
rt([o, r], "gatherV2");
const l = wt(i, o.shape)[0], c = e.data.get(r.dataId).values, u = o.shape[l];
for (let y = 0; y < c.length; ++y) {
const C = c[y];
I(C <= u - 1 && C >= 0, () => `GatherV2: the index value ${C} is not in [0, ${u - 1}]`);
}
let h = a;
a == null && (h = 0);
const d = G(r.shape), p = fd(o, r, l, h), f = Bt({
inputs: { x: o },
backend: e,
attrs: {
shape: [
p.batchSize,
p.outerSize,
p.dimSize,
p.sliceSize
]
}
}), m = Bt({
inputs: { x: r },
backend: e,
attrs: { shape: [p.batchSize, d / p.batchSize] }
}), g = [
p.batchSize,
p.outerSize,
d / p.batchSize,
p.sliceSize
], x = e.bufferSync(m), b = e.bufferSync(f), w = T0(b, x, g);
return e.disposeIntermediateTensorInfo(f), e.disposeIntermediateTensorInfo(m), e.makeTensorInfo(p.outputShape, w.dtype, w.values);
}
const NA = {
kernelName: Ja,
backendName: "cpu",
kernelFunc: SA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function TA(n) {
const { inputs: t, backend: e } = n, { input: s } = t, o = G(s.shape), r = s.shape[s.shape.length - 1], i = o / r, a = Bt({
inputs: { x: s },
backend: e,
attrs: { shape: [i, r] }
}), l = xy(a, !0, e), c = Bt({ inputs: { x: l }, backend: e, attrs: { shape: s.shape } });
return e.disposeIntermediateTensorInfo(a), e.disposeIntermediateTensorInfo(l), c;
}
const EA = {
kernelName: Xu,
backendName: "cpu",
kernelFunc: TA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const RA = At(jr, (n) => Number.isFinite(n) ? 1 : 0, "bool"), DA = {
kernelName: jr,
backendName: "cpu",
kernelFunc: RA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const AA = At(Xr, (n) => Math.abs(n) === 1 / 0 ? 1 : 0, "bool"), FA = {
kernelName: Xr,
backendName: "cpu",
kernelFunc: AA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const OA = At(qr, (n) => Number.isNaN(n) ? 1 : 0, "bool"), _A = {
kernelName: qr,
backendName: "cpu",
kernelFunc: OA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function LA(n) {
const { backend: t, attrs: e } = n, { start: s, stop: o, num: r } = e, i = F0(s, o, r);
return t.makeTensorInfo([i.length], "float32", i);
}
const MA = {
kernelName: Hf,
backendName: "cpu",
kernelFunc: LA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const PA = At(Jr, (n) => Math.log1p(n)), zA = {
kernelName: Jr,
backendName: "cpu",
kernelFunc: PA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const BA = te((n, t) => n && t), VA = ce(nl, BA, null, "bool"), WA = {
kernelName: nl,
backendName: "cpu",
kernelFunc: VA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const UA = At(sl, (n) => n ? 0 : 1, "bool"), GA = {
kernelName: sl,
backendName: "cpu",
kernelFunc: UA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const HA = te((n, t) => n || t), KA = ce(ol, HA, null, "bool"), jA = {
kernelName: ol,
backendName: "cpu",
kernelFunc: KA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function XA(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { depthRadius: r, bias: i, alpha: a, beta: l } = s;
rt(o, "LRN");
const c = o.shape[3], u = c - 1, h = e.data.get(o.dataId).values, d = G(o.shape), p = new Float32Array(d);
function f(m) {
const g = m % c;
let x = m - g + Math.max(0, g - r);
const b = m - g + Math.min(g + r, u);
let w = 0;
for (; x <= b; x++) {
const y = h[x];
w += y * y;
}
return w;
}
for (let m = 0; m < d; m++) {
const g = f(m), x = h[m] * Math.pow(i + a * g, -l);
p[m] = x;
}
return e.makeTensorInfo(o.shape, o.dtype, p);
}
const qA = {
kernelName: rl,
backendName: "cpu",
kernelFunc: XA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function YA(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, y: r, dy: i } = t, { depthRadius: a, bias: l, alpha: c, beta: u } = s;
rt(i, "LRNGrad");
const h = G(i.shape), d = i.shape[3], p = e.data.get(i.dataId).values, f = e.data.get(o.dataId).values, m = e.data.get(r.dataId).values, g = new Float32Array(h), x = h;
for (let b = 0; b < x; b++) {
const w = b % d, y = b - w + Math.max(0, w - a), C = b - w + Math.min(d, w + a + 1);
let $ = 0;
for (let k = y; k < C; k++)
$ += Math.pow(f[k], 2);
$ = c * $ + l;
for (let k = y; k < C; k++) {
let v = -2 * c * u * f[k] * m[b] / $;
b === k && (v += Math.pow($, -u)), v *= p[b], g[k] += v;
}
}
return e.makeTensorInfo(i.shape, o.dtype, g);
}
const JA = {
kernelName: Yu,
backendName: "cpu",
kernelFunc: YA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function by(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { reductionIndices: r, keepDims: i } = s, a = e;
let l = o.shape;
const c = l.length, u = wt(r, l);
let h = u;
const d = jt(h, c);
let p = a.data.get(o.dataId).values;
if (d != null) {
const y = new Array(c);
for (let C = 0; C < y.length; C++)
y[C] = l[d[C]];
p = Bd(p, l, o.dtype, d, y), h = Zt(h.length, c), l = y;
}
rt(o, "max"), be("max", h, c);
const [f, m] = pe(l, h), g = G(m), x = _0(p, g, f, o.dtype), b = a.write(x, f, o.dtype);
let w = f;
return i && (w = ne(f, u)), { dataId: b, shape: w, dtype: o.dtype };
}
const ZA = {
kernelName: il,
backendName: "cpu",
kernelFunc: by
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function QA(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t;
rt(o, "maxPool");
const { filterSize: r, strides: i, pad: a, dimRoundingMode: l } = s, c = 1;
I(Ie(i, c), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);
const u = ln(o.shape, r, i, c, a, l);
let h;
if (u.filterWidth === 1 && u.filterHeight === 1 && Et(u.inShape, u.outShape))
h = zn({ inputs: { x: o }, backend: e });
else {
const d = e.data.get(o.dataId).values, p = lt(o.shape), f = Ud(d, o.shape, o.dtype, p, u, "max");
h = e.makeTensorInfo(u.outShape, o.dtype, f.values);
}
return h;
}
const tF = {
kernelName: al,
backendName: "cpu",
kernelFunc: QA
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function eF(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { filterSize: r, strides: i, pad: a, dimRoundingMode: l, dataFormat: c } = s;
rt(o, "maxPool3d");
const u = Zn(o.shape, r, i, 1, a, l, c), h = e.data.get(o.dataId).values, d = fy(h, o.shape, o.dtype, lt(o.shape), u, "max");
return e.makeTensorInfo(d.shape, "float32", d.values);
}
const nF = {
kernelName: ll,
backendName: "cpu",
kernelFunc: eF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sF(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, input: r } = t, { filterSize: i, strides: a, pad: l, dimRoundingMode: c } = s;
rt([o, r], "maxPool3DGrad");
const u = Zn(r.shape, i, a, 1, l, c), h = e.bufferSync(r), d = HR(h, u), p = u.strideDepth, f = u.strideHeight, m = u.strideWidth, g = u.dilationDepth, x = u.dilationHeight, b = u.dilationWidth, w = u.effectiveFilterDepth, y = u.effectiveFilterHeight, C = u.effectiveFilterWidth, $ = w - 1 - u.padInfo.front, k = C - 1 - u.padInfo.left, v = y - 1 - u.padInfo.top, S = yt(r.shape, "float32"), T = e.bufferSync(o);
for (let F = 0; F < u.batchSize; ++F)
for (let L = 0; L < u.inChannels; ++L)
for (let M = 0; M < u.inDepth; ++M)
for (let B = 0; B < u.inHeight; ++B)
for (let z = 0; z < u.inWidth; ++z) {
const V = M - $, H = B - v, U = z - k;
let K = 0;
for (let X = 0; X < w; X += g) {
const q = (V + X) / p;
if (!(q < 0 || q >= u.outDepth || Math.floor(q) !== q))
for (let Z = 0; Z < y; Z += x) {
const J = (H + Z) / f;
if (!(J < 0 || J >= u.outHeight || Math.floor(J) !== J))
for (let et = 0; et < C; et += b) {
const Q = (U + et) / m;
if (Q < 0 || Q >= u.outWidth || Math.floor(Q) !== Q)
continue;
const ot = w * y * C - 1 - d.get(F, q, J, Q, L), at = X * y * C + Z * C + et, dt = ot === at ? 1 : 0;
if (dt === 0)
continue;
const ht = T.get(F, q, J, Q, L);
K += ht * dt;
}
}
}
S.set(K, F, M, B, z, L);
}
return e.makeTensorInfo(S.shape, S.dtype, S.values);
}
const oF = {
kernelName: Zu,
backendName: "cpu",
kernelFunc: sF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function rF(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, input: r, output: i } = t, a = r;
rt([r, i], "maxPoolGrad");
const { filterSize: l, strides: c, pad: u, dimRoundingMode: h } = s, d = ln(a.shape, l, c, 1, u, h), p = e.data.get(a.dataId).values, f = yt(d.outShape, a.dtype, py(p, a.shape, a.dtype, d).values), m = d.strideHeight, g = d.strideWidth, x = d.dilationHeight, b = d.dilationWidth, w = d.effectiveFilterHeight, y = d.effectiveFilterWidth, C = y - 1 - d.padInfo.left, $ = w - 1 - d.padInfo.top, k = yt(a.shape, "float32"), v = e.data.get(o.dataId).values, S = yt(o.shape, "float32", v);
for (let T = 0; T < d.batchSize; ++T)
for (let F = 0; F < d.inChannels; ++F)
for (let L = 0; L < d.inHeight; ++L)
for (let M = 0; M < d.inWidth; ++M) {
const B = L - $, z = M - C;
let V = 0;
for (let H = 0; H < w; H += x) {
const U = (B + H) / m;
if (!(U < 0 || U >= d.outHeight || Math.floor(U) !== U))
for (let K = 0; K < y; K += b) {
const X = (z + K) / g;
if (X < 0 || X >= d.outWidth || Math.floor(X) !== X)
continue;
const q = w * y - 1 - f.get(T, U, X, F), Z = H * y + K, J = q === Z ? 1 : 0;
if (J === 0)
continue;
const et = S.get(T, U, X, F);
V += et * J;
}
}
k.set(V, T, L, M, F);
}
return e.makeTensorInfo(k.shape, k.dtype, k.values);
}
const iF = {
kernelName: Ju,
backendName: "cpu",
kernelFunc: rF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function aF(n, t, e, s, o) {
const r = lt(t), i = Ud(n, t, e, r, o, "max"), a = py(n, t, e, o, !0, s);
return [i.values, a.values];
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const lF = {
kernelName: Kf,
backendName: "cpu",
kernelFunc: ({ inputs: n, attrs: t, backend: e }) => {
const { x: s } = n, { filterSize: o, strides: r, pad: i, includeBatchInIndex: a } = t, l = e;
rt(s, "MaxPoolWithArgmax");
const c = l.data.get(s.dataId).values, u = ln(s.shape, o, r, [1, 1], i), [h, d] = aF(c, s.shape, s.dtype, a, u), p = l.write(h, u.outShape, s.dtype), f = l.write(d, u.outShape, s.dtype);
return [
{ dataId: p, shape: u.outShape, dtype: s.dtype },
{ dataId: f, shape: u.outShape, dtype: "int32" }
];
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function cF(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s, a = wt(r, o.shape), c = pe(o.shape, a)[1], u = G(c), h = [], d = e.makeTensorInfo([], "float32", new Float32Array([u]));
h.push(d);
const p = bs({ inputs: { x: o }, backend: e, attrs: { dtype: "float32" } });
h.push(p);
const f = Gd({ inputs: { a: p, b: d }, backend: e });
h.push(f);
const m = Mi({ inputs: { x: f }, backend: e, attrs: { axis: r, keepDims: i } });
return h.forEach((g) => e.disposeIntermediateTensorInfo(g)), m;
}
const uF = {
kernelName: cl,
backendName: "cpu",
kernelFunc: cF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function hF(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s;
rt(o, "min");
const a = wt(r, o.shape);
let l = a;
const c = jt(l, o.shape.length);
let u = o;
c != null && (u = Pe({ inputs: { x: o }, backend: e, attrs: { perm: c } }), l = Zt(l.length, o.shape.length)), be("min", l, u.shape.length);
const [h, d] = pe(u.shape, l), p = G(d), f = Ce(G(h), u.dtype), m = e.data.get(u.dataId).values;
for (let x = 0; x < f.length; ++x) {
const b = x * p;
let w = m[b];
for (let y = 0; y < p; ++y) {
const C = m[b + y];
(Number.isNaN(C) || C < w) && (w = C);
}
f[x] = w;
}
c != null && e.disposeIntermediateTensorInfo(u);
const g = e.makeTensorInfo(h, u.dtype, f);
if (i) {
const x = ne(h, a), b = Bt({ inputs: { x: g }, backend: e, attrs: { shape: x } });
return e.disposeIntermediateTensorInfo(g), b;
}
return g;
}
const dF = {
kernelName: ul,
backendName: "cpu",
kernelFunc: hF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function pF(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { paddings: r, mode: i } = s;
rt(o, "mirrorPad");
const a = r.map(
(w, y) => w[0] + o.shape[y] + w[1]
/* afterPad */
), l = r.map((w) => w[0]), c = r.map((w, y) => w[0] + o.shape[y]), u = i === "reflect" ? 0 : 1, h = e.data.get(o.dataId).values, d = o.shape.length, p = lt(o.shape), f = G(a), m = a.length, g = lt(a), x = we(o.dtype, f);
for (let w = 0; w < f; w++) {
let y = Mo(w, m, g);
for (let $ = 0; $ < m; $++)
y[$] < l[$] ? y[$] = l[$] * 2 - y[$] - u : y[$] >= c[$] && (y[$] = (c[$] - 1) * 2 - y[$] + u);
y = y.map(($, k) => $ - l[k]);
const C = Rn(y, d, p);
x[w] = h[C];
}
return { dataId: e.write(x, a, o.dtype), shape: a, dtype: o.dtype };
}
const fF = {
kernelName: hl,
backendName: "cpu",
kernelFunc: pF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const mF = te((n, t) => {
const e = n % t;
return n < 0 && t < 0 || n >= 0 && t >= 0 ? e : (e + t) % t;
}), gF = ce(ti, mF), xF = {
kernelName: ti,
backendName: "cpu",
kernelFunc: gF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yy(n) {
const { inputs: t, backend: e, attrs: s } = n, { logits: o } = t, { dim: r } = s, i = o.shape.length;
let a = r;
if (a === -1 && (a = i - 1), a !== i - 1)
throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${a}`);
const l = wt([a], o.shape), c = by({
inputs: { x: o },
backend: e,
attrs: { reductionIndices: l, keepDims: !1 }
}), u = ne(c.shape, l), h = Bt({ inputs: { x: c }, backend: e, attrs: { shape: u } }), d = Wd({ inputs: { a: o, b: h }, backend: e }), p = I0({ inputs: { x: d }, backend: e }), f = Mi({ inputs: { x: p }, backend: e, attrs: { axis: l, keepDims: !1 } }), m = Bt({ inputs: { x: f }, backend: e, attrs: { shape: u } }), g = Gd({ inputs: { a: p, b: m }, backend: e });
return e.disposeIntermediateTensorInfo(c), e.disposeIntermediateTensorInfo(h), e.disposeIntermediateTensorInfo(d), e.disposeIntermediateTensorInfo(p), e.disposeIntermediateTensorInfo(f), e.disposeIntermediateTensorInfo(m), g;
}
const bF = {
kernelName: El,
backendName: "cpu",
kernelFunc: yy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yF(n) {
const { inputs: t, backend: e, attrs: s } = n, { logits: o } = t, { numSamples: r, seed: i, normalized: a } = s;
rt(o, "multinomial");
const l = a ? o : yy({ inputs: { logits: o }, backend: e, attrs: { dim: -1 } }), c = l.shape[0], u = l.shape[1], h = e.data.get(l.dataId).values, d = [c, r], p = Ce(G(d), "int32");
for (let f = 0; f < c; ++f) {
const m = f * u, g = new Float32Array(u - 1);
g[0] = h[m];
for (let w = 1; w < g.length; ++w)
g[w] = g[w - 1] + h[m + w];
const x = yu.alea(i.toString()), b = f * r;
for (let w = 0; w < r; ++w) {
const y = x();
p[b + w] = g.length;
for (let C = 0; C < g.length; C++)
if (y < g[C]) {
p[b + w] = C;
break;
}
}
}
return a || e.disposeIntermediateTensorInfo(l), e.makeTensorInfo(d, "int32", p);
}
const wF = {
kernelName: jf,
backendName: "cpu",
kernelFunc: yF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const CF = zh;
function $F(n) {
const { inputs: t, backend: e, attrs: s } = n, { boxes: o, scores: r } = t, { maxOutputSize: i, iouThreshold: a, scoreThreshold: l } = s;
rt(o, "NonMaxSuppression");
const c = e.data.get(o.dataId).values, u = e.data.get(r.dataId).values, { selectedIndices: h } = CF(c, u, i, a, l);
return e.makeTensorInfo([h.length], "int32", new Int32Array(h));
}
const IF = {
kernelName: Qu,
backendName: "cpu",
kernelFunc: $F
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const kF = Bh;
function vF(n) {
const { inputs: t, backend: e, attrs: s } = n, { boxes: o, scores: r } = t, { maxOutputSize: i, iouThreshold: a, scoreThreshold: l, padToMaxOutputSize: c } = s;
rt(o, "NonMaxSuppressionPadded");
const u = e.data.get(o.dataId).values, h = e.data.get(r.dataId).values, { selectedIndices: d, validOutputs: p } = kF(u, h, i, a, l, c);
return [
e.makeTensorInfo([d.length], "int32", new Int32Array(d)),
e.makeTensorInfo([], "int32", new Int32Array([p]))
];
}
const SF = {
kernelName: th,
backendName: "cpu",
kernelFunc: vF
};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const NF = Vh;
function TF(n) {
const { inputs: t, backend: e, attrs: s } = n, { boxes: o, scores: r } = t, { maxOutputSize: i, iouThreshold: a, scoreThreshold: l, softNmsSigma: c } = s;
rt(o, "NonMaxSuppressionWithScore");
const u = e.data.get(o.dataId).values, h = e.data.get(r.dataId).values, d = i, p = a, f = l, m = c, { selectedIndices: g, selectedScores: x } = NF(u, h, d, p, f, m);
return [
e.makeTensorInfo([g.length], "int32", new Int32Array(g)),
e.makeTensorInfo([x.length], "float32", new Float32Array(x))
];
}
const EF = {
kernelName: eh,
backendName: "cpu",
kernelFunc: TF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function RF(n) {
const { inputs: t, backend: e, attrs: s } = n, { indices: o } = t, { dtype: r, depth: i, onValue: a, offValue: l } = s;
rt(o, "oneHot");
const c = G(o.shape), u = new Float32Array(c * i);
u.fill(l);
const h = e.data.get(o.dataId).values;
for (let d = 0; d < c; ++d)
h[d] >= 0 && h[d] < i && (u[d * i + h[d]] = a);
return e.makeTensorInfo([...o.shape, i], r, u);
}
const DF = {
kernelName: ml,
backendName: "cpu",
kernelFunc: RF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ta(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
if (s.dtype === "string")
throw new Error("zerosLike is not supported for string tensors");
if (s.dtype === "complex64") {
const o = Zs({ inputs: { input: s }, backend: e }), r = Ta({ inputs: { x: o }, backend: e }), i = Ao({ inputs: { input: s }, backend: e }), a = Ta({ inputs: { x: i }, backend: e }), l = Ve({ inputs: { real: r, imag: a }, backend: e });
return e.disposeIntermediateTensorInfo(o), e.disposeIntermediateTensorInfo(r), e.disposeIntermediateTensorInfo(i), e.disposeIntermediateTensorInfo(a), l;
} else
return Hd({ backend: e, attrs: { shape: s.shape, value: 0, dtype: s.dtype } });
}
const AF = {
kernelName: Al,
backendName: "cpu",
kernelFunc: Ta
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function wy(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
if (s.dtype === "string")
throw new Error("onesLike is not supported for string tensors");
if (s.dtype === "complex64") {
const o = Zs({ inputs: { input: s }, backend: e }), r = wy({ inputs: { x: o }, backend: e }), i = Ao({ inputs: { input: s }, backend: e }), a = Ta({ inputs: { x: i }, backend: e }), l = Ve({ inputs: { real: r, imag: a }, backend: e });
return e.disposeIntermediateTensorInfo(o), e.disposeIntermediateTensorInfo(r), e.disposeIntermediateTensorInfo(i), e.disposeIntermediateTensorInfo(a), l;
} else
return Hd({ backend: e, attrs: { shape: s.shape, value: 1, dtype: s.dtype } });
}
const FF = {
kernelName: fl,
backendName: "cpu",
kernelFunc: wy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Cy(n) {
const { inputs: t, backend: e, attrs: s } = n, { axis: o } = s;
if (t.length === 1)
return Na({ inputs: { input: t[0] }, backend: e, attrs: { dim: o } });
const r = t[0].shape, i = t[0].dtype;
t.forEach((u) => {
$u(r, u.shape, "All tensors passed to stack must have matching shapes"), I(i === u.dtype, () => "All tensors passed to stack must have matching dtypes");
});
const a = [], l = t.map((u) => {
const h = Na({ inputs: { input: u }, backend: e, attrs: { dim: o } });
return a.push(h), h;
}), c = Fo({ inputs: l, backend: e, attrs: { axis: o } });
return a.forEach((u) => e.disposeIntermediateTensorInfo(u)), c;
}
const OF = {
kernelName: gl,
backendName: "cpu",
kernelFunc: Cy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _F(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { paddings: r, constantValue: i } = s;
rt(o, "pad");
const a = r.map(
(b, w) => b[0] + o.shape[w] + b[1]
/* afterPad */
), l = r.map((b) => b[0]), c = e.data.get(o.dataId).values, u = G(o.shape), h = o.shape.length, d = lt(o.shape), p = G(a), f = a.length, m = lt(a), g = we(o.dtype, p);
i !== 0 && g.fill(i);
for (let b = 0; b < u; b++) {
const y = Mo(b, h, d).map(($, k) => $ + l[k]), C = Rn(y, f, m);
g[C] = c[b];
}
return { dataId: e.write(g, a, o.dtype), shape: a, dtype: o.dtype };
}
const $y = {
kernelName: xl,
backendName: "cpu",
kernelFunc: _F
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const LF = te((n, t) => Math.pow(n, t)), MF = ce(ni, LF), PF = {
kernelName: ni,
backendName: "cpu",
kernelFunc: MF
};
/**
* @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.
* =============================================================================
*/
function zF(n) {
const { inputs: t, backend: e, attrs: s } = n, { paramsNestedSplits: o, paramsDenseValues: r, indices: i } = t, a = o.map((g) => e.data.get(g.dataId).values), l = o.map((g) => g.shape), c = e.data.get(r.dataId).values, u = e.data.get(i.dataId).values, [h, d, p] = V0(a, l, c, r.shape, r.dtype, u, i.shape), f = h.map((g) => e.makeTensorInfo([g.length], "int32", g)), m = e.makeTensorInfo(p, r.dtype, d);
return f.concat([m]);
}
const BF = {
kernelName: Xf,
backendName: "cpu",
kernelFunc: zF
};
/**
* @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.
* =============================================================================
*/
function VF(n) {
const { inputs: t, backend: e } = n, { starts: s, limits: o, deltas: r } = t, i = e.data.get(s.dataId).values, a = e.data.get(o.dataId).values, l = e.data.get(r.dataId).values, [c, u] = W0(i, s.shape, s.dtype, a, o.shape, l, r.shape), h = e.makeTensorInfo([c.length], "int32", c), d = e.makeTensorInfo([u.length], s.dtype, u);
return [h, d];
}
const WF = {
kernelName: qf,
backendName: "cpu",
kernelFunc: VF
};
/**
* @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.
* =============================================================================
*/
function UF(n) {
const { inputs: t, backend: e, attrs: s } = n, { shape: o, values: r, defaultValue: i, rowPartitionTensors: a } = t, { rowPartitionTypes: l } = s, c = e.data.get(o.dataId).values, u = e.data.get(r.dataId).values, h = e.data.get(i.dataId).values, d = a.map((g) => e.data.get(g.dataId).values), p = a.map((g) => g.shape), [f, m] = U0(c, o.shape, u, r.shape, r.dtype, h, i.shape, d, p, l);
return e.makeTensorInfo(f, r.dtype, m);
}
const GF = {
kernelName: Yf,
backendName: "cpu",
kernelFunc: UF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function HF(n) {
const { backend: t, attrs: e } = n, { start: s, stop: o, dtype: r, step: i } = e, a = G0(s, o, i, r);
return t.makeTensorInfo([a.length], r, a);
}
const KF = {
kernelName: nh,
backendName: "cpu",
kernelFunc: HF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const jF = At(si, (n) => 1 / n), XF = {
kernelName: si,
backendName: "cpu",
kernelFunc: jF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function qF(n) {
const { inputs: t, backend: e, attrs: s } = n, { images: o } = t, { alignCorners: r, halfPixelCenters: i, size: a } = s;
rt(o, "resizeBilinear");
const l = lt(o.shape), [c, u] = a, [h, d, p, f] = o.shape, m = e.data.get(o.dataId).values, g = new Float32Array(G([h, c, u, f])), x = [
r && c > 1 ? d - 1 : d,
r && u > 1 ? p - 1 : p
], b = [
r && c > 1 ? c - 1 : c,
r && u > 1 ? u - 1 : u
];
let w = 0;
const y = x[0] / b[0], C = x[1] / b[1];
for (let $ = 0; $ < h; $++)
for (let k = 0; k < c; k++) {
let v;
i ? v = y * (k + 0.5) - 0.5 : v = y * k;
const S = Math.max(0, Math.floor(v)), T = v - S, F = Math.min(d - 1, Math.ceil(v)), L = $ * l[0] + S * l[1], M = $ * l[0] + F * l[1];
for (let B = 0; B < u; B++) {
let z;
i ? z = C * (B + 0.5) - 0.5 : z = C * B;
const V = Math.max(0, Math.floor(z)), H = z - V, U = Math.min(p - 1, Math.ceil(z)), K = L + V * l[2], X = M + V * l[2], q = L + U * l[2], Z = M + U * l[2];
for (let J = 0; J < f; J++) {
const et = m[K + J], Q = m[X + J], ot = m[q + J], at = m[Z + J], dt = et + (ot - et) * H, ht = Q + (at - Q) * H, xt = dt + (ht - dt) * T;
g[w++] = xt;
}
}
}
return e.makeTensorInfo([h, c, u, f], "float32", g);
}
const YF = {
kernelName: $l,
backendName: "cpu",
kernelFunc: qF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function JF(n) {
const { inputs: t, backend: e, attrs: s } = n, { images: o, dy: r } = t, { alignCorners: i } = s;
rt([r, o], "resizeBilinearGrad");
const a = lt(o.shape), [l, c, u, h] = o.shape, [, d, p] = r.shape, f = new Float32Array(l * c * u * h), m = [
i && d > 1 ? c - 1 : c,
i && p > 1 ? u - 1 : u
], g = [
i && d > 1 ? d - 1 : d,
i && p > 1 ? p - 1 : p
], x = m[0] / g[0], b = m[1] / g[1], w = e.data.get(r.dataId).values;
let y = 0;
for (let C = 0; C < l; C++) {
const $ = C * a[0];
for (let k = 0; k < d; k++) {
const v = k * x, S = Math.floor(v), T = Math.min(Math.ceil(v), c - 1), F = $ + S * a[1], L = $ + T * a[1], M = v - S, B = 1 - M;
for (let z = 0; z < p; z++) {
const V = z * b, H = Math.floor(V), U = Math.min(Math.ceil(V), u - 1), K = V - H, X = 1 - K, q = F + H * a[2], Z = F + U * a[2], J = L + H * a[2], et = L + U * a[2], Q = B * X, ot = B * K, at = M * X, dt = M * K;
for (let ht = 0; ht < h; ht++) {
const xt = w[y++];
f[q + ht] += xt * Q, f[Z + ht] += xt * ot, f[J + ht] += xt * at, f[et + ht] += xt * dt;
}
}
}
}
return e.makeTensorInfo([l, u, c, h], "float32", f);
}
const ZF = {
kernelName: rh,
backendName: "cpu",
kernelFunc: JF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function QF(n) {
const { inputs: t, backend: e, attrs: s } = n, { images: o } = t, { alignCorners: r, halfPixelCenters: i, size: a } = s;
rt(o, "resizeNearestNeighbor");
const l = lt(o.shape), [c, u] = a, [h, d, p, f] = o.shape, m = e.data.get(o.dataId).values, g = new Float32Array(h * c * u * f), x = [
r && c > 1 ? d - 1 : d,
r && u > 1 ? p - 1 : p
], b = [
r && c > 1 ? c - 1 : c,
r && u > 1 ? u - 1 : u
], w = x[0] / b[0], y = x[1] / b[1];
let C = 0;
for (let $ = 0; $ < h; $++) {
const k = $ * l[0];
for (let v = 0; v < c; v++) {
const S = i ? w * (v + 0.5) : w * v;
let T = Math.min(d - 1, r ? Math.round(S) : Math.floor(S));
i && (T = Math.max(0, T));
const F = k + T * l[1];
for (let L = 0; L < u; L++) {
const M = i ? y * (L + 0.5) : y * L;
let B = Math.min(p - 1, r ? Math.round(M) : Math.floor(M));
i && (B = Math.max(0, B));
const z = F + B * l[2];
for (let V = 0; V < f; V++) {
const H = m[z + V];
g[C++] = H;
}
}
}
}
return e.makeTensorInfo([h, c, u, f], o.dtype, g);
}
const tO = {
kernelName: Cl,
backendName: "cpu",
kernelFunc: QF
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function eO(n) {
const { inputs: t, backend: e, attrs: s } = n, { images: o, dy: r } = t, { alignCorners: i } = s;
rt([r, o], "resizeNearestNeighborGrad");
const a = lt(o.shape), l = lt(r.shape), [c, u, h, d] = o.shape, [, p, f] = r.shape, m = new Float32Array(c * u * h * d), g = e.data.get(r.dataId).values, x = [
i && p > 1 ? u - 1 : u,
i && f > 1 ? h - 1 : h
], b = [
i && p > 1 ? p - 1 : p,
i && f > 1 ? f - 1 : f
], w = x[0] / b[0], y = x[1] / b[1], C = 1 / w, $ = 1 / y, k = Math.ceil(C) * 2 + 2, v = Math.ceil($) * 2 + 2;
for (let S = 0; S < c; S++) {
const T = S * a[0];
for (let F = 0; F < u; F++) {
const L = T + F * a[1], M = Math.floor(F * C), B = Math.floor(M - k / 2);
for (let z = 0; z < h; z++) {
const V = L + z * a[2], H = Math.floor(z * $), U = Math.floor(H - v / 2);
for (let K = 0; K < d; K++) {
let X = 0;
for (let q = 0; q < k; q++) {
const Z = q + B;
if (Z < 0 || Z >= p)
continue;
const J = T + Z * l[1], et = Z * w, Q = Math.min(u - 1, i ? Math.round(et) : Math.floor(et));
if (F === Q)
for (let ot = 0; ot < v; ot++) {
const at = ot + U;
if (at < 0 || at >= f)
continue;
const dt = J + at * l[2], ht = at * y, xt = Math.min(h - 1, i ? Math.round(ht) : Math.floor(ht));
z === xt && (X += g[dt + K]);
}
}
m[V + K] = X;
}
}
}
}
return e.makeTensorInfo(o.shape, o.dtype, m);
}
const nO = {
kernelName: oh,
backendName: "cpu",
kernelFunc: eO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sO(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { dims: r } = s;
rt(o, "reverse");
const i = o.shape.length, a = wt(r, o.shape);
if (i === 0)
return zn({ inputs: { x: o }, backend: e });
const l = new ge(o.shape, o.dtype), c = e.bufferSync(o);
for (let u = 0; u < l.size; u++) {
const h = l.indexToLoc(u), d = h.slice();
a.forEach((p) => d[p] = o.shape[p] - 1 - d[p]), l.set(c.get(...d), ...h);
}
return e.makeTensorInfo(l.shape, l.dtype, l.values);
}
const oO = {
kernelName: Il,
backendName: "cpu",
kernelFunc: sO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const rO = {
kernelName: dh,
backendName: "cpu",
kernelFunc: ({ inputs: n, attrs: t, backend: e }) => {
const { image: s } = n, { radians: o, fillValue: r, center: i } = t, a = e, l = we(s.dtype, G(s.shape)), [c, u, h, d] = s.shape, [p, f] = Zh(i, u, h), m = 255, g = Math.sin(o), x = Math.cos(o), b = a.data.get(s.dataId).values;
for (let y = 0; y < c; y++) {
const C = y * h * u * d;
for (let $ = 0; $ < u; $++) {
const k = $ * (h * d);
for (let v = 0; v < h; v++) {
const S = v * d;
for (let T = 0; T < d; T++) {
const F = [c, $, v, T], L = F[2], M = F[1];
let B = (L - p) * x - (M - f) * g, z = (L - p) * g + (M - f) * x;
B = Math.round(B + p), z = Math.round(z + f);
let V = r;
if (typeof r != "number" && (T === 3 ? V = m : V = r[T]), B >= 0 && B < h && z >= 0 && z < u) {
const U = z * (h * d), K = B * d, X = C + U + K + T;
V = b[X];
}
const H = C + k + S + T;
l[H] = V;
}
}
}
}
return { dataId: a.write(l, s.shape, s.dtype), shape: s.shape, dtype: s.dtype };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const iO = At(ii, (n) => {
const t = Math.floor(n);
return n - t < 0.5 ? Math.floor(n) : n - t > 0.5 ? Math.ceil(n) : t % 2 === 0 ? t : t + 1;
}), aO = {
kernelName: ii,
backendName: "cpu",
kernelFunc: iO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function lO(n) {
const { inputs: t, backend: e, attrs: s } = n, { indices: o, updates: r } = t, { shape: i } = s, { sliceRank: a, numUpdates: l, sliceSize: c, strides: u, outputSize: h } = io(r, o, i), d = !0, p = e.bufferSync(o), f = e.bufferSync(r), m = Ms(p, f, i, h, c, l, a, u, 0, d);
return e.makeTensorInfo(i, m.dtype, m.values);
}
const cO = {
kernelName: Jf,
backendName: "cpu",
kernelFunc: lO
};
/**
* @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.
* =============================================================================
*/
function uO(n, t) {
let e = 0, s = n.length, o = 0;
for (; e < s; )
o = Math.floor((e + s) / 2), n[o] < t ? e = o + 1 : s = o;
return s;
}
function hO(n, t) {
let e = 0, s = n.length, o = 0;
for (; e < s; )
o = Math.floor((e + s) / 2), n[o] <= t ? e = o + 1 : s = o;
return s;
}
function dO(n, t, e, s, o, r) {
const i = qt("int32", e * o);
for (let a = 0; a < e; ++a) {
const l = n.slice(a * s, (a + 1) * s), c = a * o;
for (let u = 0; u < o; ++u)
i[c + u] = r === "left" ? uO(l, t[u + c]) : hO(l, t[u + c]);
}
return i;
}
/**
* @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.
* =============================================================================
*/
function pO(n) {
const { inputs: t, backend: e, attrs: s } = n, { sortedSequence: o, values: r } = t, { side: i } = s, a = e.data.get(o.dataId).values, l = e.data.get(r.dataId).values, c = dO(a, l, o.shape[0], o.shape[1], r.shape[1], i);
return e.makeTensorInfo(r.shape, "int32", c);
}
const fO = {
kernelName: Qf,
backendName: "cpu",
kernelFunc: pO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function mO(n) {
const { inputs: t, backend: e } = n, { condition: s, t: o, e: r } = t;
rt([s, o, r], "select");
const i = s.shape.length, a = e.data.get(s.dataId).values, l = e.data.get(o.dataId).values, c = e.data.get(r.dataId).values, u = Ue(o.dtype, r.dtype), h = Ce(G(o.shape), u);
let d = 0;
const p = i === 0 || i > 1 || o.shape.length === 1 ? 1 : G(o.shape.slice(1));
for (let f = 0; f < a.length; f++)
for (let m = 0; m < p; m++)
a[f] === 1 ? h[d++] = l[f] : h[d++] = c[f];
return e.makeTensorInfo(o.shape, u, h);
}
const gO = {
kernelName: kl,
backendName: "cpu",
kernelFunc: mO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const xO = Gl, bO = Hl, yO = At(li, (n) => n >= 0 ? bO * n : xO * (Math.exp(n) - 1)), wO = {
kernelName: li,
backendName: "cpu",
kernelFunc: yO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const CO = At(hi, (n) => n < 0 ? -1 : n > 0 ? 1 : 0), $O = {
kernelName: hi,
backendName: "cpu",
kernelFunc: CO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const IO = At(ci, (n) => Math.sin(n)), kO = {
kernelName: ci,
backendName: "cpu",
kernelFunc: IO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const vO = At(ui, (n) => Math.sinh(n)), SO = {
kernelName: ui,
backendName: "cpu",
kernelFunc: vO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const NO = 11920928955078125e-23, sf = Math.log(NO) + 2, TO = At(pi, (n) => {
const t = n > -sf, e = n < sf, s = Math.exp(n);
let o;
return e ? o = s : t ? o = n : o = Math.log(1 + s), o;
}), EO = {
kernelName: pi,
backendName: "cpu",
kernelFunc: TO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function RO(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { blockShape: r, paddings: i } = s;
rt([o], "spaceToBatchND");
const a = G(r), l = [[0, 0]];
l.push(...i);
for (let $ = 1 + r.length; $ < o.shape.length; ++$)
l.push([0, 0]);
const c = $y.kernelFunc({
inputs: { x: o },
backend: e,
attrs: { paddings: l, constantValue: 0 }
}), u = Si(c.shape, r, a, !1), h = Ni(u.length, r.length, !1), d = Ti(c.shape, r, a, !1), m = Bt({ inputs: { x: c }, backend: e, attrs: { shape: u } }), b = Pe({ inputs: { x: m }, backend: e, attrs: { perm: h } }), C = Bt({ inputs: { x: b }, backend: e, attrs: { shape: d } });
return e.disposeIntermediateTensorInfo(c), e.disposeIntermediateTensorInfo(m), e.disposeIntermediateTensorInfo(b), C;
}
const DO = {
kernelName: Nl,
backendName: "cpu",
kernelFunc: RO
};
/**
* @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.
* =============================================================================
*/
function AO(n) {
const { inputs: t, backend: e } = n, { indices: s, values: o, denseShape: r, defaultValue: i } = t;
if (r.shape.length !== 1)
throw new Error(`Dense shape must be a vector, saw:
${r.shape}`);
if (s.shape.length !== 2)
throw new Error(`Indices must be a matrix, saw:
${s.shape}`);
if (o.shape.length !== 1)
throw new Error(`Values must be a vector, saw:
${o.shape}`);
if (i.shape.length !== 0)
throw new Error(`Default value must be a scalar, saw:
${i.shape}`);
const a = e.data.get(s.dataId).values, l = e.data.get(o.dataId).values, c = e.data.get(r.dataId).values, u = e.data.get(i.dataId).values[0], [h, d, p, f, m] = X0(a, s.shape, s.dtype, l, o.dtype, c, u);
return [
e.makeTensorInfo(d, s.dtype, h),
e.makeTensorInfo([d[0]], o.dtype, p),
e.makeTensorInfo([f.length], "bool", new Uint8Array(f.map((g) => Number(g)))),
e.makeTensorInfo([m.length], s.dtype, new Int32Array(m))
];
}
const FO = {
kernelName: tm,
backendName: "cpu",
kernelFunc: AO
};
/**
* @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.
* =============================================================================
*/
function OO(n) {
const { inputs: t, backend: e } = n, { inputIndices: s, inputShape: o, newShape: r } = t;
if (s.shape.length !== 2)
throw new Error(`Input indices should be a matrix but received shape
${s.shape}`);
if (o.shape.length !== 1)
throw new Error(`Input shape should be a vector but received shape
${o.shape}`);
if (r.shape.length !== 1)
throw new Error(`Target shape should be a vector but received shape ${r.shape}`);
const i = Array.from(e.data.get(o.dataId).values), a = e.data.get(s.dataId).values, l = Array.from(e.data.get(r.dataId).values), [c, u, h] = q0(a, s.shape, s.dtype, i, l);
return [
e.makeTensorInfo(u, s.dtype, c),
e.makeTensorInfo([h.length], r.dtype, new Int32Array(h))
];
}
const _O = {
kernelName: em,
backendName: "cpu",
kernelFunc: OO
};
/**
* @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.
* =============================================================================
*/
function LO(n) {
const { inputs: t, backend: e } = n, { data: s, indices: o, segmentIds: r } = t;
if (s.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${o.shape}`);
if (r.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${r.shape}`);
if (o.shape[0] !== r.shape[0])
throw new Error("segmentIds and indices should have same size.");
const i = e.data.get(s.dataId).values, a = e.data.get(o.dataId).values, l = e.data.get(r.dataId).values, [c, u] = Vd(i, s.shape, s.dtype, a, l, !0);
return e.makeTensorInfo(u, s.dtype, c);
}
const MO = {
kernelName: nm,
backendName: "cpu",
kernelFunc: LO
};
/**
* @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.
* =============================================================================
*/
function PO(n) {
const { inputs: t, backend: e } = n, { data: s, indices: o, segmentIds: r } = t;
if (s.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${o.shape}`);
if (r.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${r.shape}`);
if (o.shape[0] !== r.shape[0])
throw new Error("segmentIds and indices should have same size.");
const i = e.data.get(s.dataId).values, a = e.data.get(o.dataId).values, l = e.data.get(r.dataId).values, [c, u] = Vd(i, s.shape, s.dtype, a, l);
return e.makeTensorInfo(u, s.dtype, c);
}
const zO = {
kernelName: sm,
backendName: "cpu",
kernelFunc: PO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function BO(n) {
const { inputs: t, backend: e, attrs: s } = n, { sparseIndices: o, sparseValues: r, defaultValue: i } = t, { outputShape: a } = s, { sliceRank: l, numUpdates: c, sliceSize: u, strides: h, outputSize: d } = io(r, o, a), p = !1, f = e.bufferSync(o);
let m;
switch (r.dtype) {
case "bool": {
const g = e.bufferSync(r), x = !!e.data.get(i.dataId).values[0];
m = Ms(f, g, a, d, u, c, l, h, x, p);
break;
}
case "float32": {
const g = e.bufferSync(r), x = e.data.get(i.dataId).values[0];
m = Ms(f, g, a, d, u, c, l, h, x, p);
break;
}
case "int32": {
const g = e.bufferSync(r), x = e.data.get(i.dataId).values[0];
m = Ms(f, g, a, d, u, c, l, h, x, p);
break;
}
case "string": {
const g = e.bufferSync(r), x = ps(e.data.get(i.dataId).values[0]);
m = Ms(f, g, a, d, u, c, l, h, x, p);
break;
}
default:
throw new Error(`Unsupported type ${r.dtype}`);
}
return e.makeTensorInfo(a, m.dtype, m.values);
}
const VO = {
kernelName: om,
backendName: "cpu",
kernelFunc: BO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function WO(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { numOrSizeSplits: r, axis: i } = s, a = wt(i, o.shape)[0], l = pd(o, r, a), c = new Array(o.shape.length).fill(0), u = o.shape.slice();
return l.map((h) => {
const d = [...u];
d[a] = h;
const p = Qs({ inputs: { x: o }, backend: e, attrs: { begin: c, size: d } });
return c[a] += h, p;
});
}
const UO = {
kernelName: Tl,
backendName: "cpu",
kernelFunc: WO
};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const GO = {
kernelName: ih,
backendName: "cpu",
kernelFunc: ({ inputs: n, backend: t }) => {
const { x: e } = n, s = t;
rt(e, "square");
const o = s.data.get(e.dataId).values, r = new Float32Array(o.length);
for (let a = 0; a < o.length; ++a) {
const l = o[a];
r[a] = l * l;
}
return { dataId: s.write(r, e.shape, e.dtype), shape: e.shape, dtype: e.dtype };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const HO = At(wi, (n, t) => {
const e = t;
return isNaN(n) ? NaN : n > 0 ? 1 : e.alpha;
}), KO = {
kernelName: wi,
backendName: "cpu",
kernelFunc: HO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function jO(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { begin: r, end: i, strides: a, beginMask: l, endMask: c, ellipsisMask: u, newAxisMask: h, shrinkAxisMask: d } = s;
rt(o, "stridedSlice");
const { finalShapeSparse: p, finalShape: f, isIdentity: m, sliceDim0: g, isSimpleSlice: x, begin: b, end: w, strides: y } = qh(o.shape, r, i, a, l, c, u, h, d);
let C;
if (m)
C = Bt({ inputs: { x: o }, backend: e, attrs: { shape: f } });
else if (g || x) {
I(o.shape.length >= 1, () => `Input must have rank at least 1, got: ${o.shape.length}`);
const $ = Kh(b, w, y), k = Qs({ inputs: { x: o }, backend: e, attrs: { begin: b, size: $ } });
C = Bt({ inputs: { x: k }, backend: e, attrs: { shape: f } }), e.disposeIntermediateTensorInfo(k);
} else {
const $ = e.bufferSync(o), k = Z0(p, $, y, b);
C = e.makeTensorInfo(f, k.dtype, k.values);
}
return C;
}
const XO = {
kernelName: lh,
backendName: "cpu",
kernelFunc: jO
};
/**
* @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.
* =============================================================================
*/
function qO(n) {
const { inputs: t, backend: e, attrs: s } = n, { separator: o, nGramWidths: r, leftPad: i, rightPad: a, padWidth: l, preserveShortSequences: c } = s, { data: u, dataSplits: h } = t, d = e.data.get(u.dataId).values, p = e.data.get(h.dataId).values, [f, m] = Q0(d, p, o, r, i, a, l, c);
return [
e.makeTensorInfo([f.length], "string", f),
e.makeTensorInfo(h.shape, "int32", m)
];
}
const YO = {
kernelName: rm,
backendName: "cpu",
kernelFunc: qO
};
/**
* @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.
* =============================================================================
*/
function JO(n) {
const { inputs: t, backend: e, attrs: s } = n, { skipEmpty: o } = s, { input: r, delimiter: i } = t;
if (r.dtype !== "string")
throw new Error("Input must be of datatype string");
if (r.shape.length !== 1)
throw new Error(`Input must be a vector, got shape: ${r.shape}`);
if (i.shape.length !== 0)
throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);
const a = e.data.get(r.dataId).values, l = e.data.get(i.dataId).values[0], [c, u, h] = ty(a, l, o), d = u.length;
return [
e.makeTensorInfo([d, 2], "int32", c),
e.makeTensorInfo([d], "string", u),
e.makeTensorInfo([2], "int32", new Int32Array(h))
];
}
const ZO = {
kernelName: im,
backendName: "cpu",
kernelFunc: JO
};
/**
* @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.
* =============================================================================
*/
function QO(n) {
const { inputs: t, backend: e, attrs: s } = n, { numBuckets: o } = s, { input: r } = t;
if (r.dtype !== "string")
throw new Error("Input must be of datatype string");
if (o <= 0)
throw new Error("Number of buckets must be at least 1");
const i = e.data.get(r.dataId).values, a = ey(i, o);
return e.makeTensorInfo(r.shape, "int32", a);
}
const t_ = {
kernelName: am,
backendName: "cpu",
kernelFunc: QO
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const e_ = At(xi, (n) => Math.tan(n)), n_ = {
kernelName: xi,
backendName: "cpu",
kernelFunc: e_
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const s_ = At(bi, (n) => Math.tanh(n)), o_ = {
kernelName: bi,
backendName: "cpu",
kernelFunc: s_
};
/**
* @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.
* =============================================================================
*/
function r_(n) {
const { inputs: t, backend: e } = n, { tensor: s, indices: o, updates: r } = t, { sliceRank: i, numUpdates: a, sliceSize: l, strides: c, outputSize: u } = io(r, o, s.shape), h = !1, d = e.bufferSync(o), p = e.bufferSync(r), f = e.bufferSync(s), m = Ms(d, p, s.shape, u, l, a, i, c, f, h);
return e.makeTensorInfo(s.shape, m.dtype, m.values);
}
const i_ = {
kernelName: Zf,
backendName: "cpu",
kernelFunc: r_
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function a_(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { reps: r } = s;
rt(o, "tile");
const i = sy(e.bufferSync(o), r);
return e.makeTensorInfo(i.shape, i.dtype, i.values);
}
const l_ = {
kernelName: yi,
backendName: "cpu",
kernelFunc: a_
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function c_(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { k: r, sorted: i } = s;
rt(o, "topk");
const a = e.data.get(o.dataId).values, [l, c] = ry(a, o.shape, o.dtype, r, i);
return [
e.makeTensorInfo(l.shape, l.dtype, l.values),
e.makeTensorInfo(c.shape, c.dtype, c.values)
];
}
const u_ = {
kernelName: ch,
backendName: "cpu",
kernelFunc: c_
};
/**
* @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.
* =============================================================================
*/
function h_(n) {
const { inputs: t, attrs: e, backend: s } = n, { image: o, transforms: r } = t, { interpolation: i, fillMode: a, fillValue: l, outputShape: c } = e, [u, h, d, p] = o.shape, [f, m] = c ?? [h, d], g = [u, f, m, p], x = lt(o.shape), b = x[0], w = x[1], y = x[2], C = lt(g), $ = C[0], k = C[1], v = C[2], S = we(o.dtype, G(g));
S.fill(l);
const T = s.data.get(o.dataId).values, F = s.data.get(r.dataId).values;
for (let M = 0; M < u; ++M) {
const B = r.shape[0] === 1 ? F : F.subarray(M * 8, M * 8 + 8);
for (let z = 0; z < f; ++z)
for (let V = 0; V < m; ++V)
for (let H = 0; H < p; ++H) {
let U;
const K = B[6] * V + B[7] * z + 1;
if (K === 0)
continue;
const X = (B[0] * V + B[1] * z + B[2]) / K, q = (B[3] * V + B[4] * z + B[5]) / K, Z = of(X, d, a), J = of(q, h, a);
switch (i) {
case "nearest":
U = x_(T, h, d, b, w, y, M, J, Z, H, l);
break;
case "bilinear":
U = b_(T, h, d, b, w, y, M, J, Z, H, l);
break;
default:
throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`);
}
const et = M * $ + z * k + V * v + H;
S[et] = U;
}
return s.makeTensorInfo(g, o.dtype, S);
}
return { dataId: s.write(S, g, o.dtype), shape: o.shape, dtype: o.dtype };
}
const d_ = {
kernelName: uh,
backendName: "cpu",
kernelFunc: h_
};
function of(n, t, e) {
switch (e) {
case "reflect":
return p_(n, t);
case "wrap":
return f_(n, t);
case "nearest":
return g_(n, t);
case "constant":
default:
return m_(n);
}
}
function p_(n, t) {
let e = n;
if (e < 0)
if (t <= 1)
e = 0;
else {
const s = 2 * t;
e < s && (e = s * Math.trunc(-e / s) + e), e = e < -t ? e + s : -e - 1;
}
else if (e > t - 1)
if (t <= 1)
e = 0;
else {
const s = 2 * t;
e -= s * Math.trunc(e / s), e >= t && (e = s - e - 1);
}
return Vs(0, e, t - 1);
}
function f_(n, t) {
let e = n;
if (e < 0)
if (t <= 1)
e = 0;
else {
const s = t - 1;
e += t * (Math.trunc(-e / s) + 1);
}
else if (e > t - 1)
if (t <= 1)
e = 0;
else {
const s = t - 1;
e -= t * Math.trunc(e / s);
}
return Vs(0, e, t - 1);
}
function m_(n, t) {
return n;
}
function g_(n, t) {
return Vs(0, n, t - 1);
}
function lr(n, t, e, s, o, r, i, a, l, c, u) {
const h = i * s + a * o + l * r + c;
return 0 <= a && a < t && 0 <= l && l < e ? n[h] : u;
}
function x_(n, t, e, s, o, r, i, a, l, c, u) {
const h = Math.round(a), d = Math.round(l);
return lr(n, t, e, s, o, r, i, h, d, c, u);
}
function b_(n, t, e, s, o, r, i, a, l, c, u) {
const h = Math.floor(a), d = Math.floor(l), p = h + 1, f = d + 1, m = (f - l) * lr(n, t, e, s, o, r, i, h, d, c, u) + (l - d) * lr(n, t, e, s, o, r, i, h, f, c, u), g = (f - l) * lr(n, t, e, s, o, r, i, p, d, c, u) + (l - d) * lr(n, t, e, s, o, r, i, p, f, c, u);
return (p - a) * m + (a - h) * g;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function y_(n) {
const { inputs: t, attrs: e, backend: s } = n, { axis: o } = e, { x: r } = t;
rt(r, "unique");
const i = s.data.get(r.dataId).values, { outputValues: a, outputShape: l, indices: c } = iy(i, o, r.shape, r.dtype);
return [
s.makeTensorInfo(l, r.dtype, a),
s.makeTensorInfo([c.length], "int32", c)
];
}
const w_ = {
kernelName: hh,
backendName: "cpu",
kernelFunc: y_
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function C_(n) {
const { inputs: t, backend: e, attrs: s } = n, { value: o } = t;
let { axis: r } = s;
r < 0 && (r += o.shape.length);
const i = o.shape.length, a = o.shape[r], l = new Array(i - 1);
let c = 0;
for (let p = 0; p < i; p++)
p !== r && (l[c++] = o.shape[p]);
const u = new Array(i).fill(0), h = o.shape.slice();
h[r] = 1;
const d = new Array(a);
for (let p = 0; p < d.length; p++) {
u[r] = p;
const f = Qs({ inputs: { x: o }, backend: e, attrs: { begin: u, size: h } });
d[p] = Bt({ inputs: { x: f }, backend: e, attrs: { shape: l } }), e.disposeIntermediateTensorInfo(f);
}
return d;
}
const $_ = {
kernelName: Rl,
backendName: "cpu",
kernelFunc: C_
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function I_(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, segmentIds: r } = t, { numSegments: i } = s;
rt(o, "unsortedSegmentSum");
const a = o.shape.length, l = r.shape.length, c = [], u = [], h = a - l;
let d = r;
for (let f = 0; f < h; ++f) {
const m = Na({ inputs: { input: d }, backend: e, attrs: { dim: f + 1 } });
d = m, u.push(m);
}
for (let f = 0; f < i; ++f) {
const m = ws(f, "int32"), g = e.makeTensorInfo([], "int32", m), x = C0({ inputs: { a: g, b: d }, backend: e }), b = bs({ inputs: { x }, backend: e, attrs: { dtype: "float32" } }), w = sc({ inputs: { a: b, b: o }, backend: e }), y = Mi({ inputs: { x: w }, backend: e, attrs: { axis: 0, keepDims: !1 } });
c.push(y), u.push(g), u.push(x), u.push(b), u.push(w), u.push(y);
}
const p = Cy({ inputs: c, backend: e, attrs: { axis: 0 } });
return u.forEach((f) => e.disposeIntermediateTensorInfo(f)), p;
}
const k_ = {
kernelName: Dl,
backendName: "cpu",
kernelFunc: I_
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const v_ = [
yR,
QT,
CR,
IR,
rE,
vR,
NR,
ER,
DR,
FR,
_R,
MR,
zR,
WR,
GR,
jR,
qR,
JR,
QR,
xR,
eD,
sD,
rD,
aE,
aD,
sE,
cE,
cD,
tE,
hD,
pD,
fD,
gD,
bD,
wD,
$D,
kD,
SD,
TD,
RD,
AD,
OD,
LD,
PD,
zD,
VD,
UD,
HD,
KD,
jD,
XD,
YD,
QD,
uR,
eA,
uE,
cA,
hE,
uA,
pE,
gA,
xA,
yA,
mE,
xE,
CA,
IA,
vA,
NA,
yE,
CE,
eE,
EA,
dD,
DA,
FA,
_A,
hR,
IE,
vE,
MA,
NE,
zA,
WA,
GA,
jA,
qA,
JA,
ZA,
EE,
tF,
nF,
oF,
iF,
lF,
uF,
dF,
DE,
fF,
xF,
wF,
FE,
_E,
IF,
SF,
EF,
ME,
DF,
FF,
OF,
$y,
PF,
pR,
BE,
BF,
WF,
GF,
KF,
nE,
au,
XF,
fR,
mR,
gR,
YF,
ZF,
tO,
nO,
oO,
rO,
aO,
XE,
cO,
fO,
gO,
wO,
YE,
$O,
kO,
SO,
JE,
bF,
EO,
DO,
FO,
_O,
MO,
zO,
VO,
UO,
tR,
GO,
nR,
oR,
KO,
XO,
YO,
ZO,
t_,
lR,
JD,
n_,
o_,
i_,
l_,
u_,
d_,
PE,
w_,
$_,
k_,
AF
];
for (const n of v_)
cm(n);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const _s = {}, qi = {
alpha: !1,
antialias: !1,
premultipliedAlpha: !1,
preserveDrawingBuffer: !1,
depth: !1,
stencil: !1,
failIfMajorPerformanceCaveat: !0
};
function S_(n, t) {
_s[n] = t;
}
function $n(n, t) {
if (!(n in _s) || t != null) {
const s = T_(n, t);
if (s !== null)
_s[n] = s;
else
return console.log("Could not get context for WebGL version", n), null;
}
const e = _s[n];
return e == null || e.isContextLost() ? (delete _s[n], $n(n)) : (e.disable(e.DEPTH_TEST), e.disable(e.STENCIL_TEST), e.disable(e.BLEND), e.disable(e.DITHER), e.disable(e.POLYGON_OFFSET_FILL), e.disable(e.SAMPLE_COVERAGE), e.enable(e.SCISSOR_TEST), e.enable(e.CULL_FACE), e.cullFace(e.BACK), _s[n]);
}
function N_(n) {
if (!P().getBool("IS_SAFARI") && typeof OffscreenCanvas < "u" && n === 2)
return new OffscreenCanvas(300, 150);
if (typeof document < "u")
return document.createElement("canvas");
throw new Error("Cannot create a canvas in this context");
}
function T_(n, t) {
if (n !== 1 && n !== 2)
throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");
const e = t ?? N_(n);
return e.addEventListener("webglcontextlost", (s) => {
s.preventDefault(), delete _s[n];
}, !1), P().getBool("SOFTWARE_WEBGL_ENABLED") && (qi.failIfMajorPerformanceCaveat = !1), n === 1 ? (
// tslint:disable-next-line
e.getContext("webgl", qi) || e.getContext("experimental-webgl", qi)
) : e.getContext("webgl2", qi);
}
/**
* @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 Cr;
(function(n) {
n[n.DENSE = 0] = "DENSE", n[n.SHARED_BATCH = 1] = "SHARED_BATCH";
})(Cr || (Cr = {}));
var Xe;
(function(n) {
n[n.RENDER = 0] = "RENDER", n[n.UPLOAD = 1] = "UPLOAD", n[n.PIXELS = 2] = "PIXELS", n[n.DOWNLOAD = 3] = "DOWNLOAD";
})(Xe || (Xe = {}));
var me;
(function(n) {
n[n.UNPACKED_FLOAT16 = 0] = "UNPACKED_FLOAT16", n[n.UNPACKED_FLOAT32 = 1] = "UNPACKED_FLOAT32", n[n.PACKED_4X1_UNSIGNED_BYTE = 2] = "PACKED_4X1_UNSIGNED_BYTE", n[n.PACKED_2X2_FLOAT32 = 3] = "PACKED_2X2_FLOAT32", n[n.PACKED_2X2_FLOAT16 = 4] = "PACKED_2X2_FLOAT16";
})(me || (me = {}));
function Pi(n, t) {
return [t, n];
}
function E_(n, t) {
return n * t;
}
function Yi(n) {
const t = G(n), e = Math.ceil(t / 4);
return Ec(e);
}
function Ho(n, t) {
return [
Math.max(1, Math.ceil(t / 2)),
Math.max(1, Math.ceil(n / 2))
];
}
function R_(n, t) {
const [e, s] = Ho(n, t);
return e * s * 4;
}
function Kd(n, t) {
const e = n;
let s, o, r, i, a, l, c, u, h, d;
return P().getNumber("WEBGL_VERSION") === 2 ? (s = e.R32F, o = e.R16F, r = e.RGBA16F, i = e.RGBA32F, a = e.RED, c = 4, u = 1, h = e.HALF_FLOAT, d = e.FLOAT, l = e.RGBA8) : (s = n.RGBA, o = n.RGBA, r = n.RGBA, i = e.RGBA, a = n.RGBA, c = 4, u = 4, h = t != null ? t.HALF_FLOAT_OES : null, d = n.FLOAT, l = n.RGBA), {
internalFormatFloat: s,
internalFormatHalfFloat: o,
internalFormatPackedHalfFloat: r,
internalFormatPackedFloat: i,
textureFormatFloat: a,
downloadTextureFormat: l,
downloadUnpackNumChannels: c,
defaultNumChannels: u,
textureTypeHalfFloat: h,
textureTypeFloat: d
};
}
/**
* @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.
* =============================================================================
*/
function nt(n, t) {
const e = t();
return P().getBool("DEBUG") && D_(n), e;
}
function D_(n) {
const t = n.getError();
if (t !== n.NO_ERROR)
throw new Error("WebGL Error: " + __(n, t));
}
const A_ = 596e-10, F_ = 65504;
function O_(n) {
return !!(P().getBool("WEBGL_RENDER_FLOAT32_ENABLED") || n === 0 || A_ < Math.abs(n) && Math.abs(n) < F_);
}
function __(n, t) {
switch (t) {
case n.NO_ERROR:
return "NO_ERROR";
case n.INVALID_ENUM:
return "INVALID_ENUM";
case n.INVALID_VALUE:
return "INVALID_VALUE";
case n.INVALID_OPERATION:
return "INVALID_OPERATION";
case n.INVALID_FRAMEBUFFER_OPERATION:
return "INVALID_FRAMEBUFFER_OPERATION";
case n.OUT_OF_MEMORY:
return "OUT_OF_MEMORY";
case n.CONTEXT_LOST_WEBGL:
return "CONTEXT_LOST_WEBGL";
default:
return `Unknown error code ${t}`;
}
}
function Ji(n, t) {
return ts(n, () => n.getExtension(t), 'Extension "' + t + '" not supported on this browser.');
}
function L_(n, t) {
const e = ts(n, () => n.createShader(n.VERTEX_SHADER), "Unable to create vertex WebGLShader.");
if (nt(n, () => n.shaderSource(e, t)), nt(n, () => n.compileShader(e)), n.getShaderParameter(e, n.COMPILE_STATUS) === !1)
throw console.log(n.getShaderInfoLog(e)), new Error("Failed to compile vertex shader.");
return e;
}
function M_(n, t) {
const e = ts(n, () => n.createShader(n.FRAGMENT_SHADER), "Unable to create fragment WebGLShader.");
if (nt(n, () => n.shaderSource(e, t)), nt(n, () => n.compileShader(e)), P().get("ENGINE_COMPILE_ONLY"))
return e;
if (n.getShaderParameter(e, n.COMPILE_STATUS) === !1)
throw Iy(t, n.getShaderInfoLog(e)), new Error("Failed to compile fragment shader.");
return e;
}
const P_ = /ERROR: [0-9]+:([0-9]+):/g;
function Iy(n, t) {
const e = P_.exec(t);
if (e == null) {
console.log(`Couldn't parse line number in error: ${t}`), console.log(n);
return;
}
const s = +e[1], o = n.split(`
`), r = o.length.toString().length + 2, i = o.map((h, d) => wo((d + 1).toString(), r) + h);
let a = 0;
for (let h = 0; h < i.length; h++)
a = Math.max(i[h].length, a);
const l = i.slice(0, s - 1), c = i.slice(s - 1, s), u = i.slice(s);
console.log(l.join(`
`)), console.log(t.split(`
`)[0]), console.log(`%c ${wo(c[0], a)}`, "border:1px solid red; background-color:#e3d2d2; color:#a61717"), console.log(u.join(`
`));
}
function z_(n) {
return ts(n, () => n.createProgram(), "Unable to create WebGLProgram.");
}
function B_(n, t) {
if (nt(n, () => n.linkProgram(t)), !P().get("ENGINE_COMPILE_ONLY") && n.getProgramParameter(t, n.LINK_STATUS) === !1)
throw console.log(n.getProgramInfoLog(t)), new Error("Failed to link vertex and fragment shaders.");
}
function Ic(n, t) {
if (nt(n, () => n.validateProgram(t)), n.getProgramParameter(t, n.VALIDATE_STATUS) === !1)
throw console.log(n.getProgramInfoLog(t)), new Error("Shader program validation failed.");
}
function V_(n, t) {
const e = ts(n, () => n.createBuffer(), "Unable to create WebGLBuffer");
return nt(n, () => n.bindBuffer(n.ARRAY_BUFFER, e)), nt(n, () => n.bufferData(n.ARRAY_BUFFER, t, n.STATIC_DRAW)), e;
}
function W_(n, t) {
const e = ts(n, () => n.createBuffer(), "Unable to create WebGLBuffer");
return nt(n, () => n.bindBuffer(n.ELEMENT_ARRAY_BUFFER, e)), nt(n, () => n.bufferData(n.ELEMENT_ARRAY_BUFFER, t, n.STATIC_DRAW)), e;
}
function U_(n) {
return ts(n, () => n.createTexture(), "Unable to create WebGLTexture.");
}
function G_(n, t) {
const e = P().getNumber("WEBGL_MAX_TEXTURE_SIZE");
if (n <= 0 || t <= 0) {
const s = `[${n}x${t}]`;
throw new Error("Requested texture size " + s + " is invalid.");
}
if (n > e || t > e) {
const s = `[${n}x${t}]`, o = `[${e}x${e}]`;
throw new Error("Requested texture size " + s + " greater than WebGL maximum on this browser / GPU " + o + ".");
}
}
function H_(n) {
return ts(n, () => n.createFramebuffer(), "Unable to create WebGLFramebuffer.");
}
function rf(n, t, e, s, o, r, i) {
const a = n.getAttribLocation(t, e);
return a === -1 ? !1 : (nt(n, () => n.bindBuffer(n.ARRAY_BUFFER, s)), nt(n, () => n.vertexAttribPointer(a, o, n.FLOAT, !1, r, i)), nt(n, () => n.enableVertexAttribArray(a)), !0);
}
function K_(n, t, e) {
J_(n, e), nt(n, () => n.activeTexture(n.TEXTURE0 + e)), nt(n, () => n.bindTexture(n.TEXTURE_2D, t));
}
function j_(n, t, e) {
return ts(n, () => n.getUniformLocation(t, e), 'uniform "' + e + '" not present in program.');
}
function X_(n, t, e) {
return n.getUniformLocation(t, e);
}
function q_(n, t, e, s) {
nt(n, () => K_(n, t, s)), nt(n, () => n.uniform1i(e, s));
}
function kc(n, t, e) {
nt(n, () => n.bindFramebuffer(n.FRAMEBUFFER, e)), nt(n, () => n.framebufferTexture2D(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, t, 0));
}
function af(n, t) {
nt(n, () => n.bindFramebuffer(n.FRAMEBUFFER, t)), nt(n, () => n.framebufferTexture2D(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, null, 0));
}
function Zi(n) {
const t = n.checkFramebufferStatus(n.FRAMEBUFFER);
if (t !== n.FRAMEBUFFER_COMPLETE)
throw new Error("Error binding framebuffer: " + Y_(n, t));
}
function Y_(n, t) {
switch (t) {
case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
case n.FRAMEBUFFER_UNSUPPORTED:
return "FRAMEBUFFER_UNSUPPORTED";
default:
return `unknown error ${t}`;
}
}
function ts(n, t, e) {
const s = nt(n, () => t());
if (s == null)
throw new Error(e);
return s;
}
function J_(n, t) {
const e = n.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1, s = t + n.TEXTURE0;
if (s < n.TEXTURE0 || s > e) {
const o = `[gl.TEXTURE0, gl.TEXTURE${e}]`;
throw new Error(`textureUnit must be in ${o}.`);
}
}
function Oo(n, t = 2) {
return G(n.slice(0, n.length - t));
}
function _o(n) {
if (n.length === 0)
throw Error("Cannot get rows and columns of an empty shape array.");
return [
n.length > 1 ? n[n.length - 2] : 1,
n[n.length - 1]
];
}
function Qi(n) {
let t = [1, 1, 1];
return n.length === 0 || n.length === 1 && n[0] === 1 || (t = [Oo(n), ..._o(n)]), t;
}
function Z_(n, t = !1) {
let e = P().getNumber("WEBGL_MAX_TEXTURE_SIZE"), s = P().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");
s === 1 / 0 && P().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE") && (s = e / 2), t && (e = e * 2, s = s * 2, n = n.map((a, l) => l >= n.length - 2 ? Cu(n[l]) : n[l]), n.length === 1 && (n = [2, n[0]])), n.length !== 2 && (n = ys(n).newShape);
let o = G(n), r = null;
n.length <= 1 && o <= e ? r = [1, o] : n.length === 2 && n[0] <= e && n[1] <= e ? r = n : n.length === 3 && n[0] * n[1] <= e && n[2] <= e ? r = [n[0] * n[1], n[2]] : n.length === 3 && n[0] <= e && n[1] * n[2] <= e ? r = [n[0], n[1] * n[2]] : n.length === 4 && n[0] * n[1] * n[2] <= e && n[3] <= e ? r = [n[0] * n[1] * n[2], n[3]] : n.length === 4 && n[0] <= e && n[1] * n[2] * n[3] <= e && (r = [n[0], n[1] * n[2] * n[3]]);
const i = r != null && Math.max(...r) > s && Math.min(...r) <= (t ? 2 : 1) && Math.min(...r) > 0;
if (r == null || i)
if (t) {
const a = Oo(n);
let l = 2, c = 2;
n.length && ([l, c] = _o(n)), o = a * (l / 2) * (c / 2), r = Ec(o).map((u) => u * 2);
} else
r = Ec(o);
return r;
}
function ta(n) {
return n % 2 === 0;
}
function Ea(n, t) {
if (n = n.slice(-2), t = t.slice(-2), Et(n, t) || !n.length || !t.length || n[0] === 0 || n[1] === 0 || t[0] === 0 || t[1] === 0)
return !0;
if (n.length !== t.length) {
const e = n[n.length - 1], s = t[t.length - 1];
if (e === s || ta(e) && ta(s) && (n[0] === 1 || t[0] === 1))
return !0;
}
return n[1] === t[1] && ta(n[0]) && ta(t[0]);
}
let vc, Sc;
function Q_(n) {
if (vc == null) {
const t = $n(n);
vc = t.getParameter(t.MAX_TEXTURE_SIZE);
}
return vc;
}
function tL(n) {
if (Sc == null) {
const t = $n(n);
Sc = t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);
}
return Math.min(16, Sc);
}
function eL(n) {
if (n === 0)
return 0;
let t;
const e = $n(n);
return on(e, "EXT_disjoint_timer_query_webgl2") && n === 2 ? t = 2 : on(e, "EXT_disjoint_timer_query") ? t = 1 : t = 0, t;
}
function on(n, t) {
return n.getExtension(t) != null;
}
function lf(n) {
try {
if ($n(n) != null)
return !0;
} catch (t) {
return console.log("Error when getting WebGL context: ", t), !1;
}
return !1;
}
function nL(n) {
if (n === 0)
return !1;
const t = $n(n);
if (n === 1) {
if (!on(t, "OES_texture_float"))
return !1;
} else if (!on(t, "EXT_color_buffer_float"))
return !1;
return cu(t);
}
function sL(n) {
if (n === 0)
return !1;
const t = $n(n);
if (n === 1) {
if (!on(t, "OES_texture_float") || !on(t, "WEBGL_color_buffer_float"))
return !1;
} else {
if (on(t, "EXT_color_buffer_float"))
return cu(t);
const s = "EXT_color_buffer_half_float";
if (on(t, s)) {
const o = t.getExtension(s);
return oL(t, o);
}
return !1;
}
return cu(t);
}
function cu(n) {
const t = Kd(n), e = n.createTexture();
n.bindTexture(n.TEXTURE_2D, e);
const s = 1, o = 1;
n.texImage2D(n.TEXTURE_2D, 0, t.internalFormatFloat, s, o, 0, t.textureFormatFloat, t.textureTypeFloat, null);
const r = n.createFramebuffer();
n.bindFramebuffer(n.FRAMEBUFFER, r), n.framebufferTexture2D(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, e, 0);
const i = n.checkFramebufferStatus(n.FRAMEBUFFER) === n.FRAMEBUFFER_COMPLETE;
return n.bindTexture(n.TEXTURE_2D, null), n.bindFramebuffer(n.FRAMEBUFFER, null), n.deleteTexture(e), n.deleteFramebuffer(r), i;
}
function oL(n, t) {
const e = Kd(n, t), s = n.createTexture();
n.bindTexture(n.TEXTURE_2D, s);
const o = 1, r = 1;
n.texImage2D(n.TEXTURE_2D, 0, e.internalFormatHalfFloat, o, r, 0, e.textureFormatFloat, e.textureTypeHalfFloat, null);
const i = n.createFramebuffer();
n.bindFramebuffer(n.FRAMEBUFFER, i), n.framebufferTexture2D(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, s, 0);
const a = n.checkFramebufferStatus(n.FRAMEBUFFER) === n.FRAMEBUFFER_COMPLETE;
return n.bindTexture(n.TEXTURE_2D, null), n.bindFramebuffer(n.FRAMEBUFFER, null), n.deleteTexture(s), n.deleteFramebuffer(i), a;
}
function rL(n) {
return n !== 2 ? !1 : $n(n).fenceSync != null;
}
function zi(n, t) {
Array.isArray(n) || (n = [n]), n.forEach((e) => {
e != null && I(e.dtype !== "complex64", () => `${t} does not support complex64 tensors in the WebGL backend.`);
});
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const it = P();
it.registerFlag("HAS_WEBGL", () => it.getNumber("WEBGL_VERSION") > 0);
it.registerFlag("WEBGL_VERSION", () => lf(2) ? 2 : lf(1) ? 1 : 0);
it.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS", () => !1);
it.registerFlag("WEBGL_BUFFER_SUPPORTED", () => it.get("WEBGL_VERSION") === 2);
it.registerFlag("WEBGL_CPU_FORWARD", () => !0);
it.registerFlag("WEBGL_FORCE_F16_TEXTURES", () => !1);
it.registerFlag("WEBGL_PACK", () => it.getBool("HAS_WEBGL"));
it.registerFlag("WEBGL_PACK_NORMALIZATION", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_PACK_CLIP", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_PACK_DEPTHWISECONV", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_PACK_BINARY_OPERATIONS", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_PACK_UNARY_OPERATIONS", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_PACK_REDUCE", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_LAZILY_UNPACK", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_CONV_IM2COL", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE", () => it.getBool("WEBGL_PACK"));
it.registerFlag("WEBGL_MAX_TEXTURE_SIZE", () => Q_(it.getNumber("WEBGL_VERSION")));
it.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER", () => tL(it.getNumber("WEBGL_VERSION")));
it.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION", () => {
const n = it.getNumber("WEBGL_VERSION");
return n === 0 ? 0 : eL(n);
});
it.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE", () => it.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 && !wm());
it.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE", () => nL(it.getNumber("WEBGL_VERSION")));
it.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED", () => it.getBool("WEBGL_FORCE_F16_TEXTURES") ? !1 : it.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));
it.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED", () => sL(it.getNumber("WEBGL_VERSION")));
it.registerFlag("WEBGL_FENCE_API_ENABLED", () => rL(it.getNumber("WEBGL_VERSION")));
it.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM", () => it.getBool("WEBGL_RENDER_FLOAT32_ENABLED") ? 4 : 0);
it.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD", () => -1, (n) => {
if (typeof n != "number")
throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${n}.`);
if (n < 0 && n !== -1)
throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${n}.`);
});
it.registerFlag("WEBGL_FLUSH_THRESHOLD", () => wm() ? 1 : -1, (n) => {
if (typeof n != "number")
throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${n}.`);
if (n < 0 && n !== -1)
throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${n}.`);
});
it.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD", () => 128);
it.registerFlag("WEBGL_USE_SHAPES_UNIFORMS", () => !1);
it.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD", () => 1e5);
it.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD", () => 128);
it.registerFlag("WEBGL_EXP_CONV", () => !1);
it.registerFlag("SOFTWARE_WEBGL_ENABLED", () => it.getBool("IS_TEST"));
it.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE", () => 1 / 0);
it.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE", () => !1);
it.registerFlag("WEBGL2_ISNAN_CUSTOM", () => !1);
it.registerFlag("ENGINE_COMPILE_ONLY", () => !1);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ae() {
let n, t, e, s, o, r, i, a, l, c;
return P().getNumber("WEBGL_VERSION") === 2 ? (n = "#version 300 es", t = "in", e = "out", s = "in", o = "texture", r = "outputColor", i = "out vec4 outputColor;", a = P().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)
` : "", l = "", c = `
#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)));
}
`) : (n = "", t = "attribute", e = "varying", s = "varying", o = "texture2D", r = "gl_FragColor", i = "", a = `
#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));
}
`, l = `
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`, c = `
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`), {
version: n,
attribute: t,
varyingVs: e,
varyingFs: s,
texture2D: o,
output: r,
defineOutput: i,
defineSpecialNaN: a,
defineSpecialInf: l,
defineRound: c
};
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function co(n, t, e = "index") {
const s = lt(t);
return s.map((o, r) => {
const i = `int ${n[r]} = ${e} / ${o}`, a = r === s.length - 1 ? `int ${n[r + 1]} = ${e} - ${n[r]} * ${o}` : `index -= ${n[r]} * ${o}`;
return `${i}; ${a};`;
}).join("");
}
function oc(n, t, e = "index") {
const s = lt(t);
return s.map((o, r) => {
const i = `int ${n[r]} = ${e} / outShapeStrides[${r}]`, a = r === s.length - 1 ? `int ${n[r + 1]} = ${e} - ${n[r]} * outShapeStrides[${r}]` : `index -= ${n[r]} * outShapeStrides[${r}]`;
return `${i}; ${a};`;
}).join("");
}
function iL(n, t) {
const e = n.length, s = n.map((r) => `${t}[${r}]`), o = new Array(e - 1);
o[e - 2] = s[e - 1];
for (let r = e - 3; r >= 0; --r)
o[r] = `(${o[r + 1]} * ${s[r + 1]})`;
return o;
}
function aL(n, t, e = "index") {
const s = n.map((r, i) => i), o = iL(s, t);
return o.map((r, i) => {
const a = `int ${n[i]} = ${e} / ${o[i]}`, l = i === o.length - 1 ? `int ${n[i + 1]} = ${e} - ${n[i]} * ${o[i]}` : `index -= ${n[i]} * ${o[i]}`;
return `${a}; ${l};`;
}).join("");
}
function jd(n) {
const t = lt(n).map((e) => e.toString());
return `
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`;
}
function Xd() {
return `
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
`;
}
const ky = `
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;
}
`;
/**
* @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.
* =============================================================================
*/
const { getBroadcastDims: vy } = Jv;
function lL(n, t, e) {
const s = [];
if (n.forEach((p) => {
const f = G(p.shapeInfo.logicalShape);
if (p.shapeInfo.isUniform ? s.push(`uniform float ${p.name}${f > 1 ? `[${f}]` : ""};`) : (s.push(`uniform sampler2D ${p.name};`), s.push(`uniform int offset${p.name};`)), e.enableShapeUniforms) {
const { uniformShape: m } = qd(e.packedInputs, p.shapeInfo.logicalShape, p.shapeInfo.texShape);
switch (m.length) {
case 1:
s.push(`uniform int ${p.name}Shape;`);
break;
case 2:
s.push(`uniform ivec2 ${p.name}Shape;`);
break;
case 3:
s.push(`uniform ivec3 ${p.name}Shape;`);
break;
case 4:
s.push(`uniform ivec4 ${p.name}Shape;`);
break;
}
s.push(`uniform ivec2 ${p.name}TexShape;`);
}
}), e.enableShapeUniforms) {
switch (t.logicalShape.length) {
case 1:
s.push("uniform int outShape;");
break;
case 2:
s.push("uniform ivec2 outShape;"), s.push("uniform int outShapeStrides;");
break;
case 3:
s.push("uniform ivec3 outShape;"), s.push("uniform ivec2 outShapeStrides;");
break;
case 4:
s.push("uniform ivec4 outShape;"), s.push("uniform ivec3 outShapeStrides;");
break;
}
s.push("uniform ivec2 outTexShape;");
}
e.customUniforms && e.customUniforms.forEach((p) => {
s.push(`uniform ${p.type} ${p.name}${p.arrayIndex ? `[${p.arrayIndex}]` : ""};`);
});
const o = s.join(`
`), r = n.map((p) => cL(p, t, e.packedInputs, e.enableShapeUniforms)).join(`
`), i = t.texShape, a = Ae(), l = dL(a);
let c, u, h = mL(a);
return t.isPacked ? (c = uL(t.logicalShape, i, e.enableShapeUniforms), u = fL(a)) : (c = hL(t.logicalShape, i, e.enableShapeUniforms), u = pL(a)), e.packedInputs && (h += yL), [
h,
l,
u,
o,
c,
r,
e.userCode
].join(`
`);
}
function Ko(n, t = !1) {
const e = n.shapeInfo.logicalShape;
switch (e.length) {
case 0:
return DL(n, t);
case 1:
return FL(n, t);
case 2:
return _L(n, t);
case 3:
return ML(n, t);
case 4:
return zL(n, t);
case 5:
return BL(n);
case 6:
return VL(n);
default:
throw new Error(`${e.length}-D input sampling is not yet supported`);
}
}
function Sy(n, t) {
switch (n.shapeInfo.logicalShape.length) {
case 0:
return RL(n);
case 1:
return AL(n, t);
case 2:
return OL(n, t);
case 3:
return LL(n, t);
default:
return PL(n, t);
}
}
function cL(n, t, e = !1, s) {
let o = "";
e ? o += Sy(n, s) : o += Ko(n, s);
const r = n.shapeInfo.logicalShape, i = t.logicalShape;
return r.length <= i.length && (e ? o += WL(n, t) : o += UL(n, t)), o;
}
function uL(n, t, e) {
switch (n.length) {
case 0:
return Ny();
case 1:
return wL(n, t, e);
case 2:
return TL(n, t, e);
case 3:
return $L(n, t, e);
default:
return kL(n, t, e);
}
}
function hL(n, t, e) {
switch (n.length) {
case 0:
return Ny();
case 1:
return CL(n, t, e);
case 2:
return EL(n, t, e);
case 3:
return IL(n, t, e);
case 4:
return vL(n, t, e);
case 5:
return SL(n, t);
case 6:
return NL(n, t);
default:
throw new Error(`${n.length}-D output sampling is not yet supported`);
}
}
function dL(n) {
return `
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${n.texture2D}(textureSampler, uv).r;
}
`;
}
function pL(n) {
return `
void setOutput(float val) {
${n.output} = vec4(val, 0, 0, 0);
}
`;
}
function fL(n) {
return `
void setOutput(vec4 val) {
${n.output} = val;
}
`;
}
function mL(n) {
return `${n.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${n.varyingFs} vec2 resultUV;
${n.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;
${n.defineSpecialNaN}
${n.defineSpecialInf}
${n.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);
}
${gL}
${xL}
${bL}
`;
}
const gL = `
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);
}
`, xL = `
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);
}
`, bL = `
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);
}
`, yL = `
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 Ny() {
return `
int getOutputCoords() {
return 0;
}
`;
}
function wL(n, t, e) {
const s = [Math.ceil(t[0] / 2), Math.ceil(t[1] / 2)];
return s[0] === 1 ? e ? `
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
}
` : `
int getOutputCoords() {
return 2 * int(resultUV.x * ${s[1]}.0);
}
` : s[1] === 1 ? e ? `
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
}
` : `
int getOutputCoords() {
return 2 * int(resultUV.y * ${s[0]}.0);
}
` : e ? `
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);
}
` : `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);
}
`;
}
function CL(n, t, e) {
return t[0] === 1 ? e ? `
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
` : `
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
` : t[1] === 1 ? e ? `
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
` : `
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
` : e ? `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
return resTexRC.x * outTexShape[1] + resTexRC.y;
}
` : `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
`;
}
function $L(n, t, e) {
if (e)
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 s = [Math.ceil(t[0] / 2), Math.ceil(t[1] / 2)], o = Math.ceil(n[2] / 2), r = o * Math.ceil(n[1] / 2);
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int b = index / ${r};
index -= b * ${r};
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec3(b, r, c);
}
`;
}
function IL(n, t, e) {
if (e)
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${oc(["r", "c", "d"], n)}
return ivec3(r, c, d);
}
`;
const s = co(["r", "c", "d"], n);
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
return ivec3(r, c, d);
}
`;
}
function kL(n, t, e) {
if (e)
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 s = [Math.ceil(t[0] / 2), Math.ceil(t[1] / 2)], o = Math.ceil(n[n.length - 1] / 2), r = o * Math.ceil(n[n.length - 2] / 2);
let i = r, a = "", l = "b, r, c";
for (let c = 2; c < n.length - 1; c++)
i *= n[n.length - c - 1], a = `
int b${c} = index / ${i};
index -= b${c} * ${i};
` + a, l = `b${c}, ` + l;
return `
ivec${n.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
${a}
int b = index / ${r};
index -= b * ${r};
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec${n.length}(${l});
}
`;
}
function vL(n, t, e) {
if (e)
return `
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${oc(["r", "c", "d", "d2"], n)}
return ivec4(r, c, d, d2);
}
`;
const s = co(["r", "c", "d", "d2"], n);
return `
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
return ivec4(r, c, d, d2);
}
`;
}
function SL(n, t) {
const e = co(["r", "c", "d", "d2", "d3"], n);
return `
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${e}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`;
}
function NL(n, t) {
const e = co(["r", "c", "d", "d2", "d3", "d4"], n);
return `
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${e}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`;
}
function TL(n, t, e) {
const s = [Math.ceil(t[0] / 2), Math.ceil(t[1] / 2)];
if (Et(n, t))
return e ? `
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]));
}
` : `
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));
}
`;
const o = Math.ceil(n[1] / 2);
return e ? `
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);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec2(r, c);
}
`;
}
function EL(n, t, e) {
return Et(n, t) ? e ? `
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
}
` : `
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
` : n[1] === 1 ? e ? `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
` : n[0] === 1 ? e ? `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
}
` : e ? `
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);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${n[1]};
int c = index - r * ${n[1]};
return ivec2(r, c);
}
`;
}
function uo(n) {
return `offset${n}`;
}
function RL(n) {
const t = n.name, e = "get" + t.charAt(0).toUpperCase() + t.slice(1), s = Ae();
return `
vec4 ${e}() {
return ${s.texture2D}(${t}, halfCR);
}
`;
}
function DL(n, t) {
const e = n.name, s = "get" + e.charAt(0).toUpperCase() + e.slice(1);
if (n.shapeInfo.isUniform)
return `float ${s}() {return ${e};}`;
const [o, r] = n.shapeInfo.texShape;
if (o === 1 && r === 1)
return `
float ${s}() {
return sampleTexture(${e}, halfCR);
}
`;
const i = uo(e);
if (t)
return `
float ${s}() {
vec2 uv = uvFromFlat(${e}TexShape[0], ${e}TexShape[1], ${i});
return sampleTexture(${e}, uv);
}
`;
const [a, l] = n.shapeInfo.texShape;
return `
float ${s}() {
vec2 uv = uvFromFlat(${a}, ${l}, ${i});
return sampleTexture(${e}, uv);
}
`;
}
function AL(n, t) {
const e = n.name, s = "get" + e.charAt(0).toUpperCase() + e.slice(1), o = n.shapeInfo.texShape, r = Ae();
if (t)
return `
vec4 ${s}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${e}TexShape[0]) / 2.0), ceil(float(${e}TexShape[1]) / 2.0));
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${r.texture2D}(${e}, uv);
}
`;
const i = [Math.ceil(o[0] / 2), Math.ceil(o[1] / 2)];
return `
vec4 ${s}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${r.texture2D}(${e}, uv);
}
`;
}
function FL(n, t) {
const e = n.name, s = "get" + e.charAt(0).toUpperCase() + e.slice(1);
if (n.shapeInfo.isUniform)
return `
float ${s}(int index) {
${jo(n)}
}
`;
const o = n.shapeInfo.texShape, r = o[0], i = o[1];
if (i === 1 && r === 1)
return `
float ${s}(int index) {
return sampleTexture(${e}, halfCR);
}
`;
const a = uo(e);
return i === 1 ? t ? `
float ${s}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / float(${e}TexShape[0]));
return sampleTexture(${e}, uv);
}
` : `
float ${s}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${r}.0);
return sampleTexture(${e}, uv);
}
` : r === 1 ? t ? `
float ${s}(int index) {
vec2 uv = vec2((float(index + ${a}) + 0.5) / float(${e}TexShape[1]), 0.5);
return sampleTexture(${e}, uv);
}
` : `
float ${s}(int index) {
vec2 uv = vec2((float(index + ${a}) + 0.5) / ${i}.0, 0.5);
return sampleTexture(${e}, uv);
}
` : t ? `
float ${s}(int index) {
vec2 uv = uvFromFlat(${e}TexShape[0], ${e}TexShape[1], index + ${a});
return sampleTexture(${e}, uv);
}
` : `
float ${s}(int index) {
vec2 uv = uvFromFlat(${r}, ${i}, index + ${a});
return sampleTexture(${e}, uv);
}
`;
}
function OL(n, t) {
const e = n.shapeInfo.logicalShape, s = n.name, o = "get" + s.charAt(0).toUpperCase() + s.slice(1), r = n.shapeInfo.texShape, i = r[0], a = r[1], l = Ae();
if (r != null && Et(e, r))
return t ? `
vec4 ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
return ${l.texture2D}(${s}, uv);
}
` : `
vec4 ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${i}.0);
return ${l.texture2D}(${s}, uv);
}
`;
if (t)
return `
vec4 ${o}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${s}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
return ${l.texture2D}(${s}, uv);
}
`;
const c = [Math.ceil(r[0] / 2), Math.ceil(r[1] / 2)], u = Math.ceil(e[1] / 2);
return `
vec4 ${o}(int row, int col) {
vec2 uv = packedUVfrom2D(${u}, ${c[0]}, ${c[1]}, row, col);
return ${l.texture2D}(${s}, uv);
}
`;
}
function _L(n, t) {
const e = n.shapeInfo.logicalShape, s = n.name, o = "get" + s.charAt(0).toUpperCase() + s.slice(1), r = n.shapeInfo.texShape;
if (r != null && Et(e, r)) {
if (t)
return `
float ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
`;
const d = r[0], p = r[1];
return `
float ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${p}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;
}
const { newShape: i, keptDims: a } = ys(e), l = i;
if (l.length < e.length) {
const d = Xo(n, l), p = ["row", "col"];
return `
${Ko(d, t)}
float ${o}(int row, int col) {
return ${o}(${qo(p, a)});
}
`;
}
if (n.shapeInfo.isUniform)
return `
float ${o}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
${jo(n)}
}
`;
const c = r[0], u = r[1], h = uo(s);
return u === 1 ? t ? `
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${h}), vec3(${s}Shape[1], 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / float(${s}TexShape[0]));
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${h}), vec3(${e[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${c}.0);
return sampleTexture(${s}, uv);
}
` : c === 1 ? t ? `
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${h}), vec3(${s}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${s}TexShape[1]), 0.5);
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${h}), vec3(${e[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
return sampleTexture(${s}, uv);
}
` : t ? `
float ${o}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${s}Shape[1] + col + ${h};
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${e[1]} + col + ${h};
vec2 uv = uvFromFlat(${c}, ${u}, index);
return sampleTexture(${s}, uv);
}
`;
}
function LL(n, t) {
const e = n.shapeInfo.logicalShape, s = n.name, o = "get" + s.charAt(0).toUpperCase() + s.slice(1), r = n.shapeInfo.texShape, i = [Math.ceil(r[0] / 2), Math.ceil(r[1] / 2)];
if (e[0] === 1) {
const d = e.slice(1), p = [1, 2], f = Xo(n, d), m = ["b", "row", "col"];
return `
${Sy(f, t)}
vec4 ${o}(int b, int row, int col) {
return ${o}(${qo(m, p)});
}
`;
}
const a = Ae();
if (t)
return `
vec4 ${o}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${s}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${s}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${a.texture2D}(${s}, uv);
}
`;
const l = i[0], c = i[1], u = Math.ceil(e[2] / 2), h = u * Math.ceil(e[1] / 2);
return `
vec4 ${o}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${l}, ${c}, ${h}, ${u}, b, row, col);
return ${a.texture2D}(${s}, uv);
}
`;
}
function ML(n, t) {
const e = n.shapeInfo.logicalShape, s = n.name, o = "get" + s.charAt(0).toUpperCase() + s.slice(1), r = e[1] * e[2], i = e[2], { newShape: a, keptDims: l } = ys(e), c = a;
if (c.length < e.length) {
const m = Xo(n, c), g = ["row", "col", "depth"];
return `
${Ko(m, t)}
float ${o}(int row, int col, int depth) {
return ${o}(${qo(g, l)});
}
`;
}
if (n.shapeInfo.isUniform)
return `
float ${o}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${r}, ${i}, 1)));
${jo(n)}
}
`;
const u = n.shapeInfo.texShape, h = u[0], d = u[1], p = n.shapeInfo.flatOffset;
if (d === r && p == null)
return t ? `
float ${o}(int row, int col, int depth) {
int stride1 = ${s}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${h}.0);
return sampleTexture(${s}, uv);
}
`;
if (d === i && p == null)
return t ? `
float ${o}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${s}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${e[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}.0, ${h}.0);
return sampleTexture(${s}, uv);
}
`;
const f = uo(s);
return t ? `
float ${o}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${s}Shape[1] * ${s}Shape[2];
int stride1 = ${s}Shape[2];
int index = row * stride0 + col * stride1 + depth + ${f};
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${r} + col * ${i} + depth + ${f};
vec2 uv = uvFromFlat(${h}, ${d}, index);
return sampleTexture(${s}, uv);
}
`;
}
function PL(n, t) {
const e = n.name, s = "get" + e.charAt(0).toUpperCase() + e.slice(1), o = Ae();
if (t)
return `
vec4 ${s}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${e}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${e}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${e}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${e}TexShape[0]) / 2.0), ceil(float(${e}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 ${o.texture2D}(${e}, uv);
}
`;
const r = n.shapeInfo.logicalShape, i = r.length, a = n.shapeInfo.texShape, l = [Math.ceil(a[0] / 2), Math.ceil(a[1] / 2)], c = l[0], u = l[1], h = Math.ceil(r[i - 1] / 2);
let d = h * Math.ceil(r[i - 2] / 2), p = "int b, int row, int col", f = `b * ${d} + (row / 2) * ${h} + (col / 2)`;
for (let m = 2; m < i - 1; m++)
p = `int b${m}, ` + p, d *= r[i - m - 1], f = `b${m} * ${d} + ` + f;
return `
vec4 ${s}(${p}) {
int index = ${f};
int texR = index / ${u};
int texC = index - texR * ${u};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${c});
return ${o.texture2D}(${e}, uv);
}
`;
}
function zL(n, t) {
const e = n.shapeInfo.logicalShape, s = n.name, o = "get" + s.charAt(0).toUpperCase() + s.slice(1), r = e[3], i = e[2] * r, a = e[1] * i, { newShape: l, keptDims: c } = ys(e);
if (l.length < e.length) {
const b = Xo(n, l), w = ["row", "col", "depth", "depth2"];
return `
${Ko(b, t)}
float ${o}(int row, int col, int depth, int depth2) {
return ${o}(${qo(w, c)});
}
`;
}
if (n.shapeInfo.isUniform)
return `
float ${o}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${a}, ${i}, ${r}, 1)));
${jo(n)}
}
`;
const u = n.shapeInfo.flatOffset, h = n.shapeInfo.texShape, d = h[0], p = h[1], f = `int stride2 = ${s}Shape[3];`, m = `int stride1 = ${s}Shape[2] * stride2;`, g = `int stride0 = ${s}Shape[1] * stride1;`;
if (p === a && u == null)
return t ? `
float ${o}(int row, int col, int depth, int depth2) {
${f}
${m}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${i}, ${r}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${p}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;
if (p === r && u == null)
return t ? `
float ${o}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${s}Shape[1] * ${s}Shape[2], ${s}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${e[1] * e[2]}, ${e[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${p}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;
const x = uo(s);
return t ? `
float ${o}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
${f}
${m}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index + ${x});
return sampleTexture(${s}, uv);
}
` : `
float ${o}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${i} +
depth * ${r} + depth2;
vec2 uv = uvFromFlat(${d}, ${p}, index + ${x});
return sampleTexture(${s}, uv);
}
`;
}
function BL(n) {
const t = n.shapeInfo.logicalShape, e = n.name, s = "get" + e.charAt(0).toUpperCase() + e.slice(1), o = t[4], r = t[3] * o, i = t[2] * r, a = t[1] * i, { newShape: l, keptDims: c } = ys(t);
if (l.length < t.length) {
const m = Xo(n, l), g = ["row", "col", "depth", "depth2", "depth3"];
return `
${Ko(m)}
float ${s}(int row, int col, int depth, int depth2, int depth3) {
return ${s}(${qo(g, c)});
}
`;
}
if (n.shapeInfo.isUniform)
return `
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${a}, ${i}, ${r}, ${o})) +
depth3;
${jo(n)}
}
`;
const u = n.shapeInfo.flatOffset, h = n.shapeInfo.texShape, d = h[0], p = h[1];
if (p === a && u == null)
return `
float ${s}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${i}, ${r}, ${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${p}.0, ${d}.0);
return sampleTexture(${e}, uv);
}
`;
if (p === o && u == null)
return `
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1] * t[2] * t[3]},
${t[2] * t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${p}.0, ${d}.0);
return sampleTexture(${e}, uv);
}
`;
const f = uo(e);
return `
float ${s}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${i} + depth * ${r} +
depth2 * ${o} + depth3 + ${f};
vec2 uv = uvFromFlat(${d}, ${p}, index);
return sampleTexture(${e}, uv);
}
`;
}
function VL(n) {
const t = n.shapeInfo.logicalShape, e = n.name, s = "get" + e.charAt(0).toUpperCase() + e.slice(1), { newShape: o, keptDims: r } = ys(t);
if (o.length < t.length) {
const g = Xo(n, o), x = ["row", "col", "depth", "depth2", "depth3", "depth4"];
return `
${Ko(g)}
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${s}(${qo(x, r)});
}
`;
}
const i = t[5], a = t[4] * i, l = t[3] * a, c = t[2] * l, u = t[1] * c;
if (n.shapeInfo.isUniform)
return `
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${u}, ${c}, ${l}, ${a})) +
dot(
vec2(depth3, depth4),
vec2(${i}, 1)));
${jo(n)}
}
`;
const h = n.shapeInfo.flatOffset, d = n.shapeInfo.texShape, p = d[0], f = d[1];
if (f === u && h == null)
return `
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${c}, ${l}, ${a}, ${i})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${p}.0);
return sampleTexture(${e}, uv);
}
`;
if (f === i && h == null)
return `
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1] * t[2] * t[3] * t[4]},
${t[2] * t[3] * t[4]},
${t[3] * t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${p}.0);
return sampleTexture(${e}, uv);
}
`;
const m = uo(e);
return `
float ${s}(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 * ${u} + col * ${c} + depth * ${l} +
depth2 * ${a} + depth3 * ${i} + depth4 + ${m};
vec2 uv = uvFromFlat(${p}, ${f}, index);
return sampleTexture(${e}, uv);
}
`;
}
function jo(n) {
const t = n.name, e = G(n.shapeInfo.logicalShape);
return e < 2 ? `return ${t};` : `
for (int i = 0; i < ${e}; i++) {
if (i == index) {
return ${t}[i];
}
}
`;
}
function WL(n, t) {
const e = n.name, s = e.charAt(0).toUpperCase() + e.slice(1), o = "get" + s + "AtOutCoords", r = n.shapeInfo.logicalShape.length, i = t.logicalShape.length, a = vy(n.shapeInfo.logicalShape, t.logicalShape), l = Ot(i), c = i - r;
let u;
const h = ["x", "y", "z", "w", "u", "v"];
r === 0 ? u = "" : i < 2 && a.length >= 1 ? u = "coords = 0;" : u = a.map((b) => `coords.${h[b + c]} = 0;`).join(`
`);
let d = "";
i < 2 && r > 0 ? d = "coords" : d = n.shapeInfo.logicalShape.map((b, w) => `coords.${h[w + c]}`).join(", ");
let p = "return outputValue;";
const m = G(n.shapeInfo.logicalShape) === 1, x = G(t.logicalShape) === 1;
if (r === 1 && !m && !x)
p = `
return vec4(outputValue.xy, outputValue.xy);
`;
else if (m && !x)
i === 1 ? p = `
return vec4(outputValue.x, outputValue.x, 0., 0.);
` : p = `
return vec4(outputValue.x);
`;
else if (a.length) {
const b = r - 2, w = r - 1;
a.indexOf(b) > -1 && a.indexOf(w) > -1 ? p = "return vec4(outputValue.x);" : a.indexOf(b) > -1 ? p = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : a.indexOf(w) > -1 && (p = "return vec4(outputValue.xx, outputValue.zz);");
}
return `
vec4 ${o}() {
${l} coords = getOutputCoords();
${u}
vec4 outputValue = get${s}(${d});
${p}
}
`;
}
function UL(n, t) {
const e = n.name, s = e.charAt(0).toUpperCase() + e.slice(1), o = "get" + s + "AtOutCoords", r = t.texShape, i = n.shapeInfo.texShape, a = n.shapeInfo.logicalShape.length, l = t.logicalShape.length;
if (!n.shapeInfo.isUniform && a === l && n.shapeInfo.flatOffset == null && Et(i, r))
return `
float ${o}() {
return sampleTexture(${e}, resultUV);
}
`;
const c = Ot(l), u = vy(n.shapeInfo.logicalShape, t.logicalShape), h = l - a;
let d;
const p = ["x", "y", "z", "w", "u", "v"];
a === 0 ? d = "" : l < 2 && u.length >= 1 ? d = "coords = 0;" : d = u.map((m) => `coords.${p[m + h]} = 0;`).join(`
`);
let f = "";
return l < 2 && a > 0 ? f = "coords" : f = n.shapeInfo.logicalShape.map((m, g) => `coords.${p[g + h]}`).join(", "), `
float ${o}() {
${c} coords = getOutputCoords();
${d}
return get${s}(${f});
}
`;
}
function Ot(n) {
if (n <= 1)
return "int";
if (n === 2)
return "ivec2";
if (n === 3)
return "ivec3";
if (n === 4)
return "ivec4";
if (n === 5)
return "ivec5";
if (n === 6)
return "ivec6";
throw Error(`GPU for rank ${n} is not yet supported`);
}
function qd(n, t, e) {
const { newShape: s, keptDims: o } = ys(t), r = t.length, i = n && r === 3 && t[0] === 1, a = i ? t.slice(1) : s, l = !n && r > 1 && !Et(t, e) && s.length < r || i;
return { useSqueezeShape: l, uniformShape: l ? a : t, keptDims: o };
}
function Xo(n, t) {
const e = JSON.parse(JSON.stringify(n));
return e.shapeInfo.logicalShape = t, e;
}
function qo(n, t) {
return t.map((e) => n[e]).join(", ");
}
/**
* @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.
* =============================================================================
*/
function GL(n, t, e, s) {
const o = e.map((u, h) => {
const d = {
logicalShape: u.shape,
texShape: u.isUniform ? null : u.texData.texShape,
isUniform: u.isUniform,
isPacked: u.isUniform ? !1 : u.texData.isPacked,
flatOffset: null
};
return u.texData != null && u.texData.slice != null && u.texData.slice.flatOffset > 0 && (d.flatOffset = u.texData.slice.flatOffset), { name: t.variableNames[h], shapeInfo: d };
}), r = o.map((u) => u.shapeInfo), i = {
logicalShape: s.shape,
texShape: s.texData.texShape,
isUniform: !1,
isPacked: s.texData.isPacked,
flatOffset: null
}, a = lL(o, i, t), l = M_(n.gl, a), c = n.createProgram(l);
return P().get("ENGINE_COMPILE_ONLY") ? {
program: t,
fragmentShader: l,
source: a,
webGLProgram: c,
inShapeInfos: r,
outShapeInfo: i,
variablesLocations: null,
customUniformLocations: null,
infLoc: null,
nanLoc: null,
outShapeLocation: null,
outShapeStridesLocation: null,
outTexShapeLocation: null
} : (n.buildVao(c), Object.assign({
program: t,
fragmentShader: l,
source: a,
webGLProgram: c,
inShapeInfos: r,
outShapeInfo: i
}, Ty(n, t, c)));
}
function Ty(n, t, e) {
const s = [], o = [];
let r, i, a, l = null, c = null;
c = n.getUniformLocation(e, "NAN", !1), P().getNumber("WEBGL_VERSION") === 1 && (l = n.getUniformLocation(e, "INFINITY", !1));
const u = !1;
for (const h of t.variableNames) {
const d = {
name: h,
uniform: n.getUniformLocation(e, h, u),
offset: n.getUniformLocation(e, `offset${h}`, u)
};
t.enableShapeUniforms && (d.shape = n.getUniformLocation(e, `${h}Shape`, u), d.texShape = n.getUniformLocation(e, `${h}TexShape`, u)), s.push(d);
}
if (t.enableShapeUniforms && (r = n.getUniformLocation(e, "outShape", u), a = n.getUniformLocation(e, "outShapeStrides", u), i = n.getUniformLocation(e, "outTexShape", u)), t.customUniforms)
for (const h of t.customUniforms)
o.push(n.getUniformLocation(e, h.name, u));
return {
variablesLocations: s,
customUniformLocations: o,
infLoc: l,
nanLoc: c,
outShapeLocation: r,
outShapeStridesLocation: a,
outTexShapeLocation: i
};
}
function cf(n, t) {
if (n.length !== t.length)
throw Error(`Binary was compiled with ${n.length} inputs, but was executed with ${t.length} inputs`);
n.forEach((e, s) => {
const o = e.logicalShape, r = t[s], i = r.shape;
if (!Et(o, i))
throw Error(`Binary was compiled with different shapes than the current args. Shapes ${o} and ${i} must match`);
if (e.isUniform && r.isUniform)
return;
const a = e.texShape, l = r.isUniform ? null : r.texData.texShape;
if (!Et(a, l))
throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${l} must match`);
});
}
function HL(n, t, e, s, o) {
t.program.enableShapeUniforms || (cf(t.inShapeInfos, e), cf([t.outShapeInfo], [s]));
const r = s.texData.texture, i = s.texData.texShape;
s.texData.isPacked ? n.setOutputPackedMatrixTexture(r.texture, i[0], i[1]) : n.setOutputMatrixTexture(r.texture, i[0], i[1]), n.setProgram(t.webGLProgram), n.bindVertexArray(t.webGLProgram.vao), P().getNumber("WEBGL_VERSION") === 1 && t.infLoc !== null && n.gl.uniform1f(t.infLoc, 1 / 0), t.nanLoc !== null && n.gl.uniform1f(t.nanLoc, NaN);
for (let l = 0; l < e.length; ++l) {
const c = e[l], { uniform: u, offset: h, shape: d, texShape: p } = t.variablesLocations[l];
if (d) {
const { uniformShape: f } = qd(t.program.packedInputs, c.shape, c.texData.texShape);
switch (f.length) {
case 1:
n.gl.uniform1iv(d, new Int32Array(f));
break;
case 2:
n.gl.uniform2iv(d, new Int32Array(f));
break;
case 3:
n.gl.uniform3iv(d, new Int32Array(f));
break;
case 4:
n.gl.uniform4iv(d, new Int32Array(f));
break;
}
}
if (p && n.gl.uniform2i(p, c.texData.texShape[0], c.texData.texShape[1]), u != null) {
if (c.isUniform) {
if (G(c.shape) < 2)
n.gl.uniform1f(u, c.uniformValues[0]);
else {
let f = c.uniformValues;
f instanceof Float32Array || (f = new Float32Array(f)), n.gl.uniform1fv(u, f);
}
continue;
}
c.texData.slice != null && h != null && n.gl.uniform1i(h, c.texData.slice.flatOffset), n.setInputMatrixTexture(c.texData.texture.texture, u, l);
}
}
const a = t.outShapeLocation;
if (a)
switch (s.shape.length) {
case 1:
n.gl.uniform1iv(a, new Int32Array(s.shape));
break;
case 2:
n.gl.uniform2iv(a, new Int32Array(s.shape));
break;
case 3:
n.gl.uniform3iv(a, new Int32Array(s.shape));
break;
case 4:
n.gl.uniform4iv(a, new Int32Array(s.shape));
break;
}
if (t.outShapeStridesLocation) {
const l = lt(s.shape);
switch (s.shape.length) {
case 2:
n.gl.uniform1iv(t.outShapeStridesLocation, new Int32Array(l));
break;
case 3:
n.gl.uniform2iv(t.outShapeStridesLocation, new Int32Array(l));
break;
case 4:
n.gl.uniform3iv(t.outShapeStridesLocation, new Int32Array(l));
break;
}
}
if (t.outTexShapeLocation && n.gl.uniform2i(t.outTexShapeLocation, s.texData.texShape[0], s.texData.texShape[1]), t.program.customUniforms && o)
for (let l = 0; l < t.program.customUniforms.length; ++l) {
const c = t.program.customUniforms[l], u = t.customUniformLocations[l], h = o[l];
if (c.type === "float")
n.gl.uniform1fv(u, h);
else if (c.type === "vec2")
n.gl.uniform2fv(u, h);
else if (c.type === "vec3")
n.gl.uniform3fv(u, h);
else if (c.type === "vec4")
n.gl.uniform4fv(u, h);
else if (c.type === "int")
n.gl.uniform1iv(u, h);
else if (c.type === "ivec2")
n.gl.uniform2iv(u, h);
else if (c.type === "ivec3")
n.gl.uniform3iv(u, h);
else if (c.type === "ivec4")
n.gl.uniform4iv(u, h);
else
throw Error(`uniform type ${c.type} is not supported yet.`);
}
n.executeProgram();
}
function KL(n, t, e) {
let s = "";
t.concat(e).forEach((i) => {
const a = i.texData != null && i.texData.slice != null && i.texData.slice.flatOffset > 0;
if (n.enableShapeUniforms && !i.isUniform) {
const l = i.texData.texShape, { useSqueezeShape: c, uniformShape: u, keptDims: h } = qd(n.packedInputs, i.shape, l);
let d = "", p = "", f = "";
if (u.length === 1 && n.packedInputs) {
const C = [Math.ceil(l[0] / 2), Math.ceil(l[1] / 2)];
d = `${C[0] > 1}_${C[1] > 1}`;
} else if (u.length === 2 && !n.packedInputs)
p = `${u[0] > 1}_${u[1] > 1}`;
else if (u.length > 2 && !n.packedInputs) {
const C = lt(u);
f = `${C[0] === l[1]}_${C[C.length - 1] === l[1]}`;
}
const m = i.shape.length, g = u.length === 2 && Et(i.shape, l), x = G(i.shape) === 1, b = To(i.shape, e.shape), w = !n.packedInputs && m === e.shape.length && Et(l, e.texData.texShape), y = n.packedInputs || u.length > 2 ? "" : `${l[0] > 1}_${l[1] > 1}`;
s += `${m}_${w}_${c ? h : ""}_${u.length}_${x}_${b}_${g}_${d}_${p}_${f}_${y}_${a}`;
} else {
const l = i.isUniform ? "uniform" : i.texData.texShape;
s += `${i.shape}_${l}_${a}`;
}
});
const o = n.userCode;
let r = n.constructor.name;
return r += "_" + s + "_" + o + `${P().getNumber("WEBGL_VERSION")}`, r;
}
function ve(n) {
return P().getBool("WEBGL_USE_SHAPES_UNIFORMS") && n <= 4;
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class jL {
constructor(t) {
this.variableNames = ["A"], this.packedInputs = !1, this.packedOutput = !0, this.outPackingScheme = Cr.DENSE, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
const e = Ae();
this.outputShape = t, this.enableShapeUniforms = ve(this.outputShape.length), this.userCode = `
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms ? oc(["r", "c", "d"], t) : co(["r", "c", "d"], t)}
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);
}
${e.output} = result;
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class XL {
constructor(t) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0, this.outPackingScheme = Cr.DENSE, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
const e = Ae();
this.outputShape = t, this.enableShapeUniforms = ve(this.outputShape.length), this.userCode = `
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms ? oc(["r", "c", "d"], t) : co(["r", "c", "d"], t)}
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));
}
${e.output} = result;
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class qL {
constructor(t) {
this.variableNames = ["A"], this.outTexUsage = Xe.DOWNLOAD;
const e = Ae();
this.outputShape = t, this.userCode = `
${ky}
void main() {
float x = getAAtOutCoords();
${e.output} = encode_float(x);
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class YL {
constructor(t) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !1, this.outTexUsage = Xe.DOWNLOAD;
const e = Ae();
this.outputShape = t, this.userCode = `
${ky}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${e.output} = encode_float(x);
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const JL = {
R: 0,
G: 1,
B: 2,
A: 3
};
class uf {
constructor(t, e = !1, s = "RGBA") {
this.variableNames = ["A"], this.customUniforms = [{ name: "texShape", type: "ivec2" }];
const o = Ae();
this.outputShape = t, this.enableShapeUniforms = ve(this.outputShape.length);
let r = "result";
e && (r = "floor(result * 255. + 0.5)");
let i = "";
for (let a = 0; a < s.length; a++) {
const l = s[a];
i += `
if(offset == ${a}) {
result = values[${JL[l]}];
}`;
}
this.userCode = `
${this.enableShapeUniforms ? Xd() : jd(t)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
float result = 0.;
int offset = imod(flatIndex, ${s.length});
flatIndex = idiv(flatIndex, ${s.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 = ${o.texture2D}(A, uv);
${i}
}
${o.output} = vec4(${r}, 0., 0., 0.);
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ZL {
constructor(t, e = !1) {
this.variableNames = ["A"], this.packedInputs = !1, this.packedOutput = !0, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
const s = Ae();
this.outputShape = t, this.enableShapeUniforms = ve(this.outputShape.length);
let o = "", r = "result";
e && (r = "floor(result * 255. + 0.5)");
for (let i = 0; i <= 1; i++)
for (let a = 0; a <= 1; a++) {
const l = i * 2 + a;
o += `
localCoords = coords;
if(localCoords[2] + ${a} < ${this.enableShapeUniforms ? "outShape[2]" : `${t[2]}`}) {
localCoords[2] += ${a};
if (localCoords[1] + ${i} < ${this.enableShapeUniforms ? "outShape[1]" : `${t[1]}`}) {
localCoords[1] += ${i};
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 = ${s.texture2D}(A, uv);
if (offset == 0) {
result[${l}] = values[0];
} else if (offset == 1) {
result[${l}] = values[1];
} else if (offset == 2) {
result[${l}] = values[2];
} else {
result[${l}] = values[3];
}
}
}
`;
}
this.userCode = `
${this.enableShapeUniforms ? Xd() : jd(t)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${o}
${s.output} = ${r};
}
`;
}
}
/**
* @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.
* =============================================================================
*/
function QL(n) {
const t = Ae(), e = `${t.version}
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;
return L_(n, e);
}
function tM(n) {
const t = new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);
return V_(n, t);
}
function eM(n) {
const t = new Uint16Array([0, 1, 2, 2, 1, 3]);
return W_(n, t);
}
function Bi(n, t, e, s, o, r) {
G_(t, e);
const i = U_(n), a = n.TEXTURE_2D;
return nt(n, () => n.bindTexture(a, i)), nt(n, () => n.texParameteri(a, n.TEXTURE_WRAP_S, n.CLAMP_TO_EDGE)), nt(n, () => n.texParameteri(a, n.TEXTURE_WRAP_T, n.CLAMP_TO_EDGE)), nt(n, () => n.texParameteri(a, n.TEXTURE_MIN_FILTER, n.NEAREST)), nt(n, () => n.texParameteri(a, n.TEXTURE_MAG_FILTER, n.NEAREST)), P().getNumber("WEBGL_VERSION") === 1 ? nt(n, () => n.texImage2D(a, 0, s, t, e, 0, o, r, null)) : nt(n, () => n.texStorage2D(a, 1, s, t, e)), nt(n, () => n.bindTexture(n.TEXTURE_2D, null)), { texture: i, texShape: [e, t] };
}
function Ey(n) {
return n.internalFormatFloat;
}
function nM(n, t, e, s) {
const [o, r] = Pi(t, e);
return Bi(n, o, r, Ey(s), s.textureFormatFloat, n.FLOAT);
}
function Ry(n) {
return n.internalFormatHalfFloat;
}
function sM(n, t, e, s) {
const [o, r] = Pi(t, e);
return Bi(n, o, r, Ry(s), s.textureFormatFloat, s.textureTypeHalfFloat);
}
function Dy(n) {
return n.downloadTextureFormat;
}
function oM(n, t, e, s) {
const [o, r] = Pi(t, e);
return Bi(n, o, r, Dy(s), n.RGBA, n.UNSIGNED_BYTE);
}
function Ay(n) {
return n.internalFormatPackedFloat;
}
function rM(n, t, e, s) {
const [o, r] = Ho(t, e);
return Bi(n, o, r, Ay(s), n.RGBA, n.FLOAT);
}
function Fy(n) {
return n.internalFormatPackedHalfFloat;
}
function iM(n, t, e, s) {
const [o, r] = Ho(t, e);
return Bi(n, o, r, Fy(s), n.RGBA, s.textureTypeHalfFloat);
}
function aM(n, t, e) {
return nt(n, () => n.bindBuffer(n.ARRAY_BUFFER, e)), rf(n, t, "clipSpacePos", e, 3, 20, 0) && rf(n, t, "uv", e, 2, 20, 12);
}
function lM(n, t, e, s, o, r) {
nt(n, () => n.bindTexture(n.TEXTURE_2D, t));
let i, a, l;
o instanceof Uint8Array ? (i = new Uint8Array(e * s * 4), a = n.UNSIGNED_BYTE, l = n.RGBA) : (i = new Float32Array(e * s * 4), a = n.FLOAT, l = r.internalFormatPackedFloat), i.set(o), P().getNumber("WEBGL_VERSION") === 2 ? nt(n, () => n.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, e, s, n.RGBA, a, i)) : nt(n, () => n.texImage2D(n.TEXTURE_2D, 0, l, e, s, 0, n.RGBA, a, i)), nt(n, () => n.bindTexture(n.TEXTURE_2D, null));
}
function cM(n, t, e) {
nt(n, () => n.bindTexture(n.TEXTURE_2D, t)), e.data instanceof Uint8Array ? P().getNumber("WEBGL_VERSION") === 2 ? nt(n, () => n.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, e.width, e.height, n.RGBA, n.UNSIGNED_BYTE, e.data)) : nt(n, () => n.texImage2D(n.TEXTURE_2D, 0, n.RGBA, e.width, e.height, 0, n.RGBA, n.UNSIGNED_BYTE, e.data)) : P().getNumber("WEBGL_VERSION") === 2 ? nt(n, () => n.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, n.RGBA, n.UNSIGNED_BYTE, e)) : nt(n, () => n.texImage2D(n.TEXTURE_2D, 0, n.RGBA, n.RGBA, n.UNSIGNED_BYTE, e)), nt(n, () => n.bindTexture(n.TEXTURE_2D, null));
}
function uM(n, t, e, s) {
const o = n.createBuffer();
nt(n, () => n.bindBuffer(n.PIXEL_PACK_BUFFER, o));
const a = 4 * 4 * t * e;
return nt(n, () => n.bufferData(n.PIXEL_PACK_BUFFER, a, n.STREAM_READ)), nt(n, () => n.readPixels(0, 0, e, t, n.RGBA, n.FLOAT, 0)), nt(n, () => n.bindBuffer(n.PIXEL_PACK_BUFFER, null)), o;
}
function hM(n, t, e) {
const s = n, o = new Float32Array(e);
return s.bindBuffer(s.PIXEL_PACK_BUFFER, t), s.getBufferSubData(s.PIXEL_PACK_BUFFER, 0, o), s.bindBuffer(s.PIXEL_PACK_BUFFER, null), o;
}
function dM(n, t, e, s) {
const [o, r] = Pi(t, e), i = 4, a = new Uint8Array(E_(t * e, i));
return nt(n, () => n.readPixels(0, 0, o, r, s.downloadTextureFormat, n.UNSIGNED_BYTE, a)), new Float32Array(a.buffer);
}
function pM(n, t, e, s, o, r, i, a) {
const l = n, c = new Float32Array(R_(r, i));
return l.bindBuffer(l.PIXEL_PACK_BUFFER, t), l.getBufferSubData(l.PIXEL_PACK_BUFFER, 0, c), l.bindBuffer(l.PIXEL_PACK_BUFFER, null), c;
}
function fM(n, t, e) {
const s = new Float32Array(t * e * 4);
return nt(n, () => n.readPixels(0, 0, e, t, n.RGBA, n.FLOAT, s)), s;
}
/**
* @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.
* =============================================================================
*/
class Nc {
constructor(t) {
this.outputTexture = null, this.program = null, this.disposed = !1, this.itemsToPoll = [];
const e = P().getNumber("WEBGL_VERSION");
if (t != null ? (this.gl = t, S_(e, t)) : this.gl = $n(e), t = this.gl, P().getNumber("WEBGL_VERSION") === 2) {
const r = t;
this.createVertexArray = () => nt(r, () => r.createVertexArray()), this.bindVertexArray = (i) => nt(r, () => r.bindVertexArray(i)), this.deleteVertexArray = (i) => nt(r, () => r.deleteVertexArray(i)), this.getVertexArray = () => nt(r, () => r.getParameter(r.VERTEX_ARRAY_BINDING));
} else if (t != null) {
const r = t.getExtension("OES_vertex_array_object");
if (r == null)
throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");
this.createVertexArray = () => nt(t, () => r.createVertexArrayOES()), this.bindVertexArray = (i) => nt(t, () => r.bindVertexArrayOES(i)), this.deleteVertexArray = (i) => nt(t, () => r.deleteVertexArrayOES(i)), this.getVertexArray = () => nt(t, () => t.getParameter(r.VERTEX_ARRAY_BINDING_OES));
}
let s = "WEBGL_color_buffer_float";
const o = "EXT_color_buffer_half_float";
if (this.parallelCompilationExtension = this.gl.getExtension("KHR_parallel_shader_compile"), P().getNumber("WEBGL_VERSION") === 1) {
const r = "OES_texture_float", i = "OES_texture_half_float";
if (this.textureFloatExtension = Ji(this.gl, r), on(this.gl, i))
this.textureHalfFloatExtension = Ji(this.gl, i);
else if (P().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.");
if (this.colorBufferFloatExtension = this.gl.getExtension(s), on(this.gl, o))
this.colorBufferHalfFloatExtension = Ji(this.gl, o);
else if (P().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 if (s = "EXT_color_buffer_float", on(this.gl, s))
this.colorBufferFloatExtension = this.gl.getExtension(s);
else if (on(this.gl, o))
this.colorBufferHalfFloatExtension = this.gl.getExtension(o);
else
throw new Error("GL context does not support color renderable floats");
this.vertexBuffer = tM(this.gl), this.indexBuffer = eM(this.gl), this.framebuffer = H_(this.gl), this.textureConfig = Kd(this.gl, this.textureHalfFloatExtension);
}
get debug() {
return P().getBool("DEBUG");
}
dispose() {
if (this.disposed)
return;
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."), 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 t = this.gl;
nt(t, () => t.finish()), nt(t, () => t.bindFramebuffer(t.FRAMEBUFFER, null)), nt(t, () => t.deleteFramebuffer(this.framebuffer)), nt(t, () => t.bindBuffer(t.ARRAY_BUFFER, null)), nt(t, () => t.bindBuffer(t.ELEMENT_ARRAY_BUFFER, null)), nt(t, () => t.deleteBuffer(this.indexBuffer)), this.disposed = !0;
}
createFloat32MatrixTexture(t, e) {
return this.throwIfDisposed(), nM(this.gl, t, e, this.textureConfig);
}
createFloat16MatrixTexture(t, e) {
return this.throwIfDisposed(), sM(this.gl, t, e, this.textureConfig);
}
createUnsignedBytesMatrixTexture(t, e) {
return this.throwIfDisposed(), oM(this.gl, t, e, this.textureConfig);
}
uploadPixelDataToTexture(t, e) {
this.throwIfDisposed(), cM(this.gl, t, e);
}
uploadDenseMatrixToTexture(t, e, s, o) {
this.throwIfDisposed(), lM(this.gl, t, e, s, o, this.textureConfig);
}
createFloat16PackedMatrixTexture(t, e) {
return this.throwIfDisposed(), iM(this.gl, t, e, this.textureConfig);
}
createPackedMatrixTexture(t, e) {
return this.throwIfDisposed(), rM(this.gl, t, e, this.textureConfig);
}
deleteMatrixTexture(t) {
this.throwIfDisposed(), this.outputTexture === t && (af(this.gl, this.framebuffer), this.outputTexture = null), nt(this.gl, () => this.gl.deleteTexture(t));
}
downloadByteEncodedFloatMatrixFromOutputTexture(t, e, s) {
return this.downloadMatrixDriver(t, () => dM(this.gl, e, s, this.textureConfig));
}
downloadPackedMatrixFromBuffer(t, e, s, o, r, i) {
return pM(this.gl, t, e, s, o, r, i, this.textureConfig);
}
downloadFloat32MatrixFromBuffer(t, e) {
return hM(this.gl, t, e);
}
createBufferFromTexture(t, e, s) {
this.bindTextureToFrameBuffer(t);
const o = uM(this.gl, e, s, this.textureConfig);
return this.unbindTextureToFrameBuffer(), o;
}
createAndWaitForFence() {
const t = this.createFence(this.gl);
return this.pollFence(t);
}
createFence(t) {
let e, s;
if (P().getBool("WEBGL_FENCE_API_ENABLED")) {
const o = t, r = o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE, 0);
t.flush(), s = () => {
const i = o.clientWaitSync(r, 0, 0);
return i === o.ALREADY_SIGNALED || i === o.CONDITION_SATISFIED;
}, e = r;
} else
P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 ? (e = this.beginQuery(), this.endQuery(), s = () => this.isQueryAvailable(e, P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))) : s = () => !0;
return { query: e, isFencePassed: s };
}
downloadMatrixFromPackedTexture(t, e, s) {
return this.downloadMatrixDriver(t, () => fM(this.gl, e, s));
}
createProgram(t) {
this.throwIfDisposed();
const e = this.gl;
this.vertexShader == null && (this.vertexShader = QL(e));
const s = z_(e);
nt(e, () => e.attachShader(s, this.vertexShader)), nt(e, () => e.attachShader(s, t)), B_(e, s);
const o = Object.assign(s, { vao: this.createVertexArray() });
return this.debug && Ic(e, o), o;
}
buildVao(t) {
this.setProgram(t), this.bindVertexArray(t.vao);
const e = this.gl;
nt(e, () => e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, this.indexBuffer)), aM(e, t, this.vertexBuffer);
}
deleteProgram(t) {
this.throwIfDisposed(), t === this.program && (this.program = null), t != null && (nt(this.gl, () => this.gl.deleteProgram(t)), this.deleteVertexArray(t.vao));
}
setProgram(t) {
this.throwIfDisposed(), this.program = t, this.program != null && this.debug && Ic(this.gl, this.program), nt(this.gl, () => this.gl.useProgram(t));
}
getUniformLocation(t, e, s = !0) {
return this.throwIfDisposed(), s ? j_(this.gl, t, e) : X_(this.gl, t, e);
}
getAttributeLocation(t, e) {
return this.throwIfDisposed(), nt(this.gl, () => this.gl.getAttribLocation(t, e));
}
getUniformLocationNoThrow(t, e) {
return this.throwIfDisposed(), this.gl.getUniformLocation(t, e);
}
setInputMatrixTexture(t, e, s) {
this.throwIfDisposed(), this.throwIfNoProgram(), q_(this.gl, t, e, s);
}
setOutputMatrixTexture(t, e, s) {
this.setOutputMatrixTextureDriver(t, s, e);
}
setOutputPackedMatrixTexture(t, e, s) {
this.throwIfDisposed();
const [o, r] = Ho(e, s);
this.setOutputMatrixTextureDriver(t, o, r);
}
setOutputMatrixWriteRegion(t, e, s, o) {
this.setOutputMatrixWriteRegionDriver(s, t, o, e);
}
setOutputPackedMatrixWriteRegion(t, e, s, o) {
throw new Error("setOutputPackedMatrixWriteRegion not implemented.");
}
debugValidate() {
this.program != null && Ic(this.gl, this.program), Zi(this.gl);
}
executeProgram() {
this.throwIfDisposed(), this.throwIfNoProgram();
const t = this.gl;
if (this.debug) {
const e = this.getVertexArray();
console.assert(e === this.program.vao, "VAO changed between setProgram and executeProgram!"), this.debugValidate();
}
nt(t, () => t.drawElements(t.TRIANGLES, 6, t.UNSIGNED_SHORT, 0));
}
blockUntilAllProgramsCompleted() {
this.throwIfDisposed(), nt(this.gl, () => this.gl.finish());
}
getQueryTimerExtension() {
return this.disjointQueryTimerExtension == null && (this.disjointQueryTimerExtension = Ji(this.gl, P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2 ? "EXT_disjoint_timer_query_webgl2" : "EXT_disjoint_timer_query")), this.disjointQueryTimerExtension;
}
getQueryTimerExtensionWebGL2() {
return this.getQueryTimerExtension();
}
getQueryTimerExtensionWebGL1() {
return this.getQueryTimerExtension();
}
beginQuery() {
if (P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
const s = this.gl, o = this.getQueryTimerExtensionWebGL2(), r = s.createQuery();
return s.beginQuery(o.TIME_ELAPSED_EXT, r), r;
}
const t = this.getQueryTimerExtensionWebGL1(), e = t.createQueryEXT();
return t.beginQueryEXT(t.TIME_ELAPSED_EXT, e), e;
}
endQuery() {
if (P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
const e = this.gl, s = this.getQueryTimerExtensionWebGL2();
e.endQuery(s.TIME_ELAPSED_EXT);
return;
}
const t = this.getQueryTimerExtensionWebGL1();
t.endQueryEXT(t.TIME_ELAPSED_EXT);
}
async waitForQueryAndGetTime(t) {
return await ep(() => 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(t, P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))), this.getQueryTime(t, P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"));
}
getQueryTime(t, e) {
if (e === 0)
return null;
if (e === 2) {
const s = this.gl;
return s.getQueryParameter(t, s.QUERY_RESULT) / 1e6;
} else {
const s = this.getQueryTimerExtensionWebGL1();
return s.getQueryObjectEXT(t, s.QUERY_RESULT_EXT) / 1e6;
}
}
isQueryAvailable(t, e) {
if (e === 0)
return !0;
if (e === 2) {
const s = this.gl, o = this.getQueryTimerExtensionWebGL2(), r = s.getQueryParameter(t, s.QUERY_RESULT_AVAILABLE);
return this.disjoint == null && (this.disjoint = this.gl.getParameter(o.GPU_DISJOINT_EXT)), r && !this.disjoint;
} else {
const s = this.getQueryTimerExtensionWebGL1(), o = s.getQueryObjectEXT(t, s.QUERY_RESULT_AVAILABLE_EXT);
return this.disjoint == null && (this.disjoint = this.gl.getParameter(s.GPU_DISJOINT_EXT)), o && !this.disjoint;
}
}
pollFence(t) {
return new Promise((e) => {
this.addItemToPoll(() => t.isFencePassed(), () => e());
});
}
pollItems() {
const t = mM(this.itemsToPoll.map((e) => e.isDoneFn));
for (let e = 0; e <= t; ++e) {
const { resolveFn: s } = this.itemsToPoll[e];
s();
}
this.itemsToPoll = this.itemsToPoll.slice(t + 1);
}
addItemToPoll(t, e) {
if (this.itemsToPoll.push({ isDoneFn: t, resolveFn: e }), this.itemsToPoll.length > 1)
return;
let s;
"setTimeoutCustom" in P().platform && (s = P().platform.setTimeoutCustom.bind(P().platform)), ep(() => (this.pollItems(), this.itemsToPoll.length === 0), () => 0, null, s);
}
bindTextureToFrameBuffer(t) {
this.throwIfDisposed(), kc(this.gl, t, this.framebuffer), this.debug && Zi(this.gl);
}
unbindTextureToFrameBuffer() {
this.outputTexture != null ? (kc(this.gl, this.outputTexture, this.framebuffer), this.debug && Zi(this.gl)) : af(this.gl, this.framebuffer);
}
downloadMatrixDriver(t, e) {
this.bindTextureToFrameBuffer(t);
const s = e();
return this.unbindTextureToFrameBuffer(), s;
}
setOutputMatrixTextureDriver(t, e, s) {
this.throwIfDisposed();
const o = this.gl;
kc(o, t, this.framebuffer), this.debug && Zi(o), this.outputTexture = t, nt(o, () => o.viewport(0, 0, e, s)), nt(o, () => o.scissor(0, 0, e, s));
}
setOutputMatrixWriteRegionDriver(t, e, s, o) {
this.throwIfDisposed(), nt(this.gl, () => this.gl.scissor(t, e, s, o));
}
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 mM(n) {
let t = 0;
for (; t < n.length && n[t](); ++t)
;
return t - 1;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const { addImpl: gM, bincountImpl: Oy, bincountReduceImpl: xM, bitwiseAndImpl: bM, castImpl: yM, ceilImpl: wM, concatImpl: CM, equalImpl: $M, expImpl: IM, expm1Impl: kM, floorImpl: vM, gatherNdImpl: SM, gatherV2Impl: NM, greaterImpl: TM, greaterEqualImpl: EM, lessImpl: RM, lessEqualImpl: DM, linSpaceImpl: AM, logImpl: FM, maxImpl: OM, maximumImpl: _M, minimumImpl: LM, multiplyImpl: MM, negImpl: PM, notEqualImpl: zM, prodImpl: BM, raggedGatherImpl: VM, raggedRangeImpl: WM, raggedTensorToTensorImpl: UM, rangeImpl: GM, rsqrtImpl: HM, scatterImpl: KM, sigmoidImpl: jM, simpleAbsImpl: _y, sliceImpl: XM, sparseFillEmptyRowsImpl: qM, sparseReshapeImpl: YM, sparseSegmentReductionImpl: Ly, sqrtImpl: JM, staticRegexReplaceImpl: ZM, stridedSliceImpl: QM, stringNGramsImpl: tP, stringSplitImpl: eP, stringToHashBucketFastImpl: nP, subImpl: sP, tileImpl: oP, topKImpl: rP, transposeImpl: Yd, uniqueImpl: iP } = cR;
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function My(n, t) {
return ["x", "y", "z", "w", "u", "v"].slice(0, t).map((e) => `${n}.${e}`);
}
function Ee(n, t) {
return t === 1 ? [n] : My(n, t);
}
function aP(n, t) {
if (n === 1)
return "rc";
let e = "";
for (let s = 0; s < n; s++)
e += t[s], s < n - 1 && (e += ",");
return e;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class lP {
constructor(t) {
if (this.variableNames = ["A"], this.packedInputs = !1, this.packedOutput = !0, this.outputShape = t, this.rank = t.length, this.enableShapeUniforms = ve(this.outputShape.length), this.rank === 0)
this.userCode = `
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;
else {
const e = Ee("rc", this.rank), s = Ot(this.rank), o = this.getOutOfBoundsCondition(e), r = this.getSetup(e), i = this.getOutput(e);
this.userCode = `
void main() {
${s} rc = getOutputCoords();
if(${o}) {
setOutput(vec4(0));
} else {
${r}
setOutput(vec4(${i}));
}
}
`;
}
}
getSourceCoordsArr(t) {
const e = [];
for (let s = 0; s <= 1; s++)
for (let o = 0; o <= 1; o++) {
let r = `${s === 0 ? "r" : "rp1"}, ${o === 0 ? "c" : "cp1"}`;
for (let i = 2; i < this.rank; i++)
r = `${t[t.length - 1 - i]},` + r;
e.push(r);
}
return e;
}
getOutOfBoundsCondition(t) {
if (this.rank === 1)
return `rc > ${this.enableShapeUniforms ? "outShape" : this.outputShape[0]}`;
let e = "";
for (let s = this.rank - 2; s < this.rank; s++)
e += `${t[s]} >= ${this.enableShapeUniforms ? `outShape[${s}]` : this.outputShape[s]}`, s < this.rank - 1 && (e += "||");
return e;
}
getSetup(t) {
if (this.rank === 1)
return "";
const e = t.slice(-2), s = this.enableShapeUniforms ? `outShape[${this.rank} - 1]` : this.outputShape[this.rank - 1], o = this.enableShapeUniforms ? `outShape[${this.rank} - 2]` : this.outputShape[this.rank - 2];
return `
int r = ${e[0]};
int c = ${e[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${s};
bool rEdge = rp1 >= ${o};
`;
}
getOutput(t) {
const e = this.getSourceCoordsArr(t);
return this.rank === 1 ? `getA(rc), (rc + 1 >= ${this.enableShapeUniforms ? "outShape" : this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0` : `getA(${e[0]}),
cEdge ? 0. : getA(${e[1]}),
rEdge ? 0. : getA(${e[2]}),
rEdge || cEdge ? 0. : getA(${e[3]})`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Py {
constructor(t, e) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0, this.customUniforms = [{ name: "inputShape", type: "ivec3" }], this.outputShape = t, this.enableShapeUniforms = ve(this.outputShape.length);
let s = "";
for (let o = 0; o < 4; o++) {
let r = "thisRC = rc;";
o % 2 === 1 && (r += "thisRC.z += 1;"), o > 1 && (r += "thisRC.y += 1;"), s += `
${r}
${o > 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[${o}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${o > 0 ? "}" : ""}
`;
}
this.userCode = `
${cP(e, this.enableShapeUniforms)}
${this.enableShapeUniforms ? Xd() : jd(t)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${this.enableShapeUniforms ? "outShape[1]" : t[1]};
int cols = ${this.enableShapeUniforms ? "outShape[2]" : t[2]};
${s}
setOutput(result);
}
`;
}
}
function cP(n, t) {
return `
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t ? aL(["r", "c", "d"], "inputShape") : co(["r", "c", "d"], n)}
return ivec3(r, c, d);
}
`;
}
/**
* @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.
* =============================================================================
*/
class uP {
constructor(t) {
this.gpgpu = t, this.numUsedTextures = 0, this.numFreeTextures = 0, this._numBytesAllocated = 0, this._numBytesFree = 0, this.freeTextures = {}, this.usedTextures = {}, this.logEnabled = !1;
}
acquireTexture(t, e, s) {
const o = df(e, s), r = pf(t, o, s);
r in this.freeTextures || (this.freeTextures[r] = []), r in this.usedTextures || (this.usedTextures[r] = []);
const i = hf(t, o, this.gpgpu.gl, this.gpgpu.textureConfig, s);
if (this.freeTextures[r].length > 0) {
this.numFreeTextures--, this.numUsedTextures++, this._numBytesFree -= i, this.log();
const l = this.freeTextures[r].pop();
return this.usedTextures[r].push(l), l;
}
let a;
return o === me.PACKED_2X2_FLOAT32 ? a = this.gpgpu.createPackedMatrixTexture(t[0], t[1]) : o === me.PACKED_2X2_FLOAT16 ? a = this.gpgpu.createFloat16PackedMatrixTexture(t[0], t[1]) : o === me.UNPACKED_FLOAT32 ? a = this.gpgpu.createFloat32MatrixTexture(t[0], t[1]) : o === me.UNPACKED_FLOAT16 ? a = this.gpgpu.createFloat16MatrixTexture(t[0], t[1]) : o === me.PACKED_4X1_UNSIGNED_BYTE && (a = this.gpgpu.createUnsignedBytesMatrixTexture(t[0], t[1])), this.usedTextures[r].push(a), this.numUsedTextures++, this._numBytesAllocated += i, this.log(), a;
}
releaseTexture(t, e, s, o) {
if (this.freeTextures == null)
return;
const r = df(s, o), i = pf(e, r, o);
i in this.freeTextures || (this.freeTextures[i] = []);
const a = hf(e, r, this.gpgpu.gl, this.gpgpu.textureConfig, o), l = P().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");
l !== -1 && this._numBytesAllocated > l ? (this.gpgpu.deleteMatrixTexture(t.texture), this._numBytesAllocated -= a) : (this.freeTextures[i].push(t), this.numFreeTextures++, this._numBytesFree += a), this.numUsedTextures--;
const c = this.usedTextures[i], u = c && c.indexOf(t);
if (u == null || u < 0)
throw new Error("Cannot release a texture that was never provided by this texture manager");
c[u] = c[c.length - 1], c.pop(), this.log();
}
log() {
if (!this.logEnabled)
return;
const t = this.numFreeTextures + this.numUsedTextures;
console.log("Free/Used", `${this.numFreeTextures} / ${this.numUsedTextures}`, `(${t})`);
const e = this._numBytesFree / this._numBytesAllocated;
console.log(`Bytes allocated: ${this._numBytesAllocated}`), console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100 * e)}%)`);
}
get numBytesAllocated() {
return this._numBytesAllocated;
}
get numBytesFree() {
return this._numBytesFree;
}
getNumUsedTextures() {
return this.numUsedTextures;
}
getNumFreeTextures() {
return this.numFreeTextures;
}
dispose() {
if (this.freeTextures != null) {
for (const t in this.freeTextures)
this.freeTextures[t].forEach((e) => {
this.gpgpu.deleteMatrixTexture(e.texture);
});
for (const t in this.usedTextures)
this.usedTextures[t].forEach((e) => {
this.gpgpu.deleteMatrixTexture(e.texture);
});
this.freeTextures = null, this.usedTextures = null, this.numUsedTextures = 0, this.numFreeTextures = 0, this._numBytesAllocated = 0, this._numBytesFree = 0;
}
}
}
function hP(n, t) {
const e = n;
if (t === e.R32F)
return 4;
if (t === e.R16F)
return 2;
if (t === e.RGBA32F)
return 16;
if (t === n.RGBA)
return 16;
if (t === e.RGBA16F)
return 8;
if (t === e.RGBA8)
return 4;
throw new Error(`Unknown internal format ${t}`);
}
function hf(n, t, e, s, o) {
const r = dP(t, s);
let i;
if (o) {
const [l, c] = Ho(n[0], n[1]);
i = l * c;
} else {
const [l, c] = Pi(n[0], n[1]);
i = l * c;
}
const a = hP(e, r);
return i * a;
}
function dP(n, t) {
switch (n) {
case me.PACKED_2X2_FLOAT32:
return Ay(t);
case me.PACKED_2X2_FLOAT16:
return Fy(t);
case me.UNPACKED_FLOAT32:
return Ey(t);
case me.UNPACKED_FLOAT16:
return Ry(t);
case me.PACKED_4X1_UNSIGNED_BYTE:
return Dy(t);
default:
throw new Error(`Unknown physical texture type ${n}`);
}
}
function pP(n) {
return P().getBool("WEBGL_RENDER_FLOAT32_ENABLED") ? n ? me.PACKED_2X2_FLOAT32 : me.UNPACKED_FLOAT32 : n ? me.PACKED_2X2_FLOAT16 : me.UNPACKED_FLOAT16;
}
function df(n, t) {
if (n === Xe.UPLOAD)
return me.PACKED_2X2_FLOAT32;
if (n === Xe.RENDER || n == null)
return pP(t);
if (n === Xe.DOWNLOAD || n === Xe.PIXELS)
return me.PACKED_4X1_UNSIGNED_BYTE;
throw new Error(`Unknown logical texture type ${n}`);
}
function pf(n, t, e) {
return `${n[0]}_${n[1]}_${t}_${e}`;
}
/**
* @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.
* =============================================================================
*/
class En {
constructor(t, e) {
this.variableNames = ["A"], this.outputShape = t, this.enableShapeUniforms = ve(this.outputShape.length), this.userCode = `
float unaryOperation(float x) {
${e}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`;
}
}
const un = "if (isnan(x)) return x;", fP = "return x;", ff = "return abs(x);", mP = "return (x >= 0.0) ? x : (exp(x) - 1.0);", gP = un + `
return (x < 0.0) ? 0.0 : x;
`, xP = un + `
return (x < 0.0) ? 0.0 : min(6.0, x);
`, rs = "return x;", bP = "return 1.0 / (1.0 + exp(-1.0 * x));";
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const yP = "return x;", wP = `
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;
`, CP = `
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;
`, $P = `
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;
`, IP = "return 1.0 / (1.0 + exp(-1.0 * x));";
class ls {
constructor(t, e) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0, this.outputShape = t, this.enableShapeUniforms = ve(this.outputShape.length), this.userCode = `
vec4 unaryOperation(vec4 x) {
${e}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class kP {
constructor(t) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !1, this.outputShape = t, this.enableShapeUniforms = ve(this.outputShape.length);
const e = t.length, s = Ee("rc", e), o = Ot(e), r = aP(e, s), i = s.slice(-2), a = e <= 1 ? "rc" : `vec2(${i.join(",")})`;
this.userCode = `
void main() {
${o} rc = getOutputCoords();
vec4 packedInput = getA(${r});
setOutput(getChannel(packedInput, ${a}));
}
`;
}
}
/**
* @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.
* =============================================================================
*/
const vP = lg, SP = 1e-7, NP = 1e-4, ea = {};
function TP(n) {
return n in ea || (ea[n] = {}), ea[n];
}
const EP = P().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"), RP = 600;
function DP() {
return P().global.screen == null ? 1024 : P().global.screen.height * P().global.screen.width * window.devicePixelRatio * RP / 1024 / 1024;
}
class rc extends wu {
nextDataId() {
return rc.nextDataId++;
}
constructor(t) {
if (super(), this.pendingRead = /* @__PURE__ */ new WeakMap(), this.pendingDisposal = /* @__PURE__ */ new WeakSet(), this.dataRefCount = /* @__PURE__ */ new WeakMap(), this.numBytesInGPU = 0, this.uploadWaitMs = 0, this.downloadWaitMs = 0, this.lastGlFlushTime = 0, this.warnedAboutMemory = !1, this.pendingDeletes = 0, this.disposed = !1, !P().getBool("HAS_WEBGL"))
throw new Error("WebGL is not supported on this device");
let e;
if (t != null) {
if (t instanceof Nc)
e = t;
else {
const s = $n(P().getNumber("WEBGL_VERSION"), t);
e = new Nc(s);
}
this.binaryCache = {}, this.gpgpuCreatedLocally = !1;
} else {
const s = $n(P().getNumber("WEBGL_VERSION"));
e = new Nc(s), this.binaryCache = TP(P().getNumber("WEBGL_VERSION")), this.gpgpuCreatedLocally = !0;
}
this.gpgpu = e, this.canvas = this.gpgpu.gl.canvas, this.textureManager = new uP(this.gpgpu), this.numMBBeforeWarning = DP(), this.texData = new Of(this, kn());
}
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(t, e, s, o, r, i) {
const a = this.makeTensorInfo(e, s), l = this.texData.get(a.dataId);
l.isPacked = !1, l.texture = { texture: t, texShape: [o, r] }, l.texShape = [o, r];
const c = Qi(e), u = new uf(c, !1, i), h = this.runWebGLProgram(u, [a], s, [[o, r]]);
return h.shape = e, l.texture = null, this.disposeIntermediateTensorInfo(a), h.dataId;
}
write(t, e, s) {
if ((P().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS") || P().getBool("DEBUG")) && this.checkNumericalProblems(t), s === "complex64" && t != null)
throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
const o = { id: this.nextDataId() };
return this.texData.set(o, { shape: e, dtype: s, values: t, usage: Xe.UPLOAD, refCount: 1 }), o;
}
/** Return refCount of a `TensorData`. */
refCount(t) {
return this.texData.has(t) ? this.texData.get(t).refCount : 0;
}
/** Increase refCount of a `TextureData`. */
incRef(t) {
const e = this.texData.get(t);
e.refCount++;
}
/** Decrease refCount of a `TextureData`. */
decRef(t) {
if (this.texData.has(t)) {
const e = this.texData.get(t);
e.refCount--;
}
}
move(t, e, s, o, r) {
if (P().getBool("DEBUG") && this.checkNumericalProblems(e), o === "complex64")
throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
this.texData.set(t, { shape: s, dtype: o, values: e, usage: Xe.UPLOAD, refCount: r });
}
disposeIntermediateTensorInfo(t) {
this.disposeData(t.dataId);
}
readSync(t) {
const e = this.texData.get(t), { values: s, dtype: o, complexTensorInfos: r, slice: i, shape: a, isPacked: l } = e;
if (i != null) {
let d;
l ? d = new ls(a, rs) : d = new En(a, rs);
const p = this.runWebGLProgram(d, [{ dataId: t, shape: a, dtype: o }], o), f = this.readSync(p.dataId);
return this.disposeIntermediateTensorInfo(p), f;
}
if (s != null)
return this.convertAndCacheOnCPU(t);
if (o === "string")
return s;
const c = this.activeTimers != null;
let u;
c && (u = Fe());
let h;
if (o === "complex64") {
const d = this.readSync(r.real.dataId), p = this.readSync(r.imag.dataId);
h = qn(d, p);
} else
h = this.getValuesFromTexture(t);
return c && (this.downloadWaitMs += Fe() - u), this.convertAndCacheOnCPU(t, h);
}
async read(t) {
if (this.pendingRead.has(t)) {
const f = this.pendingRead.get(t);
return new Promise((m) => f.push(m));
}
const e = this.texData.get(t), { values: s, shape: o, slice: r, dtype: i, complexTensorInfos: a, isPacked: l } = e;
if (r != null) {
let f;
l ? f = new ls(o, rs) : f = new En(o, rs);
const m = this.runWebGLProgram(f, [{ dataId: t, shape: o, dtype: i }], i), g = this.read(m.dataId);
return this.disposeIntermediateTensorInfo(m), g;
}
if (s != null)
return this.convertAndCacheOnCPU(t);
if (P().getBool("DEBUG") && !P().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED") && P().getNumber("WEBGL_VERSION") === 2)
throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");
let c = null, u;
if (i !== "complex64" && P().get("WEBGL_BUFFER_SUPPORTED")) {
u = this.decode(t);
const f = this.texData.get(u.dataId);
c = this.gpgpu.createBufferFromTexture(f.texture.texture, ...Yi(o));
}
this.pendingRead.set(t, []), i !== "complex64" && await this.gpgpu.createAndWaitForFence();
let h;
if (i === "complex64") {
const f = await Promise.all([
this.read(a.real.dataId),
this.read(a.imag.dataId)
]), m = f[0], g = f[1];
h = qn(m, g);
} else if (c == null)
h = this.getValuesFromTexture(t);
else {
const f = G(o);
h = this.gpgpu.downloadFloat32MatrixFromBuffer(c, f);
}
if (u != null && this.disposeIntermediateTensorInfo(u), c != null) {
const f = this.gpgpu.gl;
nt(f, () => f.deleteBuffer(c));
}
const d = this.convertAndCacheOnCPU(t, h), p = this.pendingRead.get(t);
return this.pendingRead.delete(t), p.forEach((f) => f(d)), this.pendingDisposal.has(t) && (this.pendingDisposal.delete(t), this.disposeData(t) && kn().removeDataId(t, this), this.pendingDeletes--), d;
}
/**
* 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(t, e = {}) {
const s = this.texData.get(t), { values: o, shape: r, slice: i, dtype: a, isPacked: l, texture: c } = s;
if (a === "complex64")
throw new Error("Does not support reading texture for complex64 dtype.");
if (i != null) {
let p;
l ? p = new ls(r, rs) : p = new En(r, rs);
const f = this.runWebGLProgram(p, [{ dataId: t, shape: r, dtype: a }], a), m = this.readToGPU(f, e);
return this.disposeIntermediateTensorInfo(f), m;
}
if (c == null)
throw o != null ? new Error("Data is not on GPU but on CPU.") : new Error("There is no data on GPU or CPU.");
const u = this.decode(t, e.customTexShape), h = kn().makeTensorFromTensorInfo(u), d = this.texData.get(u.dataId);
return Object.assign({ tensorRef: h }, d.texture);
}
bufferSync(t) {
const e = this.readSync(t.dataId);
if (t.dtype === "string")
try {
const s = e.map((o) => ps(o));
return yt(t.shape, t.dtype, s);
} catch {
throw new Error("Failed to decode encoded string bytes into utf-8");
}
return yt(t.shape, t.dtype, e);
}
checkNumericalProblems(t) {
if (t != null)
for (let e = 0; e < t.length; e++) {
const s = t[e];
if (!O_(s))
throw P().getBool("WEBGL_RENDER_FLOAT32_CAPABLE") ? Error(`The value ${s} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`) : Error(`The value ${s} cannot be represented on this device.`);
}
}
getValuesFromTexture(t) {
const { shape: e, dtype: s, isPacked: o } = this.texData.get(t), r = G(e);
if (P().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")) {
const d = this.decode(t), p = this.texData.get(d.dataId), f = this.gpgpu.downloadMatrixFromPackedTexture(p.texture.texture, ...Yi(e)).subarray(0, r);
return this.disposeIntermediateTensorInfo(d), f;
}
const i = P().getBool("WEBGL_PACK") && o === !0, a = i ? Qi(e) : e, l = i ? new YL(a) : new qL(a), c = this.runWebGLProgram(l, [{ shape: a, dtype: s, dataId: t }], "float32"), u = this.texData.get(c.dataId), h = this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture, u.texShape[0], u.texShape[1]).subarray(0, r);
return this.disposeIntermediateTensorInfo(c), h;
}
timerAvailable() {
return P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0;
}
time(t) {
const e = this.activeTimers, s = [];
let o = !1;
this.programTimersStack == null ? (this.programTimersStack = s, o = !0) : this.activeTimers.push(s), this.activeTimers = s, t();
const r = Ws(this.activeTimers.map((l) => l.query)).filter((l) => l != null), i = Ws(this.activeTimers.map((l) => l.name)).filter((l) => l != null);
this.activeTimers = e, o && (this.programTimersStack = null);
const a = {
uploadWaitMs: this.uploadWaitMs,
downloadWaitMs: this.downloadWaitMs,
kernelMs: null,
wallMs: null
// will be filled by the engine
};
return (async () => {
if (P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
const l = await Promise.all(r);
a.kernelMs = L1(l), a.getExtraProfileInfo = () => l.map((c, u) => ({ name: i[u], ms: c })).map((c) => `${c.name}: ${c.ms}`).join(", ");
} else
a.kernelMs = {
error: "WebGL query timers are not supported in this environment."
};
return this.uploadWaitMs = 0, this.downloadWaitMs = 0, a;
})();
}
memory() {
return {
unreliable: !1,
numBytesInGPU: this.numBytesInGPU,
numBytesInGPUAllocated: this.textureManager.numBytesAllocated,
numBytesInGPUFree: this.textureManager.numBytesFree
};
}
startTimer() {
return P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0 ? this.gpgpu.beginQuery() : { startMs: Fe(), endMs: null };
}
endTimer(t) {
return P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0 ? (this.gpgpu.endQuery(), t) : (t.endMs = Fe(), t);
}
async getQueryTime(t) {
if (P().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0)
return this.gpgpu.waitForQueryAndGetTime(t);
const e = t;
return e.endMs - e.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(t, e = !1) {
if (this.pendingDisposal.has(t))
return !1;
if (!this.texData.has(t))
return !0;
if (e ? this.texData.get(t).refCount = 0 : this.texData.get(t).refCount--, !e && this.texData.get(t).refCount > 0)
return !1;
if (this.pendingRead.has(t))
return this.pendingDisposal.add(t), this.pendingDeletes++, !1;
this.releaseGPUData(t);
const { complexTensorInfos: s } = this.texData.get(t);
return s != null && (this.disposeData(s.real.dataId, e), this.disposeData(s.imag.dataId, e)), this.texData.delete(t), !0;
}
releaseGPUData(t) {
const { texture: e, dtype: s, texShape: o, usage: r, isPacked: i, slice: a } = this.texData.get(t), l = a && a.origDataId || t, c = this.dataRefCount.get(l);
c > 1 ? this.dataRefCount.set(l, c - 1) : (this.dataRefCount.delete(l), e != null && (this.numBytesInGPU -= this.computeBytes(o, s), this.textureManager.releaseTexture(e, o, r, i)));
const u = this.texData.get(t);
u.texture = null, u.texShape = null, u.isPacked = !1, u.slice = null;
}
getTexture(t) {
return this.uploadToGPU(t), this.texData.get(t).texture.texture;
}
/**
* Returns internal information for the specific data bucket. Used in unit
* tests.
*/
getDataInfo(t) {
return this.texData.get(t);
}
/*
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(t, e = EP) {
return P().getBool("WEBGL_CPU_FORWARD") && t.every((s) => this.texData.get(s.dataId).texture == null && G(s.shape) < e);
}
getGPGPUContext() {
return this.gpgpu;
}
where(t) {
je("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");
const e = t.dataSync();
return vP(t.shape, e);
}
packedUnaryOp(t, e, s) {
const o = new ls(t.shape, e), r = this.compileAndRun(o, [t], s);
return kn().makeTensorFromTensorInfo(r);
}
// 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(t) {
if (this.shouldExecuteOnCPU([t]) && t.dtype !== "complex64") {
const o = _y(this.texData.get(t.dataId).values);
return this.makeOutput(t.shape, t.dtype, o);
}
if (P().getBool("WEBGL_PACK_UNARY_OPERATIONS"))
return this.packedUnaryOp(t, ff, t.dtype);
const e = new En(t.shape, ff), s = this.compileAndRun(e, [t]);
return kn().makeTensorFromTensorInfo(s);
}
makeTensorInfo(t, e, s) {
let o;
if (e === "string" && s != null && s.length > 0 && vr(s[0])) {
const r = s.map((i) => us(i));
o = this.write(r, t, e);
} else
o = this.write(s, t, e);
return this.texData.get(o).usage = null, { dataId: o, shape: t, dtype: e };
}
makeOutput(t, e, s) {
return kn().makeTensorFromTensorInfo(this.makeTensorInfo(t, e, s), this);
}
unpackTensor(t) {
const e = new kP(t.shape);
return this.runWebGLProgram(e, [t], t.dtype);
}
packTensor(t) {
const e = new lP(t.shape), s = !0;
return this.runWebGLProgram(e, [t], t.dtype, null, s);
}
packedReshape(t, e) {
const s = [
Oo(t.shape),
..._o(t.shape)
], o = {
dtype: t.dtype,
shape: s,
dataId: t.dataId
}, r = [
Oo(e),
..._o(e)
], i = new Py(r, s), a = !0, l = [s], c = this.runWebGLProgram(i, [o], t.dtype, l, a);
return { dataId: c.dataId, shape: e, dtype: c.dtype };
}
decode(t, e) {
const s = this.texData.get(t), { isPacked: o, shape: r, dtype: i } = s;
if (e != null) {
const d = G(r), p = e[0] * e[1] * 4;
I(d <= p, () => "customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.");
}
const a = Qi(r);
let l;
o ? l = new XL(a) : l = new jL(a);
const c = !0, u = [e ?? Yi(a)], h = this.runWebGLProgram(l, [{ shape: a, dtype: i, dataId: t }], i, u, c, e);
return { dtype: i, shape: r, dataId: h.dataId };
}
runWebGLProgram(t, e, s, o, r = !1, i) {
const a = this.makeTensorInfo(t.outputShape, s), l = this.texData.get(a.dataId);
if (t.packedOutput && (l.isPacked = !0), t.outPackingScheme === Cr.DENSE) {
const x = i ?? Yi(t.outputShape);
l.texShape = x.map((b) => b * 2);
}
if (t.outTexUsage != null && (l.usage = t.outTexUsage), G(a.shape) === 0)
return l.values = we(a.dtype, 0), a;
const c = [], u = e.map((x) => {
if (x.dtype === "complex64")
throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");
let b = this.texData.get(x.dataId);
if (b.texture == null) {
if (!t.packedInputs && G(x.shape) <= P().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))
return {
shape: x.shape,
texData: null,
isUniform: !0,
uniformValues: b.values
};
t.packedInputs && (b.isPacked = !0, b.shape = x.shape);
}
if (this.uploadToGPU(x.dataId), !!b.isPacked != !!t.packedInputs)
x = b.isPacked ? this.unpackTensor(x) : this.packTensor(x), c.push(x), b = this.texData.get(x.dataId);
else if (b.isPacked && !Ea(b.shape, x.shape)) {
const w = x, y = x.shape;
x.shape = b.shape, x = this.packedReshape(x, y), c.push(x), b = this.texData.get(x.dataId), w.shape = y;
}
return { shape: x.shape, texData: b, isUniform: !1 };
});
this.uploadToGPU(a.dataId);
const h = { shape: a.shape, texData: l, isUniform: !1 }, d = KL(t, u, h), p = this.getAndSaveBinary(d, () => GL(this.gpgpu, t, u, h)), f = this.activeTimers != null;
let m;
f && (m = this.startTimer()), P().get("ENGINE_COMPILE_ONLY") || HL(this.gpgpu, p, u, h, o), c.forEach((x) => this.disposeIntermediateTensorInfo(x)), f && (m = this.endTimer(m), this.activeTimers.push({ name: t.constructor.name, query: this.getQueryTime(m) }));
const g = P().getNumber("WEBGL_FLUSH_THRESHOLD");
if (g > 0) {
const x = Fe();
x - this.lastGlFlushTime > g && (this.gpgpu.gl.flush(), this.lastGlFlushTime = x);
}
if (!P().getBool("WEBGL_LAZILY_UNPACK") && l.isPacked && r === !1) {
const x = this.unpackTensor(a);
return this.disposeIntermediateTensorInfo(a), x;
}
return a;
}
compileAndRun(t, e, s, o, r = !1) {
return s = s || e[0].dtype, this.runWebGLProgram(t, e, s, o, r);
}
getAndSaveBinary(t, e) {
return t in this.binaryCache || (this.binaryCache[t] = e()), this.binaryCache[t];
}
getTextureManager() {
return this.textureManager;
}
dispose() {
this.disposed || (P().getBool("IS_TEST") || Object.keys(this.binaryCache).forEach((e) => {
this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram), delete this.binaryCache[e];
}), this.textureManager.dispose(), this.canvas != null && typeof HTMLCanvasElement < "u" && this.canvas instanceof HTMLCanvasElement ? this.canvas.remove() : this.canvas = null, this.gpgpuCreatedLocally && (this.gpgpu.program = null, this.gpgpu.dispose()), this.disposed = !0);
}
floatPrecision() {
return this.floatPrecisionValue == null && (this.floatPrecisionValue = _(() => {
if (!P().get("WEBGL_RENDER_FLOAT32_ENABLED")) {
const t = P().getBool("DEBUG");
P().set("DEBUG", !1);
const e = this.abs(Tt(1e-8)).dataSync()[0];
if (P().set("DEBUG", t), e > 0)
return 32;
}
return 16;
})), this.floatPrecisionValue;
}
/** Returns the smallest representable number. */
epsilon() {
return this.floatPrecision() === 32 ? SP : NP;
}
uploadToGPU(t) {
const e = this.texData.get(t), { shape: s, dtype: o, values: r, texture: i, usage: a, isPacked: l } = e;
if (i != null)
return;
const c = this.activeTimers != null;
let u;
c && (u = Fe());
let h = e.texShape;
if (h == null && (h = Z_(s, l), e.texShape = h), r != null) {
const d = Qi(s);
let p, f = h[1], m = h[0];
const g = r instanceof Uint8Array || r instanceof Uint8ClampedArray;
(l || !g) && ([f, m] = Ho(h[0], h[1])), l ? p = new ZL(d, g) : p = new uf(d, g);
const x = g ? [m, f] : h, b = this.makeTensorInfo(x, o), w = this.texData.get(b.dataId);
g ? w.usage = Xe.PIXELS : w.usage = Xe.UPLOAD, w.texShape = x, this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId), f, m, r);
const y = [[m, f]], C = !0, $ = this.runWebGLProgram(p, [b], o, y, C), k = this.texData.get($.dataId);
e.texShape = k.texShape, e.isPacked = k.isPacked, e.usage = k.usage, P().get("ENGINE_COMPILE_ONLY") ? this.disposeData($.dataId) : (e.texture = k.texture, e.values = null, this.texData.delete($.dataId)), this.disposeIntermediateTensorInfo(b), c && (this.uploadWaitMs += Fe() - u);
} else {
const d = this.acquireTexture(h, a, o, l);
e.texture = d;
}
}
convertAndCacheOnCPU(t, e) {
const s = this.texData.get(t), { dtype: o } = s;
return e != null && (s.values = AP(e, o)), s.values;
}
acquireTexture(t, e, s, o) {
if (this.numBytesInGPU += this.computeBytes(t, s), !this.warnedAboutMemory && this.numBytesInGPU > this.numMBBeforeWarning * 1024 * 1024) {
const r = (this.numBytesInGPU / 1024 / 1024).toFixed(2);
this.warnedAboutMemory = !0, console.warn(`High memory usage in GPU: ${r} MB, most likely due to a memory leak`);
}
return this.textureManager.acquireTexture(t, e, o);
}
computeBytes(t, e) {
return t[0] * t[1] * ra(e);
}
checkCompileCompletion() {
for (const [, t] of Object.entries(this.binaryCache))
this.checkCompletion_(t);
}
async checkCompileCompletionAsync() {
const t = [];
if (this.gpgpu.parallelCompilationExtension) {
for (const [, e] of Object.entries(this.binaryCache))
t.push(this.checkCompletionAsync_(e));
return Promise.all(t);
} else {
for (const [, e] of Object.entries(this.binaryCache)) {
const s = new Promise((o) => {
try {
this.checkCompletion_(e), o(!0);
} catch (r) {
throw r;
}
});
t.push(s);
}
return Promise.all(t);
}
}
async checkCompletionAsync_(t) {
return this.gpgpu.gl.getProgramParameter(t.webGLProgram, this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR) ? this.checkCompletion_(t) : (await vg(), this.checkCompletionAsync_(t));
}
checkCompletion_(t) {
if (this.gpgpu.gl.getProgramParameter(t.webGLProgram, this.gpgpu.gl.LINK_STATUS) === !1)
throw console.log(this.gpgpu.gl.getProgramInfoLog(t.webGLProgram)), this.gpgpu.gl.getShaderParameter(t.fragmentShader, this.gpgpu.gl.COMPILE_STATUS) === !1 ? (Iy(t.source, this.gpgpu.gl.getShaderInfoLog(t.fragmentShader)), new Error("Failed to compile fragment shader.")) : new Error("Failed to link vertex and fragment shaders.");
return !0;
}
getUniformLocations() {
for (const t of Object.values(this.binaryCache)) {
this.gpgpu.buildVao(t.webGLProgram);
const { variablesLocations: e, customUniformLocations: s, infLoc: o, nanLoc: r, outShapeLocation: i, outShapeStridesLocation: a, outTexShapeLocation: l } = Ty(this.gpgpu, t.program, t.webGLProgram);
t.variablesLocations = e, t.customUniformLocations = s, t.infLoc = o, t.nanLoc = r, t.outShapeLocation = i, t.outShapeStridesLocation = a, t.outTexShapeLocation = l;
}
}
/**
* Create a TF.js tensor out of an existing WebGL texture. A new texture will
* be created.
*/
createTensorFromGPUData(t, e, s) {
t.channels = t.channels || "RGBA";
const { texture: o, height: r, width: i, channels: a } = t, l = kn().backend;
if (!l.gpgpu.gl.isTexture(o))
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 c = l.writeTexture(o, e, s, r, i, a);
return kn().makeTensorFromDataId(c, e, s, l);
}
}
rc.nextDataId = 0;
function AP(n, t) {
if (t === "float32" || t === "complex64")
return n;
if (t === "int32" || t === "bool") {
const e = t === "int32" ? new Int32Array(n.length) : new Uint8Array(n.length);
for (let s = 0; s < e.length; ++s)
e[s] = Math.round(n[s]);
return e;
} else
throw new Error(`Unknown dtype ${t}`);
}
/**
* @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.
* =============================================================================
*/
Cm() && vm(
"webgl",
() => new rc(),
2
/* priority */
);
/**
* @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.
* =============================================================================
*/
const Jd = `
if (isnan(a)) return a;
if (isnan(b)) return b;
`;
class to {
constructor(t, e, s) {
this.variableNames = ["A", "B"], this.outputShape = mt(e, s), this.enableShapeUniforms = ve(this.outputShape.length), this.userCode = `
float binaryOperation(float a, float b) {
${t}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ho = `
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;
`;
class Yo {
constructor(t, e, s, o = !1) {
this.variableNames = ["A", "B"], this.supportsBroadcasting = !0, this.packedInputs = !0, this.packedOutput = !0, this.outputShape = mt(e, s);
const r = this.outputShape.length;
this.enableShapeUniforms = ve(r);
let i = "";
if (o)
if (r === 0 || G(this.outputShape) === 1)
i = `
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;
else if (i = `
${Ot(r)} coords = getOutputCoords();
`, r === 1)
this.enableShapeUniforms ? i += `
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
` : i += `
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;
else {
const l = Ee("coords", r);
this.enableShapeUniforms ? i += `
bool nextRowOutOfBounds =
(${l[r - 2]} + 1) >= outShape[${r} - 2];
bool nextColOutOfBounds =
(${l[r - 1]} + 1) >= outShape[${r} - 1];
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
` : i += `
bool nextRowOutOfBounds =
(${l[r - 2]} + 1) >= ${this.outputShape[r - 2]};
bool nextColOutOfBounds =
(${l[r - 1]} + 1) >= ${this.outputShape[r - 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) {
${t}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${i}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function He(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
return e.incRef(s.dataId), { dataId: s.dataId, shape: s.shape, dtype: s.dtype };
}
const FP = {
kernelName: Kr,
backendName: "webgl",
kernelFunc: He
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ts(n) {
const { inputs: t, backend: e } = n, { real: s, imag: o } = t, r = e.makeTensorInfo(s.shape, "complex64"), i = e.texData.get(r.dataId), a = He({ inputs: { x: s }, backend: e }), l = He({ inputs: { x: o }, backend: e });
return i.complexTensorInfos = { real: a, imag: l }, r;
}
const OP = {
kernelName: Fu,
backendName: "webgl",
kernelFunc: Ts
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const zy = "return (a < 0.) ? b * a : a;", By = `
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
function _P(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { alpha: r } = s, i = e.makeTensorInfo([], "float32", ws(r, "float32")), a = P().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new Yo(By, o.shape, i.shape) : new to(zy, o.shape, i.shape), l = e.runWebGLProgram(a, [o, i], "float32");
return e.disposeIntermediateTensorInfo(i), l;
}
const LP = {
kernelName: Qa,
backendName: "webgl",
kernelFunc: _P
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Vy = "return (a < 0.) ? b * a : a;", Wy = `
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
function MP(n) {
const { inputs: t, backend: e } = n, { x: s, alpha: o } = t, r = P().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new Yo(Wy, s.shape, o.shape) : new to(Vy, s.shape, o.shape);
return e.runWebGLProgram(r, [s, o], "float32");
}
const PP = {
kernelName: bl,
backendName: "webgl",
kernelFunc: MP
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Jo = "if (isnan(x)) return x;";
function vt({ opSnippet: n, packedOpSnippet: t, cpuKernelImpl: e, dtype: s }) {
return ({ inputs: o, backend: r }) => {
const { x: i } = o, a = r, l = s || i.dtype;
if (a.shouldExecuteOnCPU([i]) && e != null) {
const h = a.texData.get(i.dataId), d = e(h.values, l);
return a.makeTensorInfo(i.shape, l, d);
}
const c = P().getBool("WEBGL_PACK_UNARY_OPERATIONS") && t != null;
let u;
return c ? u = new ls(i.shape, t) : u = new En(i.shape, n), a.runWebGLProgram(u, [i], l);
};
}
function ye({ opSnippet: n, packedOpSnippet: t, checkOutOfBounds: e = !1, supportsComplex: s = !1, cpuKernelImpl: o, dtype: r }) {
return ({ inputs: i, backend: a }) => {
const { a: l, b: c } = i, u = a;
if (s && l.dtype === "complex64") {
const f = u.texData.get(l.dataId), m = u.texData.get(c.dataId), [g, x] = [
[f.complexTensorInfos.real, m.complexTensorInfos.real],
[f.complexTensorInfos.imag, m.complexTensorInfos.imag]
].map((w) => {
const [y, C] = w, $ = {
dataId: y.dataId,
dtype: y.dtype,
shape: l.shape
}, k = {
dataId: C.dataId,
dtype: C.dtype,
shape: c.shape
}, v = new to(n, l.shape, c.shape);
return u.runWebGLProgram(v, [$, k], Ue(y.dtype, C.dtype));
}), b = Ts({ inputs: { real: g, imag: x }, backend: u });
return u.disposeIntermediateTensorInfo(g), u.disposeIntermediateTensorInfo(x), b;
}
const h = r || Ue(l.dtype, c.dtype);
if ((l.dtype === "string" || c.dtype === "string" || u.shouldExecuteOnCPU([l, c])) && o != null) {
const f = u.texData.get(l.dataId).values, m = u.texData.get(c.dataId).values, g = l.dtype === "string" ? (
// tslint:disable-next-line: no-any
Yn(f)
) : f, x = l.dtype === "string" ? (
// tslint:disable-next-line: no-any
Yn(m)
) : m, [b, w] = o(l.shape, c.shape, g, x, h), y = u.makeTensorInfo(w, h), C = u.texData.get(y.dataId);
return C.values = b, y;
}
const d = P().getBool("WEBGL_PACK_BINARY_OPERATIONS") && t != null;
let p;
return d ? p = new Yo(t, l.shape, c.shape, e) : p = new to(n, l.shape, c.shape), u.runWebGLProgram(p, [l, c], h);
};
}
function $r(n, t = !1) {
if (n === "linear")
return t ? yP : fP;
if (n === "relu")
return t ? CP : gP;
if (n === "elu")
return t ? wP : mP;
if (n === "relu6")
return t ? $P : xP;
if (n === "prelu")
return t ? Wy : Vy;
if (n === "leakyrelu")
return t ? By : zy;
if (n === "sigmoid")
return t ? IP : bP;
throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Uy {
constructor(t, e, s, o = !1, r = !1, i = !1, a = null, l = !1, c = !1) {
this.variableNames = ["matrixA", "matrixB"], this.packedInputs = !0, this.packedOutput = !0, this.outputShape = s, this.enableShapeUniforms = ve(this.outputShape.length);
const u = o ? t[1] : t[2], h = Math.ceil(u / 2), d = o ? "i * 2, rc.y" : "rc.y, i * 2", p = r ? "rc.z, i * 2" : "i * 2, rc.z", f = o ? ["a.xxyy", "a.zzww"] : ["a.xxzz", "a.yyww"], m = r ? ["b.xzxz", "b.ywyw"] : ["b.xyxy", "b.zwzw"];
let g = "", x = "";
a && (l ? g = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${a}
}` : c ? g = `vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${a}
}` : g = `vec4 activation(vec4 x) {
${a}
}`, x = "result = activation(result);");
const b = i ? "result += getBiasAtOutCoords();" : "";
i && this.variableNames.push("bias"), l && this.variableNames.push("preluActivationWeights"), c && this.variableNames.push("leakyreluAlpha");
let w = "rc.x", y = "rc.x";
t[0] < e[0] ? w = `imod(rc.x, ${t[0]})` : e[0] < t[0] && (y = `imod(rc.x, ${e[0]})`), this.userCode = `
${g}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${h}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
int batchA = ${w};
int batchB = ${y};
for (int i = 0; i < ${h}; i++) {
vec4 a = getMatrixA(batchA, ${d});
vec4 b = getMatrixB(batchB, ${p});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${f[0]} * ${m[0]});
result += (${f[1]} * ${m[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${b}
${x}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const mf = {
REAL: "return areal * breal - aimag * bimag;",
IMAG: "return areal * bimag + aimag * breal;"
};
class gf {
constructor(t, e, s) {
this.variableNames = ["AReal", "AImag", "BReal", "BImag"], this.outputShape = mt(e, s), this.userCode = `
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${t}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const xf = "return a * b;";
function Zd(n) {
const { inputs: t, backend: e } = n, { a: s, b: o } = t, r = Ue(s.dtype, o.dtype);
if (s.dtype === "complex64") {
const a = e.texData.get(s.dataId), l = e.texData.get(o.dataId), c = new gf(mf.REAL, s.shape, o.shape), u = new gf(mf.IMAG, s.shape, o.shape), h = [
{
dataId: a.complexTensorInfos.real.dataId,
dtype: a.complexTensorInfos.real.dtype,
shape: s.shape
},
{
dataId: a.complexTensorInfos.imag.dataId,
dtype: a.complexTensorInfos.imag.dtype,
shape: s.shape
},
{
dataId: l.complexTensorInfos.real.dataId,
dtype: l.complexTensorInfos.real.dtype,
shape: o.shape
},
{
dataId: l.complexTensorInfos.imag.dataId,
dtype: l.complexTensorInfos.imag.dtype,
shape: o.shape
}
], d = e.runWebGLProgram(c, h, "float32"), p = e.runWebGLProgram(u, h, "float32"), f = Ts({ inputs: { real: d, imag: p }, backend: e });
return e.disposeIntermediateTensorInfo(d), e.disposeIntermediateTensorInfo(p), f;
}
if (e.shouldExecuteOnCPU([s, o])) {
const a = e.texData.get(s.dataId), l = e.texData.get(o.dataId), [c, u] = MM(s.shape, o.shape, a.values, l.values, r), h = e.makeTensorInfo(u, r), d = e.texData.get(h.dataId);
return d.values = c, h;
}
let i;
return P().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? i = new Yo(xf, s.shape, o.shape) : i = new to(xf, s.shape, o.shape), e.runWebGLProgram(i, [s, o], r);
}
const zP = {
kernelName: ei,
backendName: "webgl",
kernelFunc: Zd
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function BP(n, t, e) {
const s = [
Oo(n.shape),
..._o(n.shape)
], o = {
dtype: n.dtype,
shape: s,
dataId: n.dataId
}, r = [
Oo(t),
..._o(t)
], i = new Py(r, s), a = !0, l = [s], c = e.runWebGLProgram(i, [o], n.dtype, l, a);
return { dataId: c.dataId, shape: t, dtype: c.dtype };
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function tt(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { shape: r } = s, i = e, a = G(o.shape), l = Lf(r, a), c = G(l);
I(a === c, () => `The new shape (${l}) has ${c} elements and the old shape (${o.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);
const u = i.texData.get(o.dataId);
return u.isPacked && !Ea(o.shape, l) && !(u.texture !== null && Ea(u.shape, l)) ? BP(o, l, i) : (i.incRef(o.dataId), { dataId: o.dataId, shape: l, dtype: o.dtype });
}
const VP = {
kernelName: wl,
backendName: "webgl",
kernelFunc: tt
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class bf {
constructor(t, e) {
this.variableNames = ["x"];
const { windowSize: s, batchSize: o, inSize: r, outSize: i } = t;
this.outputShape = [o, i];
const a = Math.floor(s / 4) * 4, l = s % 4;
let c = "sumValue += dot(values, ones);";
if (e != null) {
const h = 1 / e;
c = `sumValue += dot(values * ${vo(h) ? h.toPrecision(2) : h}, ones);`;
}
let u = "";
r % s > 0 && (u = `
if (inIdx < 0 || inIdx >= ${r}) {
return 0.0;
}
`), this.userCode = `
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${u}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
float sumValue = 0.0;
for (int i = 0; i < ${a}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${c}
}
int inIdx = inOffset + ${a};
if (${l === 1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${c}
} else if (${l === 2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${c}
} else if (${l === 3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${c}
}
setOutput(sumValue);
}
`;
}
}
/**
* @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.
* =============================================================================
*/
class WP {
constructor(t, e) {
this.variableNames = ["x"];
const { windowSize: s, batchSize: o, inSize: r, outSize: i } = t;
this.outputShape = [o, i];
let a = "0.0", l = "";
e === "prod" ? a = "1.0" : e === "min" ? (a = "1.0 / 1e-20", l = "min") : e === "max" && (a = "-1.0 / 1e-20", l = "max");
let c = `${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
e === "sum" ? c = "sumValue" : e === "prod" ? c = "prodValue" : e === "all" ? c = "allValue" : e === "any" && (c = "anyValue");
const u = Math.floor(s / 4) * 4, h = s % 4;
let d = `
if (${e === "sum"}) {
sumValue += dot(values, ones);
} else if (${e === "prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${l}(values, minMaxValue);
if (${e === "min"} || ${e === "max"}) {
minMaxValue = ${l}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
}
}
}
`, p = "vec4";
e === "all" ? (a = "1.0", d = `
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`, p = "bvec4") : e === "any" && (a = "0.0", d = `
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`, p = "bvec4");
let f = "";
r % s > 0 && (f = `
if (inIdx < 0 || inIdx >= ${r}) {
return initializationValue;
}
`), this.userCode = `
const float initializationValue = ${a};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${f}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
vec4 minMaxValue = vec4(${a});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${u}; i += 4) {
int inIdx = inOffset + i;
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${d}
}
int inIdx = inOffset + ${u};
if (${h === 1}) {
${p} values = ${p}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${d}
} else if (${h === 2}) {
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${d}
} else if (${h === 3}) {
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${d}
}
setOutput(${c});
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function UP(n) {
const t = [];
for (; t.length === 0 || t[t.length - 1].outSize !== 1; ) {
const e = t.length ? t[t.length - 1].outSize : n[1], s = Ul(e);
t.push({
inSize: e,
windowSize: s,
outSize: Math.ceil(e / s)
});
}
return t;
}
function po(n, t, e, s) {
const o = UP(n.shape);
let r = n;
for (let i = 0; i < o.length; i++) {
const { inSize: a, windowSize: l, outSize: c } = o[i];
let u, h;
e === "mean" ? u = i === 0 ? new bf({ windowSize: l, inSize: a, batchSize: n.shape[0], outSize: c }, a) : new bf({ windowSize: l, inSize: a, batchSize: n.shape[0], outSize: c }) : u = new WP({ windowSize: l, inSize: a, batchSize: n.shape[0], outSize: c }, e), h = r, r = s.runWebGLProgram(u, [r], t), h.dataId !== n.dataId && s.disposeIntermediateTensorInfo(h);
}
return r;
}
/**
* @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.
* =============================================================================
*/
class GP {
constructor(t, e) {
this.variableNames = ["A"];
const s = new Array(t.length);
for (let i = 0; i < s.length; i++)
s[i] = t[e[i]];
this.outputShape = s, this.rank = s.length;
const o = Ot(this.rank), r = HP(e);
this.userCode = `
void main() {
${o} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`;
}
}
function HP(n) {
const t = n.length;
if (t > 6)
throw Error(`Transpose for rank ${t} is not yet supported`);
const e = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u", "resRC.v"], s = new Array(t);
for (let o = 0; o < n.length; o++)
s[n[o]] = e[o];
return s.join();
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class KP {
constructor(t, e) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0;
const s = new Array(t.length);
for (let u = 0; u < s.length; u++)
s[u] = t[e[u]];
if (this.outputShape = s, this.rank = s.length, this.rank > 6)
throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);
const o = Ot(this.rank), r = My("rc", this.rank), i = new Array(this.rank);
for (let u = 0; u < e.length; u++)
i[e[u]] = r[u];
const a = `vec2(${i.slice(-2).join()})`, l = `++${r[this.rank - 1]} < ${s[this.rank - 1]}`, c = `getChannel(getA(${i.join()}), ${a})`;
this.userCode = `
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${c};
if(${l}) {
result[1] = ${c};
}
--${r[this.rank - 1]};
if(++${r[this.rank - 2]} < ${s[this.rank - 2]}) {
result[2] = ${c};
if(${l}) {
result[3] = ${c};
}
}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ic(n, t, e) {
const s = P().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new KP(n.shape, t) : new GP(n.shape, t);
return e.runWebGLProgram(s, [n], n.dtype);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function jP(n, t, e, s) {
const o = t, r = n.shape.length, i = wt(o, n.shape);
let a = i;
const l = jt(a, r), c = l != null;
let u = n;
c && (u = ic(n, l, s), a = Zt(a.length, r)), be("sum", a, r);
const [h, d] = pe(u.shape, a);
let p = h;
e && (p = ne(h, i));
const f = G(d), g = G(n.shape) / f, x = tt({ inputs: { x: u }, attrs: { shape: [g, f] }, backend: s }), b = ph(n.dtype), w = po(x, b, "sum", s), y = tt({ inputs: { x: w }, attrs: { shape: p }, backend: s });
return s.disposeIntermediateTensorInfo(x), s.disposeIntermediateTensorInfo(w), c && s.disposeIntermediateTensorInfo(u), y;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function ac(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s;
return jP(o, r, i, e);
}
const XP = {
kernelName: Sl,
backendName: "webgl",
kernelFunc: ac
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function De(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { perm: r } = s, i = e, a = o.shape.length, l = new Array(a);
for (let u = 0; u < l.length; u++)
l[u] = o.shape[r[u]];
let c;
if (i.shouldExecuteOnCPU([o])) {
const h = i.texData.get(o.dataId).values, d = Yd(h, o.shape, o.dtype, r, l);
c = i.makeTensorInfo(l, o.dtype);
const p = i.texData.get(c.dataId);
p.values = d;
} else
c = ic(o, r, i);
return c;
}
const qP = {
kernelName: Co,
backendName: "webgl",
kernelFunc: De
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Gy = 1e3;
function Ra({ a: n, b: t, transposeA: e, transposeB: s, backend: o, bias: r = null, preluActivationWeights: i = null, leakyreluAlpha: a = 0, activation: l = null }) {
const c = n.shape.length, u = t.shape.length, h = e ? n.shape[c - 2] : n.shape[c - 1], d = s ? t.shape[u - 1] : t.shape[u - 2], p = e ? n.shape[c - 1] : n.shape[c - 2], f = s ? t.shape[u - 2] : t.shape[u - 1], m = n.shape.slice(0, -2), g = t.shape.slice(0, -2), x = G(m), b = G(g), y = mt(n.shape.slice(0, -2), t.shape.slice(0, -2)).concat([p, f]);
I(h === d, () => `Error in matMul: inner shapes (${h}) and (${d}) of Tensors with shapes ${n.shape} and ${t.shape} and transposeA=${e} and transposeB=${s} must match.`);
const C = e ? [x, h, p] : [x, p, h], $ = s ? [b, f, d] : [b, d, f], k = tt({ inputs: { x: n }, backend: o, attrs: { shape: C } }), v = tt({ inputs: { x: t }, backend: o, attrs: { shape: $ } }), S = [k, v], T = Math.max(x, b), F = e ? k.shape[1] : k.shape[2], L = r != null, M = i != null, B = l === "leakyrelu", z = l != null ? $r(l, !0) : null, V = L || M || B || z != null;
let H;
if ((p === 1 || f === 1) && F > Gy && V === !1) {
let K = k, X = v;
e && (K = De({ inputs: { x: k }, backend: o, attrs: { perm: [0, 2, 1] } }), S.push(K)), s && (X = De({ inputs: { x: v }, backend: o, attrs: { perm: [0, 2, 1] } }), S.push(X));
const q = f !== 1, Z = f === 1;
let J = K;
q && (J = tt({
inputs: { x: K },
backend: o,
attrs: { shape: [T, F, 1] }
}), S.push(J));
const et = f === 1 ? 2 : 1;
let Q = X;
Z && (Q = tt({
inputs: { x: X },
backend: o,
attrs: { shape: [T, 1, F] }
}), S.push(Q));
const ot = Zd({ inputs: { a: J, b: Q }, backend: o });
H = ac({ inputs: { x: ot }, backend: o, attrs: { axis: et, keepDims: !0 } }), S.push(ot);
} else {
const K = Ue(n.dtype, t.dtype), X = new Uy(C, $, [T, p, f], e, s, L, z, M, B), q = [k, v];
if (r != null && q.push(r), M && q.push(i), B) {
const Z = o.makeTensorInfo([], "float32", ws(a, "float32"));
q.push(Z), S.push(Z);
}
H = o.runWebGLProgram(X, q, K);
}
const U = tt({ inputs: { x: H }, backend: o, attrs: { shape: y } });
S.push(H);
for (const K of S)
o.disposeIntermediateTensorInfo(K);
return U;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function YP(n) {
const { inputs: t, backend: e, attrs: s } = n, { a: o, b: r, bias: i, preluActivationWeights: a } = t, { transposeA: l, transposeB: c, activation: u, leakyreluAlpha: h } = s;
return Ra({
a: o,
b: r,
transposeA: l,
transposeB: c,
backend: e,
bias: i,
preluActivationWeights: a,
leakyreluAlpha: h,
activation: u
});
}
const JP = {
kernelName: ia,
backendName: "webgl",
kernelFunc: YP
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const yf = "return abs(x);";
function ZP(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
if (e.shouldExecuteOnCPU([s]) && s.dtype !== "complex64") {
const r = e.texData.get(s.dataId), i = _y(r.values);
return e.makeTensorInfo(s.shape, s.dtype, i);
}
let o;
return P().getBool("WEBGL_PACK_UNARY_OPERATIONS") ? o = new ls(s.shape, yf) : o = new En(s.shape, yf), e.runWebGLProgram(o, [s], s.dtype);
}
const QP = {
kernelName: Fa,
backendName: "webgl",
kernelFunc: ZP
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const t3 = un + `
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`, e3 = vt({ opSnippet: t3 }), n3 = {
kernelName: Sr,
backendName: "webgl",
kernelFunc: e3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const s3 = un + `
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`, o3 = vt({ opSnippet: s3 }), r3 = {
kernelName: Nr,
backendName: "webgl",
kernelFunc: o3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const wf = "return a + b;", i3 = ye({
opSnippet: wf,
packedOpSnippet: wf,
supportsComplex: !0,
cpuKernelImpl: gM
}), a3 = {
kernelName: Po,
backendName: "webgl",
kernelFunc: i3
};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class l3 {
constructor(t, e) {
this.outputShape = [], this.outputShape = t, this.variableNames = e.map((r, i) => `T${i}`);
const s = [];
this.variableNames.forEach((r) => {
s.push(`float v${r} = get${r}AtOutCoords();`);
});
const o = this.variableNames.map((r) => `v${r}`).join(" + ");
this.userCode = `
void main() {
${s.join(`
`)}
float result = ${o};
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class c3 {
constructor(t, e) {
this.outputShape = [], this.packedInputs = !0, this.packedOutput = !0, this.outputShape = t, this.variableNames = e.map((r, i) => `T${i}`);
const s = [];
this.variableNames.forEach((r) => {
s.push(`vec4 v${r} = get${r}AtOutCoords();`);
});
const o = this.variableNames.map((r) => `v${r}`).join(" + ");
this.userCode = `
void main() {
${s.join(`
`)}
vec4 result = ${o};
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function oa(n) {
const { inputs: t, backend: e } = n, s = t;
if (s.length === 1)
return He({ inputs: { x: s[0] }, backend: e });
if (s.length > P().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")) {
const l = Math.floor(s.length / 2), c = oa({ inputs: s.slice(0, l), backend: e }), u = oa({ inputs: s.slice(l), backend: e });
return oa({ inputs: [c, u], backend: e });
}
const o = s.map((l) => l.dtype).reduce((l, c) => Ue(l, c)), r = s.map((l) => l.shape), a = P().getBool("WEBGL_PACK") ? new c3(s[0].shape, r) : new l3(s[0].shape, r);
return e.runWebGLProgram(a, s, o);
}
const u3 = {
kernelName: Su,
backendName: "webgl",
kernelFunc: oa
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function h3(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s, a = o.shape.length, l = wt(r, o.shape);
let c = l;
const u = jt(c, a);
let h = o;
u != null && (h = De({ inputs: { x: o }, backend: e, attrs: { perm: u } }), c = Zt(c.length, a)), be("all", c, a);
const [d, p] = pe(h.shape, c), f = G(p), m = tt({ inputs: { x: h }, backend: e, attrs: { shape: [-1, f] } }), g = po(m, m.dtype, "all", e);
let x;
if (i) {
const b = ne(d, l);
x = tt({ inputs: { x: g }, backend: e, attrs: { shape: b } });
} else
x = tt({ inputs: { x: g }, backend: e, attrs: { shape: d } });
return e.disposeIntermediateTensorInfo(m), e.disposeIntermediateTensorInfo(g), u != null && e.disposeIntermediateTensorInfo(h), x;
}
const d3 = {
kernelName: Nu,
backendName: "webgl",
kernelFunc: h3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function p3(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s, a = o.shape.length, l = wt(r, o.shape);
let c = l;
const u = jt(c, a);
let h = o;
u != null && (h = De({ inputs: { x: o }, backend: e, attrs: { perm: u } }), c = Zt(c.length, a)), be("any", c, a);
const [d, p] = pe(h.shape, c), f = G(p), m = tt({ inputs: { x: h }, backend: e, attrs: { shape: [-1, f] } }), g = po(m, m.dtype, "any", e);
let x;
if (i) {
const b = ne(d, l);
x = tt({ inputs: { x: g }, backend: e, attrs: { shape: b } });
} else
x = tt({ inputs: { x: g }, backend: e, attrs: { shape: d } });
return e.disposeIntermediateTensorInfo(m), e.disposeIntermediateTensorInfo(g), u != null && e.disposeIntermediateTensorInfo(h), x;
}
const f3 = {
kernelName: Tu,
backendName: "webgl",
kernelFunc: p3
};
/**
* @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.
* =============================================================================
*/
class m3 {
constructor(t, e, s) {
this.variableNames = ["A"];
const { windowSize: o, batchSize: r, outSize: i } = t;
s || this.variableNames.push("bestIndicesA"), this.outputShape = [r, i];
const a = e === "max" ? ">" : "<", l = s ? "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 * ${o};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${o}; i++) {
int inIdx = ${l};
float candidate = getA(batch, inIdx);
if (candidate ${a} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class g3 {
constructor(t, e, s, o) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0, I(t.length > 2, () => `Packed arg${s.charAt(0).toUpperCase() + s.slice(1)} supports only inputs with rank above 2.`);
const r = t[t.length - 1], i = Math.ceil(r / e);
this.outputShape = t.slice(0, -1), i > 1 && this.outputShape.push(i), o || this.variableNames.push("bestIndicesA");
const a = this.outputShape, l = a.length, c = Ot(l), u = Ee("coords", l);
let h, d;
if (i === 1) {
d = l + 1;
const v = Ot(d);
h = `
${v} sourceLocR = ${v}(${u.join()}, 0);
++${u[l - 1]};
${v} sourceLocG = ${v}(${u.join()}, 0);
++${u[l - 2]};
${v} sourceLocA = ${v}(${u.join()}, 0);
--${u[l - 1]};
${v} sourceLocB = ${v}(${u.join()}, 0);
--${u[l - 2]};`;
} else
d = l, h = `
${c} sourceLocR = coords;
++${u[l - 1]};
${c} sourceLocG = coords;
++${u[l - 2]};
${c} sourceLocA = coords;
--${u[l - 1]};
${c} sourceLocB = coords;
--${u[l - 2]};`;
const p = ["x", "y", "z", "w", "u", "v"].slice(0, d), f = "." + p[d - 1], m = p.map((v) => "int " + v), g = Ee("sourceLocR", d - 1).concat("inIdx.r"), x = Ee("sourceLocG", d - 1).concat("inIdx.g"), b = Ee("sourceLocB", d - 1).concat("inIdx.b"), w = Ee("sourceLocA", d - 1).concat("inIdx.a"), y = s === "max" ? "greaterThan" : "lessThan", C = o ? "" : `
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${x.join()}),
getBestIndicesAChannel(${b.join()}),
getBestIndicesAChannel(${w.join()})));`, $ = `vec4(
getAChannel(${g.join()}),
hasNextCol ? getAChannel(${x.join()}) : 0.,
hasNextRow ? getAChannel(${b.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`, k = o ? "" : `
float getBestIndicesAChannel(${m.join()}) {
return getChannel(getBestIndicesA(${p.join()}),
vec2(${p.slice(-2).join()}));
}`;
this.userCode = `
float getAChannel(${m.join()}) {
return getChannel(getA(${p.join()}),
vec2(${p.slice(-2).join()}));
}
${k}
void main() {
${c} coords = getOutputCoords();
bool hasNextCol = ${u[l - 1]} < ${a[l - 1] - 1};
bool hasNextRow = ${u[l - 2]} < ${a[l - 2] - 1};
${h}
ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},
sourceLocB${f}, sourceLocA${f}) * ${e};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${$};
for (int i = 0; i < ${e}; i++) {
inIdx = srcIdx;
${C}
vec4 candidate = ${$};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${y}(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);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Hy(n, t, e, s = null) {
let o = t.shape[0], r = t.shape[1];
s != null && (o = s.shape[0], r = s.shape[1]);
const i = Ul(r), a = { windowSize: i, inSize: r, batchSize: o, outSize: Math.ceil(r / i) }, l = new m3(a, e, s == null), c = [t];
s != null && c.push(s);
const u = n.runWebGLProgram(l, c, "int32");
if (u.shape[1] === 1)
return u;
const h = Hy(n, t, e, u);
return n.disposeIntermediateTensorInfo(u), h;
}
function Ky(n, t, e, s = null) {
const o = s != null ? s.shape : t.shape, r = o[o.length - 1], i = Ul(r), a = new g3(o, i, e, s == null), l = s == null ? [t] : [t, s], c = n.runWebGLProgram(a, l, "int32");
if (c.shape.length === t.shape.length) {
const u = Ky(n, t, e, c);
return n.disposeIntermediateTensorInfo(c), u;
}
return c;
}
function jy(n, t, e, s) {
const o = [e];
if (be("arg" + s.charAt(0).toUpperCase() + s.slice(1), o, t.shape.length), !P().getBool("WEBGL_PACK_REDUCE") || t.shape.length <= 2) {
const r = [], i = n.texData.get(t.dataId), a = i !== null && i.isPacked;
let l = t;
a && (l = n.unpackTensor(t), r.push(l));
const [c, u] = pe(l.shape, o), h = G(u), d = tt({ inputs: { x: l }, backend: n, attrs: { shape: [-1, h] } });
r.push(d);
const p = Hy(n, d, s);
r.push(p);
const f = tt({ inputs: { x: p }, backend: n, attrs: { shape: c } });
return r.forEach((m) => n.disposeIntermediateTensorInfo(m)), f;
}
return Ky(n, t, s);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function x3(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r } = s;
let i = wt(r, o.shape);
const a = jt(i, o.shape.length);
let l = o;
const c = [];
a != null && (l = De({ inputs: { x: o }, backend: e, attrs: { perm: a } }), c.push(l), i = Zt(i.length, l.shape.length)), be("argMax", [i[0]], l.shape.length);
const u = jy(e, l, i[0], "max");
return c.forEach((h) => e.disposeIntermediateTensorInfo(h)), u;
}
const b3 = {
kernelName: Oa,
backendName: "webgl",
kernelFunc: x3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function y3(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r } = s;
let i = wt(r, o.shape);
const a = jt(i, o.shape.length);
let l = o;
const c = [];
a != null && (l = De({ inputs: { x: o }, backend: e, attrs: { perm: a } }), c.push(l), i = Zt(i.length, l.shape.length)), be("argMin", [i[0]], l.shape.length);
const u = jy(e, l, i[0], "min");
return c.forEach((h) => e.disposeIntermediateTensorInfo(h)), u;
}
const w3 = {
kernelName: _a,
backendName: "webgl",
kernelFunc: y3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const C3 = un + `
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`, $3 = vt({ opSnippet: C3 }), I3 = {
kernelName: Tr,
backendName: "webgl",
kernelFunc: $3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const k3 = un + "return log(x + sqrt(x * x + 1.0));", v3 = vt({ opSnippet: k3 }), S3 = {
kernelName: Er,
backendName: "webgl",
kernelFunc: v3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const N3 = un + `
return atan(x);
`, T3 = vt({ opSnippet: N3 }), E3 = {
kernelName: Rr,
backendName: "webgl",
kernelFunc: T3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const R3 = Jd + `
return atan(a, b);
`, D3 = `
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);
` + ho + `
return result;
`, A3 = ye({ opSnippet: R3, packedOpSnippet: D3 }), F3 = {
kernelName: Ar,
backendName: "webgl",
kernelFunc: A3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const O3 = un + `
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`, _3 = vt({ opSnippet: O3 }), L3 = {
kernelName: Dr,
backendName: "webgl",
kernelFunc: _3
};
/**
* @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.
* =============================================================================
*/
class Ir {
constructor(t, e, s, o = !1, r = !1) {
if (this.variableNames = ["x"], e === "avg" && s)
throw new Error("Cannot compute positions for average pool.");
const i = t.filterWidth, a = t.strideHeight, l = t.strideWidth, c = t.dilationHeight, u = t.dilationWidth, h = t.effectiveFilterHeight, d = t.effectiveFilterWidth, p = t.padInfo.top, f = t.padInfo.left;
this.outputShape = t.outShape;
const m = e === "avg", g = `((batch * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + d`, x = `(xR * ${t.inWidth} + xC) * ${t.inChannels} + d`;
let b = "0.0";
if (m || (b = "-1.0 / 1e-20"), s) {
const v = ">=";
this.userCode = `
const ivec2 strides = ivec2(${a}, ${l});
const ivec2 pads = ivec2(${p}, ${f});
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 < ${h};
wR += ${c}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int wC = 0; wC < ${d};
wC += ${u}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${t.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 ${v} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${o ? r ? g : x : `wR * ${d} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;
return;
}
const w = "max";
let y = `${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
e === "avg" && (y = "avgValue / max(count, 1.0)");
const C = Math.floor(i / 4) * 4, $ = i % 4, k = `
if (${m}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${w}(values, minMaxValue);
}
`;
this.userCode = `
const ivec2 strides = ivec2(${a}, ${l});
const ivec2 pads = ivec2(${p}, ${f});
const float initializationValue = ${b};
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 >= ${t.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(${b});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${h};
wR += ${c}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int wC = 0; wC < ${C}; wC += 4) {
int xC = xCCorner + wC * ${u};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
getValue(batch, xR, xC + 2 * ${u}, d),
getValue(batch, xR, xC + 3 * ${u}, d)
);
${k}
}
int xC = xCCorner + ${C};
if (${$ === 1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${k}
} else if (${$ === 2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
initializationValue,
initializationValue
);
${k}
} else if (${$ === 3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
getValue(batch, xR, xC + 2 * ${u}, d),
initializationValue
);
${k}
}
}
setOutput(${y});
}
`;
}
}
class Qd {
constructor(t, e, s, o = !1, r = !1) {
if (this.variableNames = ["x"], e === "avg" && s)
throw new Error("Cannot compute positions for average pool.");
const i = t.filterWidth, a = t.strideDepth, l = t.strideHeight, c = t.strideWidth, u = t.dilationDepth, h = t.dilationHeight, d = t.dilationWidth, p = t.effectiveFilterDepth, f = t.effectiveFilterHeight, m = t.effectiveFilterWidth, g = t.padInfo.front, x = t.padInfo.top, b = t.padInfo.left;
this.outputShape = t.outShape;
const w = e === "avg";
let y = "0.0";
if (w || (y = "-1.0 / 1e-20"), s) {
const T = ">=";
this.userCode = `
const ivec3 strides =
ivec3(${a}, ${l}, ${c});
const ivec3 pads = ivec3(${g}, ${x}, ${b});
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 < ${p};
wD += ${u}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${t.inDepth}) {
continue;
}
for (int wR = 0; wR < ${f};
wR += ${h}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int wC = 0; wC < ${m};
wC += ${d}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${t.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 ${T} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${o ? r ? `(((batch * ${t.inDepth} + xD) * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch` : `((xD * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch` : `wD * ${f} * ${m} +
wR * ${m} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;
return;
}
const C = "max";
let $ = `${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
e === "avg" && ($ = "avgValue / max(count, 1.0)");
const k = Math.floor(i / 4) * 4, v = i % 4, S = `
if (${w}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${C}(values, minMaxValue);
}
`;
this.userCode = `
const ivec3 strides =
ivec3(${a}, ${l}, ${c});
const ivec3 pads = ivec3(${g}, ${x}, ${b});
const float initializationValue = ${y};
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 >= ${t.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(${y});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${p};
wD += ${u}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${t.inDepth}) {
continue;
}
for (int wR = 0; wR < ${f};
wR += ${h}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int wC = 0; wC < ${k}; wC += 4) {
int xC = xCCorner + wC * ${d};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
getValue(batch, xD, xR, xC + 3 * ${d}, ch)
);
${S}
}
int xC = xCCorner + ${k};
if (${v === 1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${S}
} else if (${v === 2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
initializationValue,
initializationValue
);
${S}
} else if (${v === 3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
initializationValue
);
${S}
}
}
}
setOutput(${$});
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function M3(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t;
zi(o, "avgPool");
const { filterSize: r, strides: i, pad: a, dimRoundingMode: l } = s, c = 1;
I(Ie(i, c), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);
const u = ln(o.shape, r, i, c, a, l);
if (u.filterWidth === 1 && u.filterHeight === 1 && Et(u.inShape, u.outShape))
return He({ inputs: { x: o }, backend: e });
const h = new Ir(u, "avg", !1);
return e.runWebGLProgram(h, [o], "float32");
}
const P3 = {
kernelName: La,
backendName: "webgl",
kernelFunc: M3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function z3(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { filterSize: r, strides: i, pad: a, dimRoundingMode: l, dataFormat: c } = s, u = [1, 1, 1], h = Zn(o.shape, r, i, u, a, l, c), d = new Qd(h, "avg", !1);
return e.runWebGLProgram(d, [o], "float32");
}
const B3 = {
kernelName: Ma,
backendName: "webgl",
kernelFunc: z3
};
/**
* @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.
* =============================================================================
*/
class V3 {
constructor(t) {
this.variableNames = ["dy"], this.outputShape = t.inShape;
const e = t.filterHeight, s = t.filterWidth, o = t.strideHeight, r = t.strideWidth, i = t.dilationHeight, a = t.dilationWidth, l = t.effectiveFilterHeight, c = t.effectiveFilterWidth, u = l - 1 - t.padInfo.top, h = c - 1 - t.padInfo.left, d = 1 / (e * s);
this.userCode = `
const ivec2 pads = ivec2(${u}, ${h});
const float avgMultiplier = float(${d});
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 < ${l};
wR += ${i}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${c};
wC+= ${a}) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`;
}
}
class W3 {
constructor(t) {
this.variableNames = ["dy"], this.outputShape = t.inShape;
const e = t.filterDepth, s = t.filterHeight, o = t.filterWidth, r = t.strideDepth, i = t.strideHeight, a = t.strideWidth, l = t.dilationDepth, c = t.dilationHeight, u = t.dilationWidth, h = t.effectiveFilterDepth, d = t.effectiveFilterHeight, p = t.effectiveFilterWidth, f = h - 1 - t.padInfo.front, m = d - 1 - t.padInfo.top, g = p - 1 - t.padInfo.left, x = 1 / (e * s * o);
this.userCode = `
const ivec3 pads = ivec3(${f}, ${m}, ${g});
const float avgMultiplier = float(${x});
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 < ${h};
wD += ${l}) {
float dyD = float(dyDCorner + wD) / ${r}.0;
if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${d};
wR += ${c}) {
float dyR = float(dyRCorner + wR) / ${i}.0;
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${p};
wC += ${u}) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function U3(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, input: r } = t, i = r, { filterSize: a, strides: l, pad: c, dimRoundingMode: u } = s, h = [1, 1, 1], d = Zn(i.shape, a, l, h, c, u), p = new W3(d);
return e.runWebGLProgram(p, [o], i.dtype);
}
const G3 = {
kernelName: Ru,
backendName: "webgl",
kernelFunc: U3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function H3(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, input: r } = t, i = r;
zi([o, r], "avgPoolGrad");
const { filterSize: a, strides: l, pad: c } = s, u = ln(i.shape, a, l, 1, c), h = new V3(u);
return e.runWebGLProgram(h, [o], i.dtype);
}
const K3 = {
kernelName: Eu,
backendName: "webgl",
kernelFunc: H3
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function j3(n) {
const { inputs: t, backend: e, attrs: s } = n, { a: o, b: r } = t, { transposeA: i, transposeB: a } = s;
return Ra({ a: o, b: r, transposeA: i, transposeB: a, backend: e });
}
const X3 = {
kernelName: Pa,
backendName: "webgl",
kernelFunc: j3
};
/**
* @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.
* =============================================================================
*/
class q3 {
constructor(t, e, s, o, r, i) {
this.outputShape = [], this.variableNames = ["x", "mean", "variance"], mt(t, e), mt(t, s);
let a = "0.0";
o != null && (mt(t, o), this.variableNames.push("offset"), a = "getOffsetAtOutCoords()");
let l = "1.0";
r != null && (mt(t, r), this.variableNames.push("scale"), l = "getScaleAtOutCoords()"), this.outputShape = t, this.userCode = `
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${a};
float scale = ${l};
float inv = scale * inversesqrt(variance + float(${i}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Y3 {
constructor(t, e, s, o, r, i) {
this.packedInputs = !0, this.packedOutput = !0, this.variableNames = ["x", "mean", "variance"], mt(t, e), mt(t, s);
let a = "vec4(0.0)";
o != null && (mt(t, o), this.variableNames.push("offset"), a = "getOffsetAtOutCoords()");
let l = "vec4(1.0)";
r != null && (mt(t, r), this.variableNames.push("scale"), l = "getScaleAtOutCoords()"), this.outputShape = t, this.userCode = `
void main() {
vec4 offset = ${a};
vec4 scale = ${l};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${i}));
setOutput((x - mean) * inv + offset);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const J3 = ({ inputs: n, backend: t, attrs: e }) => {
const { x: s, mean: o, variance: r, offset: i, scale: a } = n;
I(o.shape.length === r.shape.length, () => "Batch normalization gradient requires mean and variance to have equal ranks."), I(i == null || o.shape.length === i.shape.length, () => "Batch normalization gradient requires mean and offset to have equal ranks."), I(a == null || o.shape.length === a.shape.length, () => "Batch normalization gradient requires mean and scale to have equal ranks.");
let { varianceEpsilon: l } = e;
l == null && (l = 1e-3);
const c = [s, o, r];
let u = null;
i != null && (u = i.shape, c.push(i));
let h = null;
a != null && (h = a.shape, c.push(a));
const d = P().getBool("WEBGL_PACK_NORMALIZATION") ? new Y3(s.shape, o.shape, r.shape, u, h, l) : new q3(s.shape, o.shape, r.shape, u, h, l);
return t.runWebGLProgram(d, c, c[0].dtype);
}, Z3 = {
kernelName: Ya,
backendName: "webgl",
kernelFunc: J3
};
/**
* @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.
* =============================================================================
*/
class Q3 {
constructor(t) {
this.variableNames = ["source"], this.outputShape = t, this.rank = t.length;
const e = Ot(this.rank);
this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
const s = tz(this.rank);
let o;
const r = t.map((i, a) => `sourceLoc.${uu[a]} = start[${a}] + coords.${uu[a]};`);
o = `
${e} sourceLoc;
${e} coords = getOutputCoords();
${r.join(`
`)}
`, this.userCode = `
void main() {
${o}
setOutput(getSource(${s}));
}
`;
}
}
const uu = ["x", "y", "z", "w", "u", "v"];
function tz(n) {
if (n === 1)
return "sourceLoc";
if (n <= 6)
return uu.slice(0, n).map((t) => "sourceLoc." + t).join(",");
throw Error(`Slicing for rank ${n} is not yet supported`);
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class ez {
constructor(t) {
this.variableNames = ["source"], this.packedInputs = !0, this.packedOutput = !0, this.outputShape = t, this.rank = t.length, this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
const e = Ot(this.rank), s = Ee("coords", this.rank), o = Ee("sourceLoc", this.rank), r = this.rank === 1 ? "sourceLoc" : `vec2(${o.slice(-2).join()})`, i = `getChannel(getSource(${o.join()}), ${r})`, a = `
result.x = ${i};
if (++${s[this.rank - 1]} < ${t[this.rank - 1]}) {
++${o[this.rank - 1]};
result.y = ${i};
--${o[this.rank - 1]};
}
`, l = this.rank === 1 ? "" : `
--${s[this.rank - 1]};
if (++${s[this.rank - 2]} < ${t[this.rank - 2]}) {
++${o[this.rank - 2]};
result.z = ${i};
if (++${s[this.rank - 1]} < ${t[this.rank - 1]}) {
++${o[this.rank - 1]};
result.w = ${i};
}
}
`, c = this.rank <= 4 ? `sourceLoc = coords +
${e}(${t.map((u, h) => `start[${h}]`).join()});` : t.map((u, h) => `${o[h]} = ${s[h]} + start[${h}];`).join(`
`);
this.userCode = `
void main() {
${e} coords = getOutputCoords();
${e} sourceLoc;
${c}
vec4 result = vec4(0.);
${a}
${l}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nz(n, t, e, s) {
const o = s.texData.get(n.dataId), r = s.makeTensorInfo(e, n.dtype), i = s.texData.get(r.dataId);
Object.assign(i, o), i.refCount = 1, i.shape = e, i.dtype = n.dtype;
let a = Xh(t, lt(n.shape));
o.slice && (a += o.slice.flatOffset), i.slice = {
flatOffset: a,
// Point to the original dataId, which is used to do ref counting.
origDataId: o.slice && o.slice.origDataId || n.dataId
};
const l = s.dataRefCount.get(i.slice.origDataId) || 1;
return s.dataRefCount.set(i.slice.origDataId, l + 1), r;
}
function Zo(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { begin: r, size: i } = s, [a, l] = Wl(o, r, i);
if (Hh(o, a, l), G(l) === 0)
return e.makeTensorInfo(l, o.dtype, []);
if (e.shouldExecuteOnCPU([o]) || o.dtype === "string") {
const h = e.texData.get(o.dataId), d = XM(h.values, a, l, o.shape, o.dtype);
return e.makeTensorInfo(l, o.dtype, d);
}
const { isPacked: c } = e.texData.get(o.dataId), u = jh(o.shape, a, l);
if (c || !u) {
const h = P().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new ez(l) : new Q3(l), d = [a];
return e.runWebGLProgram(h, [o], o.dtype, d);
}
return e.uploadToGPU(o.dataId), nz(o, a, l, e);
}
const sz = {
kernelName: vl,
backendName: "webgl",
kernelFunc: Zo
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const oz = (n) => {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { blockShape: r, crops: i } = s;
I(o.shape.length <= 4, () => "batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");
const a = r.reduce((b, w) => b * w), l = Si(o.shape, r, a), c = Ni(l.length, r.length), u = Ti(o.shape, r, a), h = Qh(i, r.length), d = td(u, i, r.length), p = [], f = tt({ inputs: { x: o }, backend: e, attrs: { shape: l } }), m = De({ inputs: { x: f }, backend: e, attrs: { perm: c } }), g = tt({
inputs: { x: m },
backend: e,
attrs: { shape: u }
}), x = Zo({
inputs: { x: g },
backend: e,
attrs: { begin: h, size: d }
});
return p.push(f), p.push(m), p.push(g), p.forEach((b) => e.disposeIntermediateTensorInfo(b)), x;
}, rz = {
kernelName: za,
backendName: "webgl",
kernelFunc: oz
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function iz(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, weights: r } = t, { size: i } = s, a = e.readSync(o.dataId), l = e.readSync(r.dataId), c = Oy(a, l, r.dtype, r.shape, i);
return e.makeTensorInfo([i], r.dtype, c);
}
const az = {
kernelName: Du,
backendName: "webgl",
kernelFunc: iz
};
/**
* @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.
* =============================================================================
*/
const lz = `
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);
`, cz = `
return float(int(a.r) & int(b.r));
`;
function uz(n) {
const { inputs: t, backend: e } = n, { a: s, b: o } = t, r = P().getBool("WEBGL_PACK_BINARY_OPERATIONS"), i = P().getNumber("WEBGL_VERSION");
if (e.shouldExecuteOnCPU([s, o]) || i === 1) {
const l = e.texData.get(s.dataId).values, c = e.texData.get(o.dataId).values, [u, h] = bM(s.shape, o.shape, l, c, s.dtype), d = e.makeTensorInfo(h, s.dtype), p = e.texData.get(d.dataId);
return p.values = u, d;
}
let a;
return r ? a = new Yo(lz, s.shape, o.shape, !1) : a = new to(cz, s.shape, o.shape), e.runWebGLProgram(a, [s, o], s.dtype);
}
const hz = {
kernelName: Au,
backendName: "webgl",
kernelFunc: uz
};
/**
* @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.
* =============================================================================
*/
function dz(n) {
const { inputs: t, backend: e } = n, { s0: s, s1: o } = t, r = e.readSync(s.dataId), i = e.readSync(o.dataId), a = mt(Array.from(r), Array.from(i));
return e.makeTensorInfo([a.length], "int32", Int32Array.from(a));
}
const pz = {
kernelName: Wf,
backendName: "webgl",
kernelFunc: dz
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const fz = "return float(a != b);", Xy = ye({ opSnippet: fz, cpuKernelImpl: zM, dtype: "bool" }), mz = {
kernelName: pl,
backendName: "webgl",
kernelFunc: Xy
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Vi(n) {
const { inputs: t, backend: e } = n, { input: s } = t, o = e.texData.get(s.dataId);
return He({ inputs: { x: o.complexTensorInfos.real }, backend: e });
}
const gz = {
kernelName: sh,
backendName: "webgl",
kernelFunc: Vi
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const xz = "return float(int(x));";
function bz(n, t) {
const e = new En(n.shape, xz), s = t.runWebGLProgram(e, [n], "int32");
return { dataId: s.dataId, shape: s.shape, dtype: s.dtype };
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function hu(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { dtype: r } = s;
if (r === "complex64") {
if (o.dtype === "complex64")
return He({ inputs: { x: o }, backend: e });
const i = he(o.shape), a = hu({ inputs: { x: o }, backend: e, attrs: { dtype: "float32" } }), l = Ts({ inputs: { real: a, imag: i }, backend: e });
return i.dispose(), e.disposeIntermediateTensorInfo(a), l;
}
if (o.dtype === "complex64") {
const i = Vi({ inputs: { input: o }, backend: e }), a = hu({ inputs: { x: i }, backend: e, attrs: { dtype: r } });
return e.disposeIntermediateTensorInfo(i), a;
}
if (!Mf(o.dtype, r)) {
const i = He({ inputs: { x: o }, backend: e });
return { dataId: i.dataId, shape: i.shape, dtype: r };
}
if (e.shouldExecuteOnCPU([o])) {
const i = e.texData.get(o.dataId).values, [a, l, c] = yM(i, o.shape, o.dtype, r);
return e.makeTensorInfo(a, l, c);
}
if (r === "int32")
return bz(o, e);
if (r === "bool") {
const i = e.makeTensorInfo([], "bool", we("bool", 1)), l = Xy({ inputs: { a: o, b: i }, backend: e });
return e.disposeIntermediateTensorInfo(i), l;
}
throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${r}`);
}
const yz = {
kernelName: Fr,
backendName: "webgl",
kernelFunc: hu
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Cf = "return ceil(x);", wz = vt({ opSnippet: Cf, packedOpSnippet: Cf, cpuKernelImpl: wM }), Cz = {
kernelName: Or,
backendName: "webgl",
kernelFunc: wz
};
/**
* @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.
* =============================================================================
*/
class $z {
constructor(t) {
this.variableNames = ["A"], this.customUniforms = [
{ name: "minVal", type: "float" },
{ name: "maxVal", type: "float" }
], this.outputShape = t, this.userCode = `
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Iz {
constructor(t) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0, this.customUniforms = [
{ name: "minVal", type: "float" },
{ name: "maxVal", type: "float" }
], this.outputShape = t, this.userCode = `
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kz(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { clipValueMin: r, clipValueMax: i } = s;
let a;
P().getBool("WEBGL_PACK_CLIP") ? a = new Iz(o.shape) : a = new $z(o.shape);
const l = [[r], [i]];
return e.runWebGLProgram(a, [o], o.dtype, l);
}
const vz = {
kernelName: _r,
backendName: "webgl",
kernelFunc: kz
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Sz {
constructor(t) {
this.variableNames = ["real", "imag"], this.outputShape = t, 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))
);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function $f(n, t) {
return {
dataId: t.dataId,
dtype: t.dtype,
shape: n.shape
};
}
function Nz(n) {
const { inputs: t, backend: e } = n, { x: s } = t, o = e.texData.get(s.dataId), r = new Sz(s.shape), i = [
$f(s, o.complexTensorInfos.real),
$f(s, o.complexTensorInfos.imag)
];
return e.runWebGLProgram(r, i, i[0].dtype);
}
const Tz = {
kernelName: Ba,
backendName: "webgl",
kernelFunc: Nz
};
/**
* @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.
* =============================================================================
*/
class Ez {
// Concats 2d tensors along axis=1. See comments in MathBackendWebGL.concat().
constructor(t) {
this.outputShape = [], this.outputShape = An(
t,
1
/* axis */
), this.variableNames = t.map((i, a) => `T${a}`);
const e = new Array(t.length - 1);
e[0] = t[0][1];
for (let i = 1; i < e.length; i++)
e[i] = e[i - 1] + t[i][1];
const s = [`if (yC < ${e[0]}) setOutput(getT0(yR, yC));`];
for (let i = 1; i < e.length; i++) {
const a = e[i - 1];
s.push(`else if (yC < ${e[i]}) setOutput(getT${i}(yR, yC-${a}));`);
}
const o = e.length, r = e[e.length - 1];
s.push(`else setOutput(getT${o}(yR, yC-${r}));`), this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${s.join(`
`)}
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Rz {
constructor(t, e) {
this.packedInputs = !0, this.packedOutput = !0, this.outputShape = [], this.outputShape = An(t, e);
const s = this.outputShape, o = s.length, r = Ot(o), i = Ee("coords", o), a = ["x", "y", "z", "w", "u", "v"].slice(0, o);
this.variableNames = t.map((m, g) => `T${g}`);
const l = new Array(t.length - 1);
l[0] = t[0][e];
for (let m = 1; m < l.length; m++)
l[m] = l[m - 1] + t[m][e];
const c = a[e], u = a.slice(-2), h = a.join();
let d = `if (${c} < ${l[0]}) {
return getChannel(
getT0(${h}), vec2(${u.join()}));
}`;
for (let m = 1; m < l.length; m++) {
const g = l[m - 1];
d += `
if (${c} < ${l[m]} && ${c} >= ${l[m - 1]}) {
return getChannel(
getT${m}(${na(a, c, g)}),
vec2(${na(u, c, g)}));
}`;
}
const p = l.length, f = l[l.length - 1];
d += `
return getChannel(
getT${p}(${na(a, c, f)}),
vec2(${na(u, c, f)}));`, this.userCode = `
float getValue(${a.map((m) => "int " + m)}) {
${d}
}
void main() {
${r} coords = getOutputCoords();
vec4 result = vec4(getValue(${i}), 0., 0., 0.);
${i[o - 1]} = ${i[o - 1]} + 1;
if (${i[o - 1]} < ${s[o - 1]}) {
result.g = getValue(${i});
}
${i[o - 2]} = ${i[o - 2]} + 1;
if (${i[o - 2]} < ${s[o - 2]}) {
result.a = getValue(${i});
}
${i[o - 1]} = ${i[o - 1]} - 1;
if (${i[o - 2]} < ${s[o - 2]} &&
${i[o - 1]} < ${s[o - 1]}) {
result.b = getValue(${i});
}
setOutput(result);
}
`;
}
}
function na(n, t, e) {
const s = n.indexOf(t);
return n.map((r, i) => i === s ? `${r} - ${e}` : r).join();
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function lc(n) {
const { inputs: t, backend: e } = n, { input: s } = t, o = e.texData.get(s.dataId);
return He({ inputs: { x: o.complexTensorInfos.imag }, backend: e });
}
const Dz = {
kernelName: qu,
backendName: "webgl",
kernelFunc: lc
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function cr(n, t, e) {
const s = n[0].dtype;
if (s === "complex64") {
const p = n.map((b) => Vi({ inputs: { input: b }, backend: e })), f = n.map((b) => lc({ inputs: { input: b }, backend: e })), m = cr(p, t, e), g = cr(f, t, e), x = Ts({ inputs: { real: m, imag: g }, backend: e });
return p.forEach((b) => e.disposeIntermediateTensorInfo(b)), f.forEach((b) => e.disposeIntermediateTensorInfo(b)), e.disposeIntermediateTensorInfo(m), e.disposeIntermediateTensorInfo(g), x;
}
let o = e.shouldExecuteOnCPU(n);
if (s === "string" && (o = !0), o) {
const p = n.map((y) => {
const $ = [-1, G(y.shape.slice(t))];
return tt({ inputs: { x: y }, backend: e, attrs: { shape: $ } });
}), f = p.map((y) => ({ vals: e.readSync(y.dataId), shape: y.shape })), m = An(
p.map((y) => y.shape),
1
/* axis */
), g = p[0].shape[0] === 1, x = CM(f, m, s, g), b = An(n.map((y) => y.shape), t), w = e.makeTensorInfo(b, s, x);
return p.forEach((y) => e.disposeIntermediateTensorInfo(y)), w;
}
const r = n.filter((p) => G(p.shape) > 0), i = P().getBool("WEBGL_PACK_ARRAY_OPERATIONS") && r[0].shape.length > 1;
if (r.length === 1) {
const p = i ? new En(n[0].shape, rs) : new ls(n[0].shape, rs);
return e.runWebGLProgram(p, n, s);
}
const a = P().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");
if (r.length > a) {
const p = [];
for (let m = 0; m < r.length; m += a) {
const g = r.slice(m, m + a);
p.push(cr(g, t, e));
}
const f = cr(p, t, e);
for (const m of p)
e.disposeIntermediateTensorInfo(m);
return f;
}
if (i) {
const p = new Rz(r.map((f) => f.shape), t);
return e.runWebGLProgram(p, r, s);
}
const { tensors2D: l, outShape: c } = Az(r, t, e), u = new Ez(l.map((p) => p.shape)), h = e.runWebGLProgram(u, l, s);
l.forEach((p) => e.disposeIntermediateTensorInfo(p));
const d = tt({ inputs: { x: h }, attrs: { shape: c }, backend: e });
return e.disposeIntermediateTensorInfo(h), d;
}
function Az(n, t, e) {
const s = An(n.map((r) => r.shape), t);
return { tensors2D: n.map((r) => tt({
inputs: { x: r },
attrs: { shape: [-1, G(r.shape.slice(t))] },
backend: e
})), outShape: s };
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function qy(n) {
const { inputs: t, backend: e, attrs: s } = n, { axis: o } = s, r = wt(o, t[0].shape)[0], i = t.map((c) => c.shape);
Yh(i, r);
const a = An(t.map((c) => c.shape), r);
if (G(a) === 0)
return e.makeTensorInfo(a, t[0].dtype, []);
const l = t.filter((c) => G(c.shape) > 0);
return l.length === 1 ? He({ inputs: { x: l[0] }, backend: e }) : cr(l, r, e);
}
const Fz = {
kernelName: Va,
backendName: "webgl",
kernelFunc: qy
};
/**
* @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.
* =============================================================================
*/
class Yy {
constructor(t, e = !1, s = null, o = !1, r = !1) {
this.variableNames = ["x", "W"], this.outputShape = t.outShape;
const i = t.padInfo.top, a = t.padInfo.left, l = t.strideHeight, c = t.strideWidth, u = t.dilationHeight, h = t.dilationWidth, d = t.filterHeight, p = t.filterWidth, f = Math.floor(t.inChannels / 4) * 4, m = t.inChannels % 4, g = t.dataFormat === "channelsLast", x = g ? 1 : 2, b = g ? 2 : 3, w = g ? 3 : 1;
let y = "", C = "";
s && (o ? y = `float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}` : r ? y = `float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${s}
}` : y = `
float activation(float x) {
${s}
}
`, C = "result = activation(result);");
const $ = e ? "result += getBiasAtOutCoords();" : "";
e && this.variableNames.push("bias"), o && this.variableNames.push("preluActivationWeights"), r && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${y}
const ivec2 strides = ivec2(${l}, ${c});
const ivec2 pads = ivec2(${i}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${w}];
ivec2 xRCCorner =
ivec2(coords[${x}], coords[${b}]) * 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 < ${d}; wR++) {
int xR = xRCorner + wR * ${u};
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int wC = 0; wC < ${p}; wC++) {
int xC = xCCorner + wC * ${h};
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${f}; 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 (${g}) {
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 (${m === 1}) {
if (${g}) {
dotProd +=
getX(batch, xR, xC, ${f}) *
getW(wR, wC, ${f}, d2);
} else {
dotProd +=
getX(batch, ${f}, xR, xC) *
getW(wR, wC, ${f}, d2);
}
} else if (${m === 2}) {
vec2 wValues = vec2(
getW(wR, wC, ${f}, d2),
getW(wR, wC, ${f} + 1, d2)
);
if (${g}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${f}),
getX(batch, xR, xC, ${f} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${f}, xR, xC),
getX(batch, ${f} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${m === 3}) {
vec3 wValues = vec3(
getW(wR, wC, ${f}, d2),
getW(wR, wC, ${f} + 1, d2),
getW(wR, wC, ${f} + 2, d2)
);
if (${g}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${f}),
getX(batch, xR, xC, ${f} + 1),
getX(batch, xR, xC, ${f} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${f}, xR, xC),
getX(batch, ${f} + 1, xR, xC),
getX(batch, ${f} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${$}
${C}
setOutput(result);
}
`;
}
}
class Oz {
constructor(t) {
this.variableNames = ["x", "W"], this.outputShape = t.outShape;
const e = t.padInfo.front, s = t.padInfo.top, o = t.padInfo.left, r = t.strideDepth, i = t.strideHeight, a = t.strideWidth, l = t.dilationDepth, c = t.dilationHeight, u = t.dilationWidth, h = t.filterDepth, d = t.filterHeight, p = t.filterWidth, f = Math.floor(t.inChannels / 4) * 4, m = t.inChannels % 4;
this.userCode = `
const ivec3 strides = ivec3(${r}, ${i}, ${a});
const ivec3 pads = ivec3(${e}, ${s}, ${o});
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 < ${h}; wF++) {
int xF = xFCorner + wF * ${l};
if (xF < 0 || xF >= ${t.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d}; wR++) {
int xR = xRCorner + wR * ${c};
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int wC = 0; wC < ${p}; wC++) {
int xC = xCCorner + wC * ${u};
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${f}; 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 (${m === 1}) {
dotProd +=
getX(batch, xF, xR, xC, ${f}) *
getW(wF, wR, wC, ${f}, d2);
} else if (${m === 2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${f}),
getX(batch, xF, xR, xC, ${f} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${f}, d2),
getW(wF, wR, wC, ${f} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${m === 3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${f}),
getX(batch, xF, xR, xC, ${f} + 1),
getX(batch, xF, xR, xC, ${f} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${f}, d2),
getW(wF, wR, wC, ${f} + 1, d2),
getW(wF, wR, wC, ${f} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`;
}
}
/**
* @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.
* =============================================================================
*/
class Jy {
constructor(t, e = !1, s = null, o = !1, r = !1) {
this.variableNames = ["x", "W"], this.packedInputs = !0, this.packedOutput = !0, this.customUniforms = [
{ name: "pads", type: "ivec2" },
{ name: "strides", type: "ivec2" },
{ name: "dilations", type: "ivec2" },
{ name: "inDims", type: "ivec2" }
], this.outputShape = t.outShape, this.enableShapeUniforms = ve(this.outputShape.length);
const i = t.padInfo.left, a = t.strideWidth, l = t.dilationWidth, c = t.filterHeight, u = t.filterWidth, h = u;
let d = `
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;
for (let g = 0; g < u; g++)
d += `
vec4 xTexelC${g * 2};
int xTexelC${g * 2}Ready;
vec4 xTexelC${g * 2 + 1};
int xTexelC${g * 2 + 1}Ready;
vec4 xC${g};`;
d += `
for (int r = 0; r < ${c}; r++) {
for (int d1 = 0; d1 < ${t.inChannels}; d1 += 2) {
`;
for (let g = 0; g < u; g++)
d += `
xTexelC${g * 2} = vec4(0.0);
xTexelC${g * 2}Ready = 0;
xTexelC${g * 2 + 1} = vec4(0.0);
xTexelC${g * 2 + 1}Ready = 0;
xC${g} = vec4(0.0);`;
d += `
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;
for (let g = 0; g < (h + 1) / 2; g++) {
const x = g * 2;
if (d += `
xC = xCCorner + ${x * l};
`, a === 1) {
if (x < u && (i % 2 === 1 ? (d += `
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = 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${x}.zw = vec2(0.0);
}
xTexelC${x}Ready = 1;
}
`, l === 1 && x > 0 ? d += `
xC${x} = vec4(xTexelC${x - 2}.zw, xTexelC${x}.xy);
` : d += `
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${x} = vec4(previous.zw, xTexelC${x}.xy);
} else {
xC${x} = vec4(0.0, 0.0, xTexelC${x}.xy);
}
`) : d += `
if (xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${x}.zw = vec2(0.0);
}
xTexelC${x}Ready = 1;
}
xC${x} = xTexelC${x};
`, x + 1 < u)) {
const b = i % 2 === 0 ? Cu(l) : l;
l % 2 === 0 && i % 2 === 1 || l % 2 !== 0 && i % 2 !== 1 ? (d += `
xCOffset = xC + imod(pads[1], 2) + ${b};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x + 1}Ready == 0) {
xTexelC${x + 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${x + 1}.zw = vec2(0.0);
}
xTexelC${x + 1}Ready = 1;
}
`, l > 1 ? d += `
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
xC${x + 1} = vec4(previous.zw, xTexelC${x + 1}.xy);
} else {
xC${x + 1} = vec4(0.0, 0.0, xTexelC${x + 1}.xy);
}
` : d += `
xC${x + 1} = vec4(xTexelC${x}.zw, xTexelC${x + 1}.xy);
`) : b === 1 ? d += `
xC${x + 1} = xTexelC${x};
` : d += `
xCOffset = xC + ${b};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x + 1}Ready == 0) {
xTexelC${x + 1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${x + 1}.zw = vec2(0.0);
}
xTexelC${x + 1}Ready = 1;
}
xC${x + 1} = xTexelC${x + 1};
`;
}
} else
x < u && (i % 2 === 1 ? (d += `
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = 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${x}.zw = vec2(0.0);
}
xTexelC${x}Ready = 1;
}
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${x + 1}Ready == 0) {
xTexelC${x + 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${x + 1}.zw = vec2(0.0);
}
xTexelC${x + 1}Ready = 1;
}
xC${x} = vec4(xTexelC${x}.zw, xTexelC${x + 1}.zw);
`, x + 1 < u && (d += `
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${x + 1} = vec4(xTexelC${x + 1}.xy, final.xy);
`)) : (d += `
if(xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${x}.zw = vec2(0.0);
}
xTexelC${x}Ready = 1;
}
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x + 1}Ready == 0) {
xTexelC${x + 1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${x + 1}.zw = vec2(0.);
}
xTexelC${x + 1}Ready = 1;
}
xC${x} = vec4(
xTexelC${x}.xy, xTexelC${x + 1}.xy);
`, x + 1 < u && (d += `
xC${x + 1} = vec4(xTexelC${x}.zw, xTexelC${x + 1}.zw);
`)));
x < u && (d += `
wTexel = getW(r, ${x}, d1, d2);
dotProd += xC${x}.xxzz * vec4(wTexel.xy, wTexel.xy);
if(d1 + 1 < ${t.inChannels}) {
dotProd += xC${x}.yyww * vec4(wTexel.zw, wTexel.zw);
}
`, x + 1 < u && (d += `
wTexel = getW(r, ${x + 1}, d1, d2);
dotProd += xC${x + 1}.xxzz * vec4(wTexel.xy, wTexel.xy);
if(d1 + 1 < ${t.inChannels}) {
dotProd += xC${x + 1}.yyww * vec4(wTexel.zw, wTexel.zw);
}
`));
}
d += `
}
`, d += `
}
`, d += `
}
`;
let p = "", f = "";
s && (o ? p = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${s}
}` : r ? p = `vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${s}
}` : p = `vec4 activation(vec4 x) {
${s}
}`, f = "result = activation(result);");
const m = e ? "result += getBiasAtOutCoords();" : "";
e && this.variableNames.push("bias"), o && this.variableNames.push("preluActivationWeights"), r && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${p}
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);
${d}
vec4 result = dotProd - vec4(0.000000000000001);
${m}
${f}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class _z {
constructor(t, e) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0, 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 = t, this.enableShapeUniforms = ve(this.outputShape.length);
const { dataFormat: s } = e, o = Ae(), r = s === "channelsLast", i = r ? 1 : 2, a = r ? 2 : 3, l = this.enableShapeUniforms ? "if(blockIndex < outShape[2] && pos < outShape[1]) {" : `if(blockIndex < ${t[2]} && pos < ${t[1]}) {`;
let c = "";
for (let u = 0; u <= 1; u++)
for (let h = 0; h <= 1; h++)
c += `
blockIndex = rc.z + ${h};
pos = rc.y + ${u};
${l}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
if(d0 < inputShape[${i}] && 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[${a}] && d1 >= 0) {
ch = imod(pos, inChannels);
if (${r}) {
innerDims = vec2(d1, ch);
result[${u * 2 + h}] = getChannel(
getA(rc.x, d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${u * 2 + h}] = 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;
${c}
${o.output} = result;
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Da(n, t) {
const e = n.length;
return e >= 3 ? t ? [
...n.slice(0, -3),
n[e - 3] * n[e - 2],
n[e - 1]
/* channel */
] : [
...n.slice(0, -3),
n[e - 3],
n[e - 2] * n[e - 1]
/* height * width */
] : !t && e === 1 && n[0] > 1 ? [n[0], 1] : null;
}
function Zy({ x: n, filter: t, convInfo: e, backend: s, bias: o = null, preluActivationWeights: r = null, leakyreluAlpha: i = 0, activation: a = null }) {
const l = n.shape, c = s.texData.get(n.dataId), u = e.inChannels, h = l[0] * l[1] * l[2], d = e.outChannels, p = e.dataFormat === "channelsLast", f = !1, m = !1;
let g;
const x = [];
if (r != null) {
const y = Da(r.shape, p);
y != null && (r = tt({
inputs: { x: r },
backend: s,
attrs: { shape: y }
}), x.push(r));
}
if (o != null) {
const y = Da(o.shape, p);
y != null && (o = tt({ inputs: { x: o }, backend: s, attrs: { shape: y } }), x.push(o));
}
if (!((h === 1 || d === 1) && u > Gy) && c.isPacked && p && c.texture != null && l[2] % 2 !== 0 && Et(c.shape.slice(-3), l.slice(-3))) {
const y = l[0] * l[1] * (l[2] + 1), C = {
dataId: n.dataId,
shape: [1, y, e.inChannels],
dtype: n.dtype
}, $ = c.shape;
c.shape = c.shape.slice(), c.shape[c.shape.length - 2]++, I(Ea(c.shape, C.shape), () => `packed reshape ${c.shape} to ${C.shape} isn't free`);
const k = tt({
inputs: { x: t },
backend: s,
attrs: { shape: [1, e.inChannels, e.outChannels] }
});
x.push(k);
const v = Ra({
a: C,
b: k,
backend: s,
transposeA: f,
transposeB: m,
bias: o,
activation: a,
preluActivationWeights: r,
leakyreluAlpha: i
}), S = s.texData.get(v.dataId);
I(S.isPacked, () => "batchMatMul result is expected to be packed"), c.shape = $, S.shape = e.outShape, g = He({ inputs: { x: v }, backend: s }), g.shape = e.outShape, x.push(v);
} else {
const y = e.outHeight * e.outWidth, C = tt({
inputs: { x: n },
backend: s,
attrs: {
shape: p ? [e.batchSize, y, e.inChannels] : [e.batchSize, e.inChannels, y]
}
}), $ = tt({
inputs: { x: t },
backend: s,
attrs: { shape: [1, e.inChannels, e.outChannels] }
}), k = Ra({
a: p ? C : $,
b: p ? $ : C,
transposeA: !p,
transposeB: m,
backend: s,
bias: o,
activation: a,
preluActivationWeights: r,
leakyreluAlpha: i
});
g = tt({ inputs: { x: k }, backend: s, attrs: { shape: e.outShape } }), x.push(C), x.push($), x.push(k);
}
for (const y of x)
s.disposeIntermediateTensorInfo(y);
return g;
}
function Qy({ x: n, filter: t, convInfo: e, backend: s, bias: o = null, preluActivationWeights: r = null, leakyreluAlpha: i = 0, activation: a = null }) {
const { filterWidth: l, filterHeight: c, inChannels: u, outWidth: h, outHeight: d, dataFormat: p } = e, f = p === "channelsLast", m = l * c * u, g = d * h, x = [e.batchSize, m, g], b = !0, w = !1, y = [];
if (r != null) {
const U = Da(r.shape, f);
U != null && (r = tt({
inputs: { x: r },
backend: s,
attrs: { shape: U }
}), y.push(r));
}
if (o != null) {
const U = Da(o.shape, f);
U != null && (o = tt({ inputs: { x: o }, backend: s, attrs: { shape: U } }), y.push(o));
}
const C = tt({
inputs: { x: t },
backend: s,
attrs: { shape: [1, m, G(t.shape) / m] }
});
y.push(C);
const $ = new _z(x, e), k = [
n.shape,
[e.padInfo.top, e.padInfo.left],
[e.strideHeight, e.strideWidth],
[e.dilationHeight, e.dilationWidth],
[e.inChannels],
[e.filterWidth * e.inChannels],
[e.outWidth]
], v = s.runWebGLProgram($, [n], "float32", k), S = tt({ inputs: { x: v }, backend: s, attrs: { shape: x } });
y.push(v), y.push(S);
const T = o != null, F = r != null, L = a === "leakyrelu", M = a ? $r(a, !0) : null, B = new Uy(f ? S.shape : C.shape, f ? C.shape : S.shape, f ? [e.batchSize, g, e.outChannels] : [e.batchSize, e.outChannels, g], b, w, T, M, F, L), z = f ? [S, C] : [C, S];
if (o && z.push(o), F && z.push(r), L) {
const U = s.makeTensorInfo([], "float32", ws(i, "float32"));
z.push(U), y.push(U);
}
const V = s.runWebGLProgram(B, z, "float32"), H = tt({ inputs: { x: V }, backend: s, attrs: { shape: e.outShape } });
y.push(V);
for (const U of y)
s.disposeIntermediateTensorInfo(U);
return H;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Lz(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r } = t, { strides: i, pad: a, dataFormat: l, dilations: c, dimRoundingMode: u } = s, h = Qn(l), d = xe(o.shape, r.shape, i, c, a, u, !1, h);
let p;
if (d.filterHeight === 1 && d.filterWidth === 1 && d.dilationHeight === 1 && d.dilationWidth === 1 && d.strideHeight === 1 && d.strideWidth === 1 && (d.padInfo.type === "SAME" || d.padInfo.type === "VALID"))
p = Zy({ x: o, filter: r, convInfo: d, backend: e });
else if (d.strideWidth <= 2 && h === "channelsLast" && P().getBool("WEBGL_EXP_CONV")) {
const m = new Jy(d), g = [
[d.padInfo.top, d.padInfo.left],
[d.strideHeight, d.strideWidth],
[d.dilationHeight, d.dilationWidth],
[d.inHeight, d.inWidth]
];
p = e.runWebGLProgram(m, [o, r], "float32", g);
} else if (P().getBool("WEBGL_CONV_IM2COL"))
p = Qy({ x: o, filter: r, convInfo: d, backend: e });
else {
const m = new Yy(d);
p = e.runWebGLProgram(m, [o, r], "float32");
}
const f = tt({ inputs: { x: p }, backend: e, attrs: { shape: d.outShape } });
return e.disposeIntermediateTensorInfo(p), f;
}
const Mz = {
kernelName: Wa,
backendName: "webgl",
kernelFunc: Lz
};
/**
* @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.
* =============================================================================
*/
class Pz {
constructor(t) {
this.variableNames = ["x", "dy"], this.outputShape = t.filterShape;
const e = t.strideHeight, s = t.strideWidth, o = t.padInfo.top, r = t.padInfo.left, i = t.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 < ${t.batchSize}; b++) {
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${e} - ${o};
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${r};
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
${i ? `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 zz {
constructor(t) {
this.variableNames = ["dy", "W"], this.outputShape = t.inShape;
const e = t.filterHeight, s = t.filterWidth, o = t.strideHeight, r = t.strideWidth, i = t.dataFormat === "channelsLast", a = e - 1 - t.padInfo.top, l = s - 1 - t.padInfo.left, c = i ? 1 : 2, u = i ? 2 : 3, h = i ? 3 : 1;
this.userCode = `
const ivec2 pads = ivec2(${a}, ${l});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${h}];
ivec2 dyCorner = ivec2(coords[${c}], coords[${u}]) - 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 < ${e}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${e} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
if (${i}) {
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 Bz {
constructor(t) {
this.variableNames = ["x", "dy"], this.outputShape = t.filterShape;
const e = t.strideDepth, s = t.strideHeight, o = t.strideWidth, r = t.padInfo.front, i = t.padInfo.top, a = t.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 < ${t.batchSize}; b++) {
for (int yF = 0; yF < ${t.outDepth}; yF++) {
int xF = wF + yF * ${e} - ${r};
if (xF < 0 || xF >= ${t.inDepth}) {
continue;
}
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${s} - ${i};
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${o} - ${a};
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`;
}
}
class Vz {
constructor(t) {
this.variableNames = ["dy", "W"], this.outputShape = t.inShape;
const e = t.filterDepth, s = t.filterHeight, o = t.filterWidth, r = t.strideDepth, i = t.strideHeight, a = t.strideWidth, l = e - 1 - t.padInfo.front, c = s - 1 - t.padInfo.top, u = o - 1 - t.padInfo.left;
this.userCode = `
const ivec3 pads = ivec3(${l}, ${c}, ${u});
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 < ${e}; wF++) {
float dyF = float(dyFCorner + wF) / ${r}.0;
if (dyF < 0.0 || dyF >= ${t.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${e} - 1 - wF;
for (int wR = 0; wR < ${s}; wR++) {
float dyR = float(dyRCorner + wR) / ${i}.0;
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${s} - 1 - wR;
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${o} - 1 - wC;
for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Wz(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, dy: r } = t, { strides: i, pad: a, dataFormat: l, dimRoundingMode: c, filterShape: u } = s, h = Qn(l), d = xe(o.shape, u, i, 1, a, c, !1, h), p = new Pz(d);
return e.runWebGLProgram(p, [o, r], "float32");
}
const Uz = {
kernelName: Ou,
backendName: "webgl",
kernelFunc: Wz
};
/**
* @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.
* =============================================================================
*/
class Gz {
constructor(t) {
this.variableNames = ["dy", "W"], this.packedInputs = !0, this.packedOutput = !0, this.customUniforms = [
{ name: "strides", type: "vec2" }
], this.outputShape = t.inShape, this.enableShapeUniforms = ve(this.outputShape.length);
const e = t.filterHeight, s = t.filterWidth, o = e - 1 - t.padInfo.top, r = s - 1 - t.padInfo.left;
this.userCode = `
const ivec2 pads = ivec2(${o}, ${r});
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 < ${e}; wR++) {
float dyR = float(dyRCorner + wR) / strides[0];
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${e} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
int wCPerm = ${s} - 1 - wC;
float dyC = float(dyCCorner + wC) / strides[1];
bool idyCVal = (dyC >= 0.0) && (dyC < ${t.outWidth}.0)
&& (fract(dyC) == 0.0);
int idyC = int(dyC);
float dyC2 = float(dyCCorner + wC + 1) / strides[1];
bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${t.outWidth}.0)
&& (fract(dyC2) == 0.0);
int idyC2 = int(dyC2);
if (idyCVal && idyCVal2) {
for (int d2 = 0; d2 < ${t.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 < ${t.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 < ${t.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);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Hz(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, filter: r } = t, { inputShape: i, strides: a, pad: l, dataFormat: c, dimRoundingMode: u } = s, h = Qn(c), d = xe(i, r.shape, a, 1, l, u, !1, h);
if (P().getBool("WEBGL_PACK_CONV2DTRANSPOSE") && h === "channelsLast") {
const p = [
[d.strideHeight, d.strideWidth]
], f = new Gz(d);
return e.runWebGLProgram(f, [o, r], "float32", p);
} else {
const p = new zz(d);
return e.runWebGLProgram(p, [o, r], "float32");
}
}
const Kz = {
kernelName: Ua,
backendName: "webgl",
kernelFunc: Hz
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function jz(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r } = t, { strides: i, pad: a, dilations: l } = s, c = Cs(o.shape, r.shape, i, l, a), u = new Oz(c);
return e.runWebGLProgram(u, [o, r], "float32");
}
const Xz = {
kernelName: Ga,
backendName: "webgl",
kernelFunc: jz
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function qz(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, dy: r } = t, { strides: i, pad: a, filterShape: l } = s, c = Cs(o.shape, l, i, 1, a), u = new Bz(c);
return e.runWebGLProgram(u, [o, r], "float32");
}
const Yz = {
kernelName: _u,
backendName: "webgl",
kernelFunc: qz
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Jz(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, filter: r } = t, { pad: i, strides: a, inputShape: l } = s, c = Cs(l, r.shape, a, 1, i), u = new Vz(c);
return e.runWebGLProgram(u, [o, r], "float32");
}
const Zz = {
kernelName: Lu,
backendName: "webgl",
kernelFunc: Jz
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Qz = Jo + `
return cos(x);
`, tB = `
vec4 result = cos(x);
bvec4 isNaN = isnan(x);
${ho}
return result;
`, eB = vt({ opSnippet: Qz, packedOpSnippet: tB }), nB = {
kernelName: Lr,
backendName: "webgl",
kernelFunc: eB
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sB = `
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`, oB = vt({ opSnippet: sB }), rB = {
kernelName: Mr,
backendName: "webgl",
kernelFunc: oB
};
/**
* @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.
* =============================================================================
*/
class iB {
constructor(t, e, s, o, r) {
this.variableNames = ["Image", "Boxes", "BoxInd"], this.outputShape = [];
const [i, a, l, c] = t, [u] = e, [h, d] = s;
this.outputShape = [u, h, d, c];
const p = o === "bilinear" ? 1 : 0, [f, m] = [`${a - 1}.0`, `${l - 1}.0`], [g, x, b] = h > 1 ? [
`${(a - 1) / (h - 1)}`,
"(y2-y1) * height_ratio",
`y1*${f} + float(y)*(height_scale)`
] : [
"0.0",
"0.0",
`0.5 * (y1+y2) * ${f}`
], [w, y, C] = d > 1 ? [
`${(l - 1) / (d - 1)}`,
"(x2-x1) * width_ratio",
`x1*${m} + float(x)*(width_scale)`
] : [
"0.0",
"0.0",
`0.5 * (x1+x2) * ${m}`
];
this.userCode = `
const float height_ratio = float(${g});
const float width_ratio = float(${w});
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 >= ${i}) {
return;
}
float height_scale = ${x};
float width_scale = ${y};
float in_y = ${b};
if( in_y < 0.0 || in_y > ${f} ) {
setOutput(float(${r}));
return;
}
float in_x = ${C};
if( in_x < 0.0 || in_x > ${m} ) {
setOutput(float(${r}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${p} == 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);
}
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const aB = (n) => {
const { inputs: t, backend: e, attrs: s } = n, { image: o, boxes: r, boxInd: i } = t, { cropSize: a, method: l, extrapolationValue: c } = s, u = new iB(o.shape, r.shape, a, l, c);
return e.runWebGLProgram(u, [o, r, i], "float32");
}, lB = {
kernelName: Pu,
backendName: "webgl",
kernelFunc: aB
};
var kr;
(function(n) {
n.Prod = "*", n.Sum = "+";
})(kr || (kr = {}));
class If {
constructor(t, e, s, o) {
this.op = t, this.outputShape = e, this.variableNames = ["x"], this.customUniforms = [{ name: "index", type: "float" }];
const r = this.outputShape.length, i = this.op === kr.Prod ? "1.0" : "0.0", a = s ? i : `getX(${kf(r, "coords", this.op)})`, l = this.outputShape[this.outputShape.length - 1];
let c = "", u = "";
s ? (c = o ? `end != ${l - 1}` : "end != 0", u = o ? "end + 1" : "end - 1") : (c = o ? `end + pow2 < ${l}` : "end >= pow2", u = o ? "end + pow2" : "end - pow2"), this.userCode = `
void main() {
${Ot(r)} coords = getOutputCoords();
int end = ${vf(r, "coords", this.op)};
float val = ${a};
int pow2 = int(pow(2.0, index));
if (${c}) {
int idx = ${u};
${vf(r, "coords", this.op)} = idx;
val ${this.op}= getX(${kf(r, "coords", this.op)});
}
setOutput(val);
}
`;
}
}
function kf(n, t, e) {
if (n === 1)
return `${t}`;
if (n === 2)
return `${t}.x, ${t}.y`;
if (n === 3)
return `${t}.x, ${t}.y, ${t}.z`;
if (n === 4)
return `${t}.x, ${t}.y, ${t}.z, ${t}.w`;
throw new Error(`Cumulative ${e} for rank ${n} is not yet supported`);
}
function vf(n, t, e) {
if (n === 1)
return `${t}`;
if (n === 2)
return `${t}.y`;
if (n === 3)
return `${t}.z`;
if (n === 4)
return `${t}.w`;
throw new Error(`Cumulative ${e} for rank ${n} is not yet supported`);
}
/**
* @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.
* =============================================================================
*/
function t1(n, t, e, s, o, r) {
const i = t.shape.length, a = jt([s], i);
let l = t;
a != null && (l = De({ inputs: { x: t }, backend: e, attrs: { perm: a } }));
const c = Zt(1, i)[0];
if (c !== i - 1)
throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length - 1} but got axis=${s}`);
const u = l.shape[c];
let h = He({ inputs: { x: l }, backend: e });
for (let d = 0; d <= Math.ceil(Math.log2(u)) - 1; d++) {
const p = new If(n, l.shape, !1, r), f = [[d]], m = h;
h = e.runWebGLProgram(p, [h], h.dtype, f), e.disposeIntermediateTensorInfo(m);
}
if (o) {
const d = new If(n, l.shape, o, r), p = h;
h = e.runWebGLProgram(d, [h], h.dtype), e.disposeIntermediateTensorInfo(p);
}
if (a != null) {
const d = $s(a), p = De({ inputs: { x: h }, backend: e, attrs: { perm: d } });
return e.disposeIntermediateTensorInfo(h), e.disposeIntermediateTensorInfo(l), p;
}
return h;
}
/**
* @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.
* =============================================================================
*/
function cB(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, exclusive: i, reverse: a } = s;
return t1(kr.Prod, o, e, r, i, a);
}
const uB = {
kernelName: Mu,
backendName: "webgl",
kernelFunc: cB
};
/**
* @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.
* =============================================================================
*/
function hB(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, exclusive: i, reverse: a } = s;
return t1(kr.Sum, o, e, r, i, a);
}
const dB = {
kernelName: Ha,
backendName: "webgl",
kernelFunc: hB
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function pB(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, weights: r } = t, { size: i, binaryOutput: a } = s;
if (o.shape.length === 1) {
const l = e.readSync(o.dataId), c = e.readSync(r.dataId), u = Oy(l, c, r.dtype, r.shape, i);
return e.makeTensorInfo([i], r.dtype, u);
} else if (o.shape.length === 2) {
const l = e.bufferSync(o), c = e.bufferSync(r), u = xM(l, c, i, a);
return e.makeTensorInfo(u.shape, r.dtype, u.values);
}
throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`);
}
const fB = {
kernelName: zu,
backendName: "webgl",
kernelFunc: pB
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class mB {
constructor(t, e, s) {
this.variableNames = ["x"], this.outputShape = [], this.outputShape = t, this.blockSize = e, this.dataFormat = s, 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 / ${e};
int offset_h = imod(h, ${e});
int in_w = w / ${e};
int offset_w = imod(w, ${e});
int offset_d = (offset_h * ${e} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`;
}
getHeightCoordString() {
return this.dataFormat === "NHWC" ? "coords[1]" : "coords[2]";
}
getWidthCoordString() {
return this.dataFormat === "NHWC" ? "coords[2]" : "coords[3]";
}
getDepthCoordString() {
return this.dataFormat === "NHWC" ? "coords[3]" : "coords[1]";
}
getOutputDepthSize() {
return this.dataFormat === "NHWC" ? this.outputShape[3] : this.outputShape[1];
}
getInputSamplingString() {
return this.dataFormat === "NHWC" ? "getX(b, in_h, in_w, in_d)" : "getX(b, in_d, in_h, in_w)";
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function gB(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { blockSize: r, dataFormat: i } = s, a = o.shape[0], l = i === "NHWC" ? o.shape[1] : o.shape[2], c = i === "NHWC" ? o.shape[2] : o.shape[3], u = i === "NHWC" ? o.shape[3] : o.shape[1], h = l * r, d = c * r, p = u / (r * r), f = i === "NHWC" ? [a, h, d, p] : [a, p, h, d], m = new mB(f, r, i);
return e.runWebGLProgram(m, [o], o.dtype);
}
const xB = {
kernelName: Bu,
backendName: "webgl",
kernelFunc: gB
};
/**
* @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.
* =============================================================================
*/
class e1 {
constructor(t, e = !1, s = null, o = !1, r = !1) {
this.variableNames = ["x", "W"], this.customUniforms = [
{ name: "pads", type: "ivec2" },
{ name: "strides", type: "ivec2" },
{ name: "dilations", type: "ivec2" },
{ name: "inDims", type: "ivec2" }
], this.outputShape = t.outShape, this.enableShapeUniforms = ve(this.outputShape.length);
const i = t.filterHeight, a = t.filterWidth, l = t.outChannels / t.inChannels;
let c = "", u = "";
s && (o ? c = `float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}` : r ? c = `float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${s}
}` : c = `
float activation(float x) {
${s}
}
`, u = "result = activation(result);");
const h = e ? "result += getBiasAtOutCoords();" : "";
e && this.variableNames.push("bias"), o && this.variableNames.push("preluActivationWeights"), r && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${c}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${l};
int q = d2 - d1 * ${l};
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 < ${i}; wR++) {
int xR = xRCorner + wR * dilations[0];
if (xR < 0 || xR >= inDims[0]) {
continue;
}
for (int wC = 0; wC < ${a}; 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;
${h}
${u}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class n1 {
constructor(t, e = !1, s = null, o = !1, r = !1) {
this.variableNames = ["x", "W"], this.packedInputs = !0, this.packedOutput = !0, this.customUniforms = [
{ name: "pads", type: "ivec2" },
{ name: "strides", type: "ivec2" },
{ name: "dilations", type: "ivec2" },
{ name: "inDims", type: "ivec2" }
], this.outputShape = t.outShape, this.enableShapeUniforms = ve(this.outputShape.length);
const i = t.outChannels / t.inChannels, a = t.padInfo.left, l = t.strideWidth, c = t.dilationWidth, u = t.filterHeight, h = t.filterWidth, d = h;
let p = `
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;
for (let x = 0; x < h; x++)
p += `
vec4 xTexelC${x * 2};
int xTexelC${x * 2}Ready;
vec4 xTexelC${x * 2 + 1};
int xTexelC${x * 2 + 1}Ready;
vec4 xC${x};`;
p += `
for (int r = 0; r < ${u}; r++) {
`;
for (let x = 0; x < h; x++)
p += `
xTexelC${x * 2} = vec4(0.0);
xTexelC${x * 2}Ready = 0;
xTexelC${x * 2 + 1} = vec4(0.0);
xTexelC${x * 2 + 1}Ready = 0;
xC${x} = vec4(0.0);`;
p += `
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;
for (let x = 0; x < (d + 1) / 2; x++) {
const b = x * 2;
if (p += `
xC = xCCorner + ${b * c};
`, l === 1) {
if (b < h && (a % 2 === 1 ? (p += `
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = 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${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
`, c === 1 && b > 0 ? p += `
xC${b} = vec4(xTexelC${b - 2}.zw, xTexelC${b}.xy);
` : p += `
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${b} = vec4(previous.zw, xTexelC${b}.xy);
} else {
xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
}
`) : p += `
if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
xC${b} = xTexelC${b};
`, b + 1 < h)) {
const w = a % 2 === 0 ? Cu(c) : c;
c % 2 === 0 && a % 2 === 1 || c % 2 !== 0 && a % 2 !== 1 ? (p += `
xCOffset = xC + imod(pads[1], 2) + ${w};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
xTexelC${b + 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${b + 1}.zw = vec2(0.0);
}
xTexelC${b + 1}Ready = 1;
}
`, c > 1 ? p += `
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
xC${b + 1} = vec4(previous.zw, xTexelC${b + 1}.xy);
} else {
xC${b + 1} = vec4(0.0, 0.0, xTexelC${b + 1}.xy);
}
` : p += `
xC${b + 1} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.xy);
`) : w === 1 ? p += `
xC${b + 1} = xTexelC${b};
` : p += `
xCOffset = xC + ${w};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
xTexelC${b + 1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b + 1}.zw = vec2(0.0);
}
xTexelC${b + 1}Ready = 1;
}
xC${b + 1} = xTexelC${b + 1};
`;
}
} else
b < h && (a % 2 === 1 ? (p += `
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = 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${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b + 1}Ready == 0) {
xTexelC${b + 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${b + 1}.zw = vec2(0.0);
}
xTexelC${b + 1}Ready = 1;
}
xC${b} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.zw);
`, b + 1 < h && (p += `
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${b + 1} = vec4(xTexelC${b + 1}.xy, final.xy);
`)) : (p += `
if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
xTexelC${b + 1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b + 1}.zw = vec2(0.);
}
xTexelC${b + 1}Ready = 1;
}
xC${b} = vec4(
xTexelC${b}.xy, xTexelC${b + 1}.xy);
`, b + 1 < h && (p += `
xC${b + 1} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.zw);
`)));
b < h && (p += `
wTexel = getW(r, ${b}, d1, q);
dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
`, b + 1 < h && (p += `
wTexel = getW(r, ${b + 1}, d1, q);
dotProd += xC${b + 1} * vec4(wTexel.xz, wTexel.xz);
`));
}
p += `
}
`, p += `
}
`;
let f = "", m = "";
s && (o ? f = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${s}
}` : r ? f = `vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${s}
}` : f = `vec4 activation(vec4 x) {
${s}
}`, m = "result = activation(result);");
const g = e ? "result += getBiasAtOutCoords();" : "";
e && this.variableNames.push("bias"), o && this.variableNames.push("preluActivationWeights"), r && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${f}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${i};
int q = d2 - d1 * ${i};
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);
${p}
vec4 result = dotProd - vec4(0.000000000000001);
${g}
${m}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function bB(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r } = t, { strides: i, pad: a, dilations: l, dimRoundingMode: c } = s;
let u = l;
u == null && (u = [1, 1]), I(Ie(i, u), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);
const h = xe(
o.shape,
r.shape,
i,
u,
a,
c,
!0
/* depthwise */
);
let d;
P().getBool("WEBGL_PACK_DEPTHWISECONV") && h.strideWidth <= 2 && h.outChannels / h.inChannels === 1 ? d = new n1(h) : d = new e1(h);
const p = [
[h.padInfo.top, h.padInfo.left],
[h.strideHeight, h.strideWidth],
[h.dilationHeight, h.dilationWidth],
[h.inHeight, h.inWidth]
];
return e.runWebGLProgram(d, [o, r], "float32", p);
}
const yB = {
kernelName: Ka,
backendName: "webgl",
kernelFunc: bB
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class wB {
constructor(t) {
this.variableNames = ["x", "dy"], this.outputShape = t.filterShape;
const e = t.strideHeight, s = t.strideWidth, o = t.padInfo.top, r = t.padInfo.left, i = t.outChannels / t.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 * ${i} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${t.batchSize}; b++) {
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${e} - ${o};
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${r};
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`;
}
}
class CB {
constructor(t) {
this.variableNames = ["dy", "W"], this.outputShape = t.inShape;
const e = t.filterHeight, s = t.filterWidth, o = t.strideHeight, r = t.strideWidth, i = e - 1 - t.padInfo.top, a = s - 1 - t.padInfo.left, l = t.outChannels / t.inChannels;
this.userCode = `
const ivec2 pads = ivec2(${i}, ${a});
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 < ${e}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${e} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${l}; dm++) {
int d2 = d1 * ${l} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function $B(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, dy: r } = t, { strides: i, dilations: a, pad: l, dimRoundingMode: c, filterShape: u } = s, h = xe(
o.shape,
u,
i,
a,
l,
c,
!0
/* depthwise */
), d = new wB(h);
return e.runWebGLProgram(d, [o, r], "float32");
}
const IB = {
kernelName: Vu,
backendName: "webgl",
kernelFunc: $B
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kB(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, filter: r } = t, { strides: i, dilations: a, pad: l, dimRoundingMode: c, inputShape: u } = s, h = xe(
u,
r.shape,
i,
a,
l,
c,
!0
/* depthwise */
), d = new CB(h);
return e.runWebGLProgram(d, [o, r], "float32");
}
const vB = {
kernelName: Wu,
backendName: "webgl",
kernelFunc: kB
};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class SB {
constructor(t) {
this.variableNames = ["X"], this.outputShape = [t, t], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function NB(n) {
const { inputs: t, backend: e } = n, { x: s } = t, o = [...s.shape, ...s.shape], r = G(s.shape), i = tt({ inputs: { x: s }, backend: e, attrs: { shape: [r] } }), a = new SB(r), l = e.runWebGLProgram(a, [i], i.dtype), c = tt({ inputs: { x: l }, backend: e, attrs: { shape: o } });
return e.disposeIntermediateTensorInfo(i), e.disposeIntermediateTensorInfo(l), c;
}
const TB = {
kernelName: Uf,
backendName: "webgl",
kernelFunc: NB
};
/**
* @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.
* =============================================================================
*/
class EB {
constructor(t) {
this.variableNames = ["x", "W"], this.outputShape = t.outShape;
const { inHeight: e, inWidth: s, padInfo: o, strideHeight: r, strideWidth: i, filterHeight: a, filterWidth: l, dilationHeight: c, dilationWidth: u } = t, { top: h, left: d } = o;
this.userCode = `
const ivec2 strides = ivec2(${r}, ${i});
const ivec2 pads = ivec2(${h}, ${d});
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 < ${a}; h++) {
int hIn = hBeg + h * ${c};
if (hIn >= 0 && hIn < ${e}) {
for (int w = 0; w < ${l}; w++) {
int wIn = wBeg + w * ${u};
if (wIn >= 0 && wIn < ${s}) {
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);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function RB(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r } = t, { strides: i, pad: a, dilations: l } = s, c = Ci(o.shape, r.shape, i, a, "NHWC", l);
let u;
const h = new EB(c);
u = e.runWebGLProgram(h, [o, r], "float32");
const d = tt({ inputs: { x: u }, backend: e, attrs: { shape: c.outShape } });
return e.disposeIntermediateTensorInfo(u), d;
}
const DB = {
kernelName: ja,
backendName: "webgl",
kernelFunc: RB
};
/**
* @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.
* =============================================================================
*/
function AB(n) {
const { inputs: t, backend: e, attrs: s } = n, { equation: o } = s, r = t, { allDims: i, summedDims: a, idDims: l } = ld(o, r.length);
ud(i.length, l, r);
const { path: c, steps: u } = hd(a, l), h = u.length;
let d = null, p = i.length;
const f = [];
for (let m = 0; m < h; ++m) {
for (const g of u[m]) {
const { permutationIndices: x, expandDims: b } = cd(p, l[g]);
let w;
dd(x) ? w = r[g] : (w = De({ inputs: { x: r[g] }, backend: e, attrs: { perm: x } }), f.push(w));
const y = w.shape.slice();
for (let C = 0; C < b.length; ++C)
y.splice(b[C], 0, 1);
Et(w.shape, y) || (w = tt({ inputs: { x: w }, backend: e, attrs: { shape: y } }), f.push(w)), d === null ? d = w : (d = Zd({ inputs: { a: w, b: d }, backend: e }), f.push(d));
}
m < h - 1 && (c[m] >= 0 && (d = ac({
inputs: { x: d },
backend: e,
attrs: {
axis: c[m] - (i.length - p),
keepDims: !1
}
}), f.push(d)), p--);
}
for (const m of f)
m !== d && e.disposeIntermediateTensorInfo(m);
return d;
}
const FB = {
kernelName: Uu,
backendName: "webgl",
kernelFunc: AB
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const OB = "return (x >= 0.0) ? x : (exp(x) - 1.0);", _B = `
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;
`, LB = vt({ opSnippet: OB, packedOpSnippet: _B }), MB = {
kernelName: zr,
backendName: "webgl",
kernelFunc: LB
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const PB = "return (b >= 0.0) ? a : a * (b + 1.0);", zB = `
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`, BB = (n) => {
const { inputs: t, backend: e } = n, { dy: s, y: o } = t, r = P().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new Yo(zB, s.shape, o.shape) : new to(PB, s.shape, o.shape);
return e.runWebGLProgram(r, [s, o], s.dtype);
}, VB = {
kernelName: Gu,
backendName: "webgl",
kernelFunc: BB
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const WB = `
return vec4(equal(a, b));
`, UB = "return float(a == b);", GB = ye({
opSnippet: UB,
packedOpSnippet: WB,
dtype: "bool",
cpuKernelImpl: $M
}), HB = {
kernelName: Xa,
backendName: "webgl",
kernelFunc: GB
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const KB = `
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${ed};
float a1 = ${nd};
float a2 = ${sd};
float a3 = ${od};
float a4 = ${rd};
float a5 = ${id};
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));
`, jB = vt({ opSnippet: KB }), XB = {
kernelName: Br,
backendName: "webgl",
kernelFunc: jB
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const qB = Jo + `
return exp(x);
`, YB = `
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;
`, s1 = vt({
opSnippet: qB,
packedOpSnippet: YB,
cpuKernelImpl: IM,
dtype: "float32"
}), JB = {
kernelName: Vr,
backendName: "webgl",
kernelFunc: s1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function du(n) {
const { inputs: t, attrs: e, backend: s } = n, { dim: o } = e, { input: r } = t, i = r.shape.length, a = r.shape.slice();
let l = o;
return o < 0 && (I(-(i + 1) <= o, () => `Axis must be in the interval [${-(i + 1)}, ${i}]`), l = i + o + 1), a.splice(l, 0, 1), tt({ inputs: { x: r }, backend: s, attrs: { shape: a } });
}
const ZB = {
kernelName: qa,
backendName: "webgl",
kernelFunc: du
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Sf = "return exp(x) - 1.0;", QB = vt({ opSnippet: Sf, packedOpSnippet: Sf, cpuKernelImpl: kM }), tV = {
kernelName: Wr,
backendName: "webgl",
kernelFunc: QB
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Nf {
constructor(t, e, s) {
this.variableNames = ["real", "imag"];
const o = e[1];
this.outputShape = e;
const r = s ? `2.0 * ${Math.PI}` : `-2.0 * ${Math.PI}`, i = s ? `${o}.0` : "1.0";
let a;
if (t === "real")
a = "return real * expR - imag * expI;";
else if (t === "imag")
a = "return real * expI + imag * expR;";
else
throw new Error(`FFT component must be either "real" or "imag", got ${t}.`);
this.userCode = `
const float exponentMultiplier = ${r};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${a}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${o});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${o}; 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) / ${i};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function o1(n, t, e) {
const s = e.texData.get(n.dataId), o = G(n.shape), r = n.shape[n.shape.length - 1], i = o / r, a = tt({ inputs: { x: n }, backend: e, attrs: { shape: [i, r] } }), l = a.shape, c = new Nf("real", l, t), u = new Nf("imag", l, t), h = [
{
dataId: s.complexTensorInfos.real.dataId,
dtype: s.complexTensorInfos.real.dtype,
shape: l
},
{
dataId: s.complexTensorInfos.imag.dataId,
dtype: s.complexTensorInfos.imag.dtype,
shape: l
}
], d = e.runWebGLProgram(c, h, "float32"), p = e.runWebGLProgram(u, h, "float32"), f = Ts({ inputs: { real: d, imag: p }, backend: e });
e.disposeIntermediateTensorInfo(d), e.disposeIntermediateTensorInfo(p);
const m = tt({ inputs: { x: f }, backend: e, attrs: { shape: n.shape } });
return e.disposeIntermediateTensorInfo(a), e.disposeIntermediateTensorInfo(f), m;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function eV(n) {
const { inputs: t, backend: e } = n, { input: s } = t;
return o1(s, !1, e);
}
const nV = {
kernelName: Hu,
backendName: "webgl",
kernelFunc: eV
};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class sV {
constructor(t, e) {
this.outputShape = [], this.customUniforms = [{ name: "value", type: "float" }], this.variableNames = ["x"], this.outputShape = t, this.userCode = `
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Wi(n) {
const { backend: t, attrs: e } = n, { shape: s, value: o } = e;
let { dtype: r } = e;
if (r = r || Lo(o), r === "string") {
const i = qt(r, G(s));
return i.fill(o), t.makeTensorInfo(s, r, i);
} else {
const i = new sV(s, o), a = [[o]];
return t.runWebGLProgram(i, [], r, a);
}
}
const oV = {
kernelName: Ku,
backendName: "webgl",
kernelFunc: Wi
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class rV {
constructor(t) {
this.variableNames = ["Image"], this.outputShape = [];
const e = t[2];
this.outputShape = t, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${e} - x - 1;
float outputValue;
if(coordX >= 0 && coordX < ${e}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const iV = {
kernelName: ju,
backendName: "webgl",
kernelFunc: ({ inputs: n, backend: t }) => {
const { image: e } = n, s = t, o = new rV(e.shape);
return s.runWebGLProgram(o, [e], e.dtype);
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Tf = "return floor(x);", aV = vt({ opSnippet: Tf, packedOpSnippet: Tf, cpuKernelImpl: vM }), lV = {
kernelName: Ur,
backendName: "webgl",
kernelFunc: aV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const cV = `
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;
}
`, uV = `
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);
`, hV = ye({ opSnippet: cV, packedOpSnippet: uV, dtype: "int32" }), dV = {
kernelName: Gr,
backendName: "webgl",
kernelFunc: hV
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class pV {
constructor(t) {
this.variableNames = ["A"];
const e = Ae(), [s, o] = t;
this.outputShape = t, 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(${o}.0, ${s}.0);
vec4 values = ${e.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));
}
`;
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class fV {
constructor(t) {
this.variableNames = ["A"], this.packedInputs = !1, this.packedOutput = !0;
const e = Ae(), [s, o] = t;
this.outputShape = t, 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(${o}.0, ${s}.0);
vec4 values = ${e.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);
}
}
${e.output} = result;
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const mV = {
kernelName: J1,
backendName: "webgl",
kernelFunc: gV
};
let go, Tc = P().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
function gV(n) {
const { inputs: t, backend: e, attrs: s } = n;
let { pixels: o } = t;
const { numChannels: r } = s, i = typeof HTMLVideoElement < "u" && o instanceof HTMLVideoElement, a = typeof HTMLImageElement < "u" && o instanceof HTMLImageElement, [l, c] = i ? [
o.videoWidth,
o.videoHeight
] : [o.width, o.height], u = [c, l], h = [c, l, r];
if (a || i) {
const m = P().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
(go == null || m !== Tc) && (Tc = m, go = document.createElement("canvas").getContext("2d", { willReadFrequently: Tc })), go.canvas.width = l, go.canvas.height = c, go.drawImage(o, 0, 0, l, c), o = go.canvas;
}
const d = e.makeTensorInfo(u, "int32");
e.texData.get(d.dataId).usage = Xe.PIXELS, e.gpgpu.uploadPixelDataToTexture(e.getTexture(d.dataId), o);
const p = P().getBool("WEBGL_PACK") ? new fV(h) : new pV(h), f = e.runWebGLProgram(p, [d], "int32");
return e.disposeData(d.dataId), f;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function xV(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r, bias: i, preluActivationWeights: a } = t, { strides: l, pad: c, dataFormat: u, dilations: h, dimRoundingMode: d, activation: p, leakyreluAlpha: f } = s, m = Qn(u), g = xe(o.shape, r.shape, l, h, c, d, !1, m);
let x;
const b = [], w = i != null, y = a != null, C = p === "leakyrelu", $ = () => {
const v = [o, r], S = (T, F) => {
if (F === "NCHW" && T.shape.length === 1 && T.shape[0] !== 1) {
const L = tt({
inputs: { x: T },
backend: e,
attrs: { shape: [T.shape[0], 1, 1] }
});
return b.push(L), L;
}
return T;
};
if (w && v.push(S(i, u)), y && v.push(S(a, u)), C) {
const T = e.makeTensorInfo([], "float32", ws(f, "float32"));
v.push(T), b.push(T);
}
return v;
};
if (g.filterHeight === 1 && g.filterWidth === 1 && g.dilationHeight === 1 && g.dilationWidth === 1 && g.strideHeight === 1 && g.strideWidth === 1 && (g.padInfo.type === "SAME" || g.padInfo.type === "VALID"))
x = Zy({
x: o,
filter: r,
convInfo: g,
backend: e,
bias: i,
activation: p,
preluActivationWeights: a,
leakyreluAlpha: f
});
else if (g.strideWidth <= 2 && m === "channelsLast" && P().getBool("WEBGL_EXP_CONV")) {
const v = p ? $r(p, !0) : null, S = new Jy(g, w, v, y, C), T = [
[g.padInfo.top, g.padInfo.left],
[g.strideHeight, g.strideWidth],
[g.dilationHeight, g.dilationWidth],
[g.inHeight, g.inWidth]
], F = $();
x = e.runWebGLProgram(S, F, "float32", T);
} else if (P().getBool("WEBGL_CONV_IM2COL"))
x = Qy({
x: o,
filter: r,
convInfo: g,
backend: e,
bias: i,
activation: p,
preluActivationWeights: a,
leakyreluAlpha: f
});
else {
const v = p ? $r(p, !1) : null, S = new Yy(g, w, v, y, C), T = $();
x = e.runWebGLProgram(S, T, "float32");
}
const k = tt({ inputs: { x }, backend: e, attrs: { shape: g.outShape } });
return b.push(x), b.forEach((v) => e.disposeIntermediateTensorInfo(v)), k;
}
const bV = {
kernelName: aa,
backendName: "webgl",
kernelFunc: xV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yV(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, filter: r, bias: i, preluActivationWeights: a } = t, { strides: l, pad: c, dilations: u, dimRoundingMode: h, activation: d, leakyreluAlpha: p } = s, f = [];
let m = u;
m == null && (m = [1, 1]), I(Ie(l, m), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);
const g = xe(
o.shape,
r.shape,
l,
m,
c,
h,
!0
/* depthwise */
), x = P().getBool("WEBGL_PACK_DEPTHWISECONV") && g.strideWidth <= 2 && g.outChannels / g.inChannels === 1, b = d ? $r(d, x) : null, w = [o, r], y = i != null, C = a != null, $ = d === "leakyrelu";
if (y && w.push(i), C && w.push(a), $) {
const T = e.makeTensorInfo([], "float32", ws(p, "float32"));
w.push(T), f.push(T);
}
let k;
x ? k = new n1(g, y, b, C, $) : k = new e1(g, y, b, C, $);
const v = [
[g.padInfo.top, g.padInfo.left],
[g.strideHeight, g.strideWidth],
[g.dilationHeight, g.dilationWidth],
[g.inHeight, g.inWidth]
], S = e.runWebGLProgram(k, w, "float32", v);
return f.forEach((T) => e.disposeIntermediateTensorInfo(T)), S;
}
const wV = {
kernelName: lm,
backendName: "webgl",
kernelFunc: yV
};
class CV {
constructor(t, e, s, o) {
this.sliceDim = t, this.strides = e, this.paramsShape = o, this.variableNames = ["x", "indices"], this.outputShape = s;
const r = Ot(s.length);
let i = `
int index;`;
for (let a = 0; a < this.sliceDim; a++)
i += `
index = round(getIndices(coords[0], ${a}));
out_of_bounds = out_of_bounds || index < 0;
out_of_bounds = out_of_bounds || index >= ${this.paramsShape[a]};
flattenIndex += index * ${this.strides[a]};`;
this.userCode = `
void main() {
${r} coords = getOutputCoords();
int flattenIndex = 0;
bool out_of_bounds = false;
${i}
setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function $V(n) {
const { inputs: t, backend: e } = n, { params: s, indices: o } = t, r = o.shape, i = r[r.length - 1], a = G(s.shape), [l, c, u, h] = Gh(s, o), d = tt({ inputs: { x: o }, backend: e, attrs: { shape: [c, i] } }), p = tt({
inputs: { x: s },
backend: e,
attrs: { shape: [G(s.shape) / u, u] }
});
if (e.shouldExecuteOnCPU([s, o]) || s.dtype === "string") {
const x = e.readSync(o.dataId), b = e.bufferSync(s), w = SM(x, b, s.dtype, c, i, u, h, s.shape, a);
return e.makeTensorInfo(l, s.dtype, w.values);
}
const f = new CV(i, h, [c, u], s.shape), m = e.runWebGLProgram(f, [p, d], p.dtype), g = tt({ inputs: { x: m }, backend: e, attrs: { shape: l } });
return e.disposeIntermediateTensorInfo(d), e.disposeIntermediateTensorInfo(p), e.disposeIntermediateTensorInfo(m), g;
}
const IV = {
kernelName: Gf,
backendName: "webgl",
kernelFunc: $V
};
/**
* @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.
* =============================================================================
*/
class kV {
constructor(t, e) {
this.variableNames = ["A", "indices"], this.outputShape = e, this.rank = e.length;
const s = Ot(this.rank), o = vV(t);
this.userCode = `
void main() {
${s} resRC = getOutputCoords();
int index = int(getIndices(resRC.x, resRC.z));
float inBounds = (index >= 0) && (index < ${t[2]}) ? 1.0 : 0.0;
setOutput(inBounds * getA(${o}));
}
`;
}
}
function vV(n, t) {
const e = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], s = [];
for (let o = 0; o < n.length; o++)
o === 2 ? s.push("index") : s.push(`${e[o]}`);
return s.join();
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function r1(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, indices: r } = t, { axis: i, batchDims: a } = s, l = wt(i, o.shape)[0];
if (P().get("DEBUG")) {
const b = e.readSync(r.dataId), w = o.shape[l];
for (let y = 0; y < b.length; ++y) {
const C = b[y];
I(C <= w - 1 && C >= 0, () => `GatherV2: the index value ${C} is not in [0, ${w - 1}]`);
}
}
const c = fd(o, r, l, a), u = G(r.shape), h = [], d = tt({
inputs: { x: o },
backend: e,
attrs: {
shape: [
c.batchSize,
c.outerSize,
c.dimSize,
c.sliceSize
]
}
}), p = tt({
inputs: { x: r },
backend: e,
attrs: { shape: [c.batchSize, u / c.batchSize] }
});
h.push(d), h.push(p);
const f = [
c.batchSize,
c.outerSize,
u / c.batchSize,
c.sliceSize
];
if (e.shouldExecuteOnCPU([o, r]) || o.dtype === "string") {
const b = e.bufferSync(p), w = e.bufferSync(d), y = NM(w, b, f);
return h.forEach((C) => e.disposeIntermediateTensorInfo(C)), e.makeTensorInfo(c.outputShape, y.dtype, y.values);
}
const m = new kV(d.shape, f), g = e.runWebGLProgram(m, [d, p], d.dtype);
h.push(g);
const x = tt({ inputs: { x: g }, backend: e, attrs: { shape: c.outputShape } });
return h.forEach((b) => e.disposeIntermediateTensorInfo(b)), x;
}
const SV = {
kernelName: Ja,
backendName: "webgl",
kernelFunc: r1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const NV = "return float(a > b);", TV = `
return vec4(greaterThan(a, b));
`, EV = ye({
opSnippet: NV,
packedOpSnippet: TV,
cpuKernelImpl: TM,
dtype: "bool"
}), RV = {
kernelName: Za,
backendName: "webgl",
kernelFunc: EV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const DV = "return float(a >= b);", AV = `
return vec4(greaterThanEqual(a, b));
`, FV = ye({
opSnippet: DV,
packedOpSnippet: AV,
dtype: "bool",
cpuKernelImpl: EM
}), OV = {
kernelName: Hr,
backendName: "webgl",
kernelFunc: FV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _V(n) {
const { inputs: t, backend: e } = n, { input: s } = t;
return o1(s, !0, e);
}
const LV = {
kernelName: Xu,
backendName: "webgl",
kernelFunc: _V
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const MV = "return float(!isnan(x) && !isinf(x));", PV = vt({ opSnippet: MV, dtype: "bool" }), zV = {
kernelName: jr,
backendName: "webgl",
kernelFunc: PV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const BV = "return float(isinf(x));", VV = vt({ opSnippet: BV, dtype: "bool" }), WV = {
kernelName: Xr,
backendName: "webgl",
kernelFunc: VV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const UV = "return float(isnan(x));", GV = vt({ opSnippet: UV, dtype: "bool" }), HV = {
kernelName: qr,
backendName: "webgl",
kernelFunc: GV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const KV = "return float(a < b);", jV = `
return vec4(lessThan(a, b));
`, XV = ye({
opSnippet: KV,
packedOpSnippet: jV,
cpuKernelImpl: RM,
dtype: "bool"
}), qV = {
kernelName: tl,
backendName: "webgl",
kernelFunc: XV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const YV = "return float(a <= b);", JV = `
return vec4(lessThanEqual(a, b));
`, ZV = ye({
opSnippet: YV,
packedOpSnippet: JV,
cpuKernelImpl: DM,
dtype: "bool"
}), QV = {
kernelName: el,
backendName: "webgl",
kernelFunc: ZV
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function tW(n) {
const { backend: t, attrs: e } = n, { start: s, stop: o, num: r } = e, i = AM(s, o, r);
return t.makeTensorInfo([i.length], "float32", i);
}
const eW = {
kernelName: Hf,
backendName: "webgl",
kernelFunc: tW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const nW = Jo + `
return x < 0.0 ? 0./0. : log(x);
`, sW = `
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;
`, oW = vt({ opSnippet: nW, packedOpSnippet: sW, cpuKernelImpl: FM }), rW = {
kernelName: Yr,
backendName: "webgl",
kernelFunc: oW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const iW = Jo + `
return log(1.0 + x);
`, aW = vt({ opSnippet: iW }), lW = {
kernelName: Jr,
backendName: "webgl",
kernelFunc: aW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const cW = "return float(a >= 1.0 && b >= 1.0);", uW = `
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`, hW = ye({
opSnippet: cW,
packedOpSnippet: uW,
dtype: "bool"
}), dW = {
kernelName: nl,
backendName: "webgl",
kernelFunc: hW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const pW = "return float(!(x >= 1.0));", fW = vt({ opSnippet: pW }), mW = {
kernelName: sl,
backendName: "webgl",
kernelFunc: fW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const gW = "return float(a >= 1.0 || b >= 1.0);", xW = `
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`, bW = ye({ opSnippet: gW, packedOpSnippet: xW, dtype: "bool" }), yW = {
kernelName: ol,
backendName: "webgl",
kernelFunc: bW
};
/**
* @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.
* =============================================================================
*/
class wW {
constructor(t, e, s, o, r) {
this.variableNames = ["x"], this.outputShape = [];
const i = e, a = t[3] - 1;
this.outputShape = t;
let l;
const c = `float(${s}) + float(${o}) * sum`;
r === 0.5 ? l = `inversesqrt(${c})` : r === 1 ? l = `1.0/(${c})` : l = `exp(log(${c}) * float(-${r}));`, 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 = -${i}; j <= ${i}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${a}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${l};
setOutput(val);
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class CW {
constructor(t, e, s, o, r) {
this.variableNames = ["x"], this.outputShape = [], this.packedInputs = !0, this.packedOutput = !0;
const i = e, a = t[3] - 1;
this.outputShape = t;
let l;
const c = `float(${s}) + float(${o}) * sum`;
r === 0.5 ? l = `inversesqrt(${c})` : r === 1 ? l = `1.0/(${c})` : l = `exp(log(${c}) * float(-${r}));`, 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 - ${i};
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 = - ${i}; j <= ${i}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));
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 * ${l};
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const $W = (n) => {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { depthRadius: r, bias: i, alpha: a, beta: l } = s, c = P().getBool("WEBGL_PACK_NORMALIZATION") ? new CW(o.shape, r, i, a, l) : new wW(o.shape, r, i, a, l);
return e.runWebGLProgram(c, [o], o.dtype);
}, IW = {
kernelName: rl,
backendName: "webgl",
kernelFunc: $W
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class kW {
constructor(t, e, s, o, r) {
this.variableNames = ["inputImage", "outputImage", "dy"], this.outputShape = [], this.outputShape = t, this.depth = t[3], this.depthRadius = e, this.bias = s, this.alpha = o, this.beta = r, 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 - ${e})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${e} + 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(${o}) * norm + float(${s});
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(${o})
* float(${r})
* getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${r});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const vW = (n) => {
const { inputs: t, backend: e, attrs: s } = n, { x: o, y: r, dy: i } = t, { depthRadius: a, bias: l, alpha: c, beta: u } = s, h = new kW(o.shape, a, l, c, u);
return e.runWebGLProgram(h, [o, r, i], o.dtype);
}, SW = {
kernelName: Yu,
backendName: "webgl",
kernelFunc: vW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function NW(n, t, e, s) {
const o = G(t), i = G(n.shape) / o, a = tt({ inputs: { x: n }, attrs: { shape: [i, o] }, backend: s }), l = po(a, n.dtype, "max", s), c = tt({ inputs: { x: l }, attrs: { shape: e }, backend: s });
return s.disposeIntermediateTensorInfo(a), s.disposeIntermediateTensorInfo(l), c;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function i1(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { reductionIndices: r, keepDims: i } = s, a = o.shape.length, l = wt(r, o.shape);
let c = l;
const u = jt(c, a), h = u != null, d = e.shouldExecuteOnCPU([o]);
let p = o;
if (h) {
if (d) {
const w = e.texData.get(p.dataId).values, y = new Array(a);
for (let k = 0; k < y.length; k++)
y[k] = o.shape[u[k]];
const C = Yd(w, o.shape, o.dtype, u, y);
p = e.makeTensorInfo(y, o.dtype);
const $ = e.texData.get(p.dataId);
$.values = C;
} else
p = ic(o, u, e);
c = Zt(c.length, a);
}
be("max", c, a);
const [f, m] = pe(p.shape, c);
let g = f;
i && (g = ne(f, l));
let x;
if (d) {
const w = e.texData.get(p.dataId).values, y = OM(w, G(m), g, o.dtype);
x = e.makeTensorInfo(g, o.dtype);
const C = e.texData.get(x.dataId);
C.values = y;
} else
x = NW(p, m, g, e);
return h && e.disposeIntermediateTensorInfo(p), x;
}
const TW = {
kernelName: il,
backendName: "webgl",
kernelFunc: i1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const EW = Jd + `
return max(a, b);
`, RW = `
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);
` + ho + `
return result;
`, DW = ye({
opSnippet: EW,
packedOpSnippet: RW,
cpuKernelImpl: _M
}), AW = {
kernelName: Zr,
backendName: "webgl",
kernelFunc: DW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function FW(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t;
zi(o, "maxPool");
const { filterSize: r, strides: i, pad: a, dimRoundingMode: l } = s, c = 1;
I(Ie(i, c), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);
const u = ln(o.shape, r, i, c, a, l);
if (u.filterWidth === 1 && u.filterHeight === 1 && Et(u.inShape, u.outShape))
return He({ inputs: { x: o }, backend: e });
const h = new Ir(u, "max", !1);
return e.runWebGLProgram(h, [o], o.dtype);
}
const OW = {
kernelName: al,
backendName: "webgl",
kernelFunc: FW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _W(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { filterSize: r, strides: i, pad: a, dataFormat: l, dimRoundingMode: c } = s, u = [1, 1, 1], h = Zn(o.shape, r, i, u, a, c, l), d = new Qd(h, "max", !1);
return e.runWebGLProgram(d, [o], o.dtype);
}
const LW = {
kernelName: ll,
backendName: "webgl",
kernelFunc: _W
};
/**
* @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.
* =============================================================================
*/
class MW {
constructor(t) {
this.variableNames = ["dy", "maxPos"], this.outputShape = t.inShape;
const e = t.strideHeight, s = t.strideWidth, o = t.dilationHeight, r = t.effectiveFilterHeight, i = t.effectiveFilterWidth, a = r - 1 - t.padInfo.top, l = i - 1 - t.padInfo.left, c = r * i - 1;
this.userCode = `
const ivec2 pads = ivec2(${a}, ${l});
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 < ${r};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${e}.0;
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${i}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${c} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${i} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`;
}
}
class PW {
constructor(t) {
this.variableNames = ["dy", "maxPos"], this.outputShape = t.inShape;
const e = t.strideDepth, s = t.strideHeight, o = t.strideWidth, r = t.dilationDepth, i = t.dilationHeight, a = t.dilationWidth, l = t.effectiveFilterDepth, c = t.effectiveFilterHeight, u = t.effectiveFilterWidth, h = l - 1 - t.padInfo.front, d = c - 1 - t.padInfo.top, p = u - 1 - t.padInfo.left, f = l * c * u - 1;
this.userCode = `
const ivec3 pads = ivec3(${h}, ${d}, ${p});
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 < ${l};
wD += ${r}) {
float dyD = float(dyDCorner + wD) / ${e}.0;
if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${c};
wR += ${i}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${u};
wC += ${a}) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${f} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${c} * ${u} +
wR * ${u} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function zW(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, input: r } = t, i = r, { filterSize: a, strides: l, pad: c, dimRoundingMode: u } = s, h = [1, 1, 1], d = Zn(i.shape, a, l, h, c, u), p = new Qd(
d,
"max",
!0
/* get positions */
), f = e.runWebGLProgram(p, [i], i.dtype), m = new PW(d), g = e.runWebGLProgram(m, [o, f], i.dtype);
return e.disposeIntermediateTensorInfo(f), g;
}
const BW = {
kernelName: Zu,
backendName: "webgl",
kernelFunc: zW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function VW(n) {
const { inputs: t, backend: e, attrs: s } = n, { dy: o, input: r, output: i } = t, a = r;
zi([r, i], "maxPoolGrad");
const { filterSize: l, strides: c, pad: u, dimRoundingMode: h } = s, d = ln(a.shape, l, c, 1, u, h), p = !0, f = new Ir(d, "max", p), m = e.runWebGLProgram(f, [a], a.dtype), g = new MW(d), x = e.runWebGLProgram(g, [o, m], a.dtype);
return e.disposeIntermediateTensorInfo(m), x;
}
const WW = {
kernelName: Ju,
backendName: "webgl",
kernelFunc: VW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function UW(n, t, e, s) {
let o = new Ir(e, "max", !1);
const r = s.runWebGLProgram(o, [n], "float32");
o = new Ir(e, "max", !0, !0, t);
const i = s.runWebGLProgram(o, [n], "float32");
return [r, i];
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const GW = {
kernelName: Kf,
backendName: "webgl",
kernelFunc: ({ inputs: n, attrs: t, backend: e }) => {
const { x: s } = n, { filterSize: o, strides: r, pad: i, includeBatchInIndex: a } = t, l = e;
I(s.shape.length === 4, () => `Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);
const c = [1, 1];
I(Ie(r, c), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${c}'`);
const u = ln(s.shape, o, r, c, i), [h, d] = UW(s, a, u, l);
return [h, d];
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function HW(n, t, e, s) {
const o = G(t), i = G(n.shape) / o, a = tt({ inputs: { x: n }, attrs: { shape: [i, o] }, backend: s }), l = po(a, "float32", "mean", s), c = tt({ inputs: { x: l }, attrs: { shape: e }, backend: s });
return s.disposeIntermediateTensorInfo(a), s.disposeIntermediateTensorInfo(l), c;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const KW = {
kernelName: cl,
backendName: "webgl",
kernelFunc: ({ inputs: n, attrs: t, backend: e }) => {
const { x: s } = n, { keepDims: o, axis: r } = t, i = e, a = s.shape.length, l = wt(r, s.shape);
let c = l;
const u = jt(c, a), h = u != null, d = i.shouldExecuteOnCPU([s]), p = [];
let f = s;
if (h) {
if (d) {
const y = i.texData.get(f.dataId).values, C = new Array(a);
for (let v = 0; v < C.length; v++)
C[v] = s.shape[u[v]];
const $ = Yd(y, s.shape, s.dtype, u, C);
f = i.makeTensorInfo(C, s.dtype);
const k = i.texData.get(f.dataId);
k.values = $;
} else
f = ic(s, u, i);
p.push(f), c = Zt(c.length, a);
}
be("sum", c, a);
const [m, g] = pe(f.shape, c);
let x = m;
o && (x = ne(m, l));
const b = HW(f, g, x, i);
for (const w of p)
i.disposeIntermediateTensorInfo(w);
return b;
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function jW(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s, a = o.shape.length, l = wt(r, o.shape);
let c = l;
const u = jt(c, a);
let h = o;
u != null && (h = De({ inputs: { x: o }, backend: e, attrs: { perm: u } }), c = Zt(c.length, o.shape.length)), be("min", c, a);
const [d, p] = pe(h.shape, c), f = G(p), m = tt({ inputs: { x: h }, backend: e, attrs: { shape: [-1, f] } }), g = po(m, m.dtype, "min", e);
let x;
if (i) {
const b = ne(d, l);
x = tt({ inputs: { x: g }, backend: e, attrs: { shape: b } });
} else
x = tt({ inputs: { x: g }, backend: e, attrs: { shape: d } });
return e.disposeIntermediateTensorInfo(m), e.disposeIntermediateTensorInfo(g), u != null && e.disposeIntermediateTensorInfo(h), x;
}
const XW = {
kernelName: ul,
backendName: "webgl",
kernelFunc: jW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const qW = Jd + `
return min(a, b);
`, YW = `
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);
` + ho + `
return result;
`, JW = ye({
opSnippet: qW,
packedOpSnippet: YW,
cpuKernelImpl: LM
}), ZW = {
kernelName: Qr,
backendName: "webgl",
kernelFunc: JW
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class QW {
constructor(t, e, s) {
this.variableNames = ["x"], this.outputShape = e.map(
(u, h) => u[0] + t[h] + u[1]
/* afterPad */
);
const o = t.length, r = Ot(o), i = e.map((u) => u[0]).join(","), a = e.map((u, h) => u[0] + t[h]).join(","), l = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, o), c = s === "reflect" ? 0 : 1;
if (o === 1) {
this.userCode = `
int start = ${i};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${c};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${c};
}
setOutput(getX(outC - start));
}
`;
return;
}
this.userCode = `
${r} start = ${r}(${i});
${r} end = ${r}(${a});
void main() {
${r} outC = getOutputCoords();
for (int i = 0; i < ${o}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${c};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${c};
}
}
${r} coords = outC - start;
setOutput(getX(${l}));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class t4 {
constructor(t, e, s) {
this.variableNames = ["x"], this.packedInputs = !0, this.packedOutput = !0, this.outputShape = e.map(
(f, m) => f[0] + t[m] + f[1]
/* afterPad */
);
const o = t.length, r = Ot(o), i = e.map((f) => f[0]).join(","), a = e.map((f, m) => f[0] + t[m]).join(","), l = Ee("rc", o), c = Ee("source", o), u = `${l[o - 1]} < ${this.outputShape[o - 1]}`, h = o === 1 ? "source" : `vec2(${c.slice(-2).join()})`, d = s === "reflect" ? 0 : 1;
let p = "";
if (o === 1) {
const f = `
${r} source = rc;
if (source < start) {
source = start * 2 - source - ${d};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${d};
}
source -= start;
`;
p = `
${r} rc = outputLoc;
${f}
result[0] = getChannel(getX(${c.join()}), ${h});
${l[o - 1]} += 1;
if(${u}) {
${f}
result[1] = getChannel(getX(${c.join()}), ${h});
}
`;
} else {
const f = `
${r} source = rc;
${r} lt = ${r}(lessThan(source, start));
${r} gte = ${r}(greaterThanEqual(source, end));
${r} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${d}) +
gte * ((end - 1) * 2 - source + ${d});
source -= start;
`;
p = `
${r} rc = outputLoc;
${f}
result[0] = getChannel(getX(${c.join()}), ${h});
${l[o - 1]} += 1;
if(${u}) {
${f}
result[1] = getChannel(getX(${c.join()}), ${h});
}
rc = outputLoc;
${l[o - 2]} += 1;
if(${l[o - 2]} < ${this.outputShape[o - 2]}) {
${f}
result[2] = getChannel(getX(${c.join()}), ${h});
${l[o - 1]} += 1;
if(${u}) {
${f}
result[3] = getChannel(getX(${c.join()}), ${h});
}
}
`;
}
this.userCode = `
const ${r} start = ${r}(${i});
const ${r} end = ${r}(${a});
void main() {
${r} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${p}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const e4 = ({ inputs: n, backend: t, attrs: e }) => {
const { x: s } = n, { paddings: o, mode: r } = e, i = P().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new t4(s.shape, o, r) : new QW(s.shape, o, r);
return t.runWebGLProgram(i, [s], s.dtype);
}, n4 = {
kernelName: hl,
backendName: "webgl",
kernelFunc: e4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const s4 = `if (b == 0.0) return NAN;
return mod(a, b);`, o4 = `
vec4 result = mod(a, b);
bvec4 isNaN = equal(b, vec4(0.0));
` + ho + `
return result;
`, r4 = ye({
opSnippet: s4,
packedOpSnippet: o4
}), i4 = {
kernelName: ti,
backendName: "webgl",
kernelFunc: r4
};
/**
* @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.
* =============================================================================
*/
class a4 {
constructor(t, e, s) {
this.variableNames = ["probs"], this.customUniforms = [{ name: "seed", type: "float" }], this.outputShape = [t, s], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${e - 1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${e - 1}));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const l4 = `
if (a == b) {
return 1.0;
};
return a / b;`, c4 = `
// 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;
`, a1 = ye({ opSnippet: l4, packedOpSnippet: c4, checkOutOfBounds: !0 }), u4 = {
kernelName: Pr,
backendName: "webgl",
kernelFunc: a1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Ef = "return a - b;", l1 = ye({
opSnippet: Ef,
packedOpSnippet: Ef,
supportsComplex: !0,
cpuKernelImpl: sP
}), h4 = {
kernelName: gi,
backendName: "webgl",
kernelFunc: l1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function c1(n) {
const { inputs: t, backend: e, attrs: s } = n, { logits: o } = t, { dim: r } = s, i = wt([r], o.shape), a = i1({
inputs: { x: o },
backend: e,
attrs: { reductionIndices: i, keepDims: !1 }
}), l = ne(a.shape, i), c = tt({ inputs: { x: a }, backend: e, attrs: { shape: l } }), u = l1({ inputs: { a: o, b: c }, backend: e }), h = s1({ inputs: { x: u }, backend: e }), d = ac({ inputs: { x: h }, backend: e, attrs: { axis: i, keepDims: !1 } }), p = tt({ inputs: { x: d }, backend: e, attrs: { shape: l } }), f = a1({ inputs: { a: h, b: p }, backend: e });
return e.disposeIntermediateTensorInfo(a), e.disposeIntermediateTensorInfo(c), e.disposeIntermediateTensorInfo(u), e.disposeIntermediateTensorInfo(h), e.disposeIntermediateTensorInfo(d), e.disposeIntermediateTensorInfo(p), f;
}
const d4 = {
kernelName: El,
backendName: "webgl",
kernelFunc: c1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function p4(n) {
const { inputs: t, backend: e, attrs: s } = n, { logits: o } = t, { numSamples: r, seed: i, normalized: a } = s, l = a ? o : c1({ inputs: { logits: o }, backend: e, attrs: { dim: o.shape.length - 1 } }), c = l.shape[0], u = l.shape[1], h = new a4(c, u, r), d = [[i]], p = e.runWebGLProgram(h, [l], "int32", d);
return a || e.disposeIntermediateTensorInfo(l), p;
}
const f4 = {
kernelName: jf,
backendName: "webgl",
kernelFunc: p4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const m4 = un + `
return -x;
`, g4 = `
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 x4(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
if (e.shouldExecuteOnCPU([s])) {
const r = e.texData.get(s.dataId), [i, a] = PM(r.values, s.shape, s.dtype);
return e.makeTensorInfo(a, s.dtype, i);
}
let o;
return P().getBool("WEBGL_PACK_UNARY_OPERATIONS") ? o = new ls(s.shape, g4) : o = new En(s.shape, m4), e.runWebGLProgram(o, [s], s.dtype);
}
const b4 = {
kernelName: dl,
backendName: "webgl",
kernelFunc: x4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const y4 = zh;
function w4(n) {
je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
const { inputs: t, backend: e, attrs: s } = n, { boxes: o, scores: r } = t, { maxOutputSize: i, iouThreshold: a, scoreThreshold: l } = s, c = e.readSync(o.dataId), u = e.readSync(r.dataId), { selectedIndices: h } = y4(c, u, i, a, l);
return e.makeTensorInfo([h.length], "int32", new Int32Array(h));
}
const C4 = {
kernelName: Qu,
backendName: "webgl",
kernelFunc: w4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const $4 = Bh;
function I4(n) {
je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
const { inputs: t, backend: e, attrs: s } = n, { boxes: o, scores: r } = t, { maxOutputSize: i, iouThreshold: a, scoreThreshold: l, padToMaxOutputSize: c } = s, u = e.readSync(o.dataId), h = e.readSync(r.dataId), { selectedIndices: d, validOutputs: p } = $4(u, h, i, a, l, c);
return [
e.makeTensorInfo([d.length], "int32", new Int32Array(d)),
e.makeTensorInfo([], "int32", new Int32Array([p]))
];
}
const k4 = {
kernelName: th,
backendName: "webgl",
kernelFunc: I4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const v4 = Vh;
function S4(n) {
je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
const { inputs: t, backend: e, attrs: s } = n, { boxes: o, scores: r } = t, { maxOutputSize: i, iouThreshold: a, scoreThreshold: l, softNmsSigma: c } = s, u = e.readSync(o.dataId), h = e.readSync(r.dataId), d = i, p = a, f = l, m = c, { selectedIndices: g, selectedScores: x } = v4(u, h, d, p, f, m);
return [
e.makeTensorInfo([g.length], "int32", new Int32Array(g)),
e.makeTensorInfo([x.length], "float32", new Float32Array(x))
];
}
const N4 = {
kernelName: eh,
backendName: "webgl",
kernelFunc: S4
};
/**
* @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.
* =============================================================================
*/
class T4 {
constructor(t, e, s, o) {
this.variableNames = ["indices"], this.outputShape = [t, e], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${o}), float(${s}),
float(index == coords.y)));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const E4 = (n) => {
const { inputs: t, backend: e, attrs: s } = n, { indices: o } = t, { dtype: r, depth: i, onValue: a, offValue: l } = s, c = G(o.shape), u = new T4(c, i, a, l), h = tt({ inputs: { x: o }, backend: e, attrs: { shape: [c] } }), d = e.runWebGLProgram(u, [h], r);
e.disposeIntermediateTensorInfo(h);
const p = [...o.shape, i], f = tt({ inputs: { x: d }, backend: e, attrs: { shape: p } });
return e.disposeIntermediateTensorInfo(d), f;
}, R4 = {
kernelName: ml,
backendName: "webgl",
kernelFunc: E4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Aa(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
if (s.dtype === "complex64") {
const o = Vi({ inputs: { input: s }, backend: e }), r = Aa({ inputs: { x: o }, backend: e }), i = lc({ inputs: { input: s }, backend: e }), a = Aa({ inputs: { x: i }, backend: e }), l = Ts({ inputs: { real: r, imag: a }, backend: e });
return e.disposeIntermediateTensorInfo(o), e.disposeIntermediateTensorInfo(r), e.disposeIntermediateTensorInfo(i), e.disposeIntermediateTensorInfo(a), l;
} else
return Wi({
attrs: {
shape: s.shape,
dtype: s.dtype,
value: s.dtype === "string" ? "" : 0
},
backend: e
});
}
const D4 = {
kernelName: Al,
backendName: "webgl",
kernelFunc: Aa
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function u1(n) {
const { inputs: t, backend: e } = n, { x: s } = t;
if (s.dtype === "string")
throw new Error("onesLike is not supported under string dtype");
if (s.dtype === "complex64") {
const o = Vi({ inputs: { input: s }, backend: e }), r = u1({ inputs: { x: o }, backend: e }), i = lc({ inputs: { input: s }, backend: e }), a = Aa({ inputs: { x: i }, backend: e }), l = Ts({ inputs: { real: r, imag: a }, backend: e });
return e.disposeIntermediateTensorInfo(o), e.disposeIntermediateTensorInfo(r), e.disposeIntermediateTensorInfo(i), e.disposeIntermediateTensorInfo(a), l;
} else
return Wi({ attrs: { shape: s.shape, dtype: s.dtype, value: 1 }, backend: e });
}
const A4 = {
kernelName: fl,
backendName: "webgl",
kernelFunc: u1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function F4(n) {
const { inputs: t, backend: e, attrs: s } = n, { axis: o } = s;
if (t.length === 1)
return du({ inputs: { input: t[0] }, backend: e, attrs: { dim: o } });
const r = t[0].shape, i = t[0].dtype;
t.forEach((u) => {
$u(r, u.shape, "All tensors passed to stack must have matching shapes"), I(i === u.dtype, () => "All tensors passed to stack must have matching dtypes");
});
const a = [], l = t.map((u) => {
const h = du({ inputs: { input: u }, backend: e, attrs: { dim: o } });
return a.push(h), h;
}), c = qy({ inputs: l, backend: e, attrs: { axis: o } });
return a.forEach((u) => e.disposeIntermediateTensorInfo(u)), c;
}
const O4 = {
kernelName: gl,
backendName: "webgl",
kernelFunc: F4
};
/**
* @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.
* =============================================================================
*/
class _4 {
constructor(t, e, s) {
this.variableNames = ["x"], this.customUniforms = [{ name: "value", type: "float" }], this.outputShape = e.map(
(c, u) => c[0] + t[u] + c[1]
/* afterPad */
);
const o = t.length, r = Ot(o), i = e.map((c) => c[0]).join(","), a = e.map((c, u) => c[0] + t[u]).join(","), l = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, o);
if (o === 1) {
this.userCode = `
int start = ${i};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;
return;
}
this.userCode = `
${r} start = ${r}(${i});
${r} end = ${r}(${a});
void main() {
${r} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${r} coords = outC - start;
setOutput(getX(${l}));
}
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class L4 {
constructor(t, e, s) {
this.variableNames = ["x"], this.packedInputs = !0, this.packedOutput = !0, this.customUniforms = [{ name: "value", type: "float" }], this.outputShape = e.map(
(m, g) => m[0] + t[g] + m[1]
/* afterPad */
);
const o = t.length, r = Ot(o), i = e.map((m) => m[0]).join(","), a = e.map((m, g) => m[0] + t[g]).join(","), l = Ee("rc", o), c = Ee("source", o), u = `${l[o - 1]} < ${this.outputShape[o - 1]}`, h = o === 1 ? "source" : `vec2(${c.slice(-2).join()})`, d = [
`${r} rc = outputLoc;`,
`${l[o - 1]} += 1;
if(${u}) {
`,
o === 1 ? "" : `}
rc = outputLoc;
${l[o - 2]} += 1;
if(${l[o - 2]} < ${this.outputShape[o - 2]}) {`,
o === 1 ? "" : ` ${l[o - 1]} += 1;
if(${u}) {`
], p = o === 1 ? "rc < start || rc >= end" : "any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";
let f = "";
for (let m = 0, g = o === 1 ? 2 : 4; m < g; m++)
f += `
${d[m]}
if (${p}) {
result[${m}] = float(value);
} else {
${r} source = rc - start;
result[${m}] = getChannel(getX(${c.join()}), ${h});
}
`;
f += o === 1 ? "} " : "}}", this.userCode = `
const ${r} start = ${r}(${i});
const ${r} end = ${r}(${a});
void main() {
${r} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${f}
setOutput(result);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const h1 = (n) => {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { paddings: r, constantValue: i } = s;
if (G(o.shape) === 0) {
const c = r.map(
(u, h) => u[0] + o.shape[h] + u[1]
/* afterPad */
);
return Wi({
backend: e,
attrs: { shape: c, value: i, dtype: o.dtype }
});
}
const a = P().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new L4(o.shape, r, i) : new _4(o.shape, r, i), l = [[i]];
return e.runWebGLProgram(a, [o], o.dtype, l);
}, M4 = {
kernelName: xl,
backendName: "webgl",
kernelFunc: h1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const P4 = `
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);
`, z4 = `
// 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);
` + ho + `
return result;
`, B4 = ye({ opSnippet: P4, packedOpSnippet: z4 }), V4 = {
kernelName: ni,
backendName: "webgl",
kernelFunc: B4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function W4(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { axis: r, keepDims: i } = s, a = o.shape.length, l = [], c = wt(r, o.shape);
let u = c;
const h = jt(u, a);
let d = o;
h != null && (d = De({ inputs: { x: o }, backend: e, attrs: { perm: h } }), u = Zt(u.length, a), l.push(d)), be("prod", u, a);
let p;
if (e.shouldExecuteOnCPU([d])) {
const f = e.texData.get(d.dataId).values, { outVals: m, outShape: g, outDtype: x } = BM(d.shape, d.dtype, f, u);
p = e.makeTensorInfo(g, x, m);
} else {
const [f, m] = pe(d.shape, u), g = G(m), x = tt({ inputs: { x: d }, backend: e, attrs: { shape: [-1, g] } }), b = ph(o.dtype), w = po(x, b, "prod", e);
p = tt({ inputs: { x: w }, backend: e, attrs: { shape: f } }), l.push(x), l.push(w);
}
if (i) {
l.push(p);
const f = ne(p.shape, c);
p = tt({ inputs: { x: p }, backend: e, attrs: { shape: f } });
}
return l.forEach((f) => e.disposeIntermediateTensorInfo(f)), p;
}
const U4 = {
kernelName: yl,
backendName: "webgl",
kernelFunc: W4
};
/**
* @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.
* =============================================================================
*/
function G4(n) {
const { inputs: t, backend: e, attrs: s } = n, { paramsNestedSplits: o, paramsDenseValues: r, indices: i } = t, { outputRaggedRank: a } = s, l = o.map((x) => e.readSync(x.dataId)), c = o.map((x) => x.shape), u = e.readSync(r.dataId), h = e.readSync(i.dataId), [d, p, f] = VM(l, c, u, r.shape, r.dtype, h, i.shape, a), m = d.map((x) => e.makeTensorInfo([x.length], "int32", x)), g = e.makeTensorInfo(f, r.dtype, p);
return m.concat([g]);
}
const H4 = {
kernelName: Xf,
backendName: "webgl",
kernelFunc: G4
};
/**
* @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.
* =============================================================================
*/
function K4(n) {
const { inputs: t, backend: e } = n, { starts: s, limits: o, deltas: r } = t, i = e.readSync(s.dataId), a = e.readSync(o.dataId), l = e.readSync(r.dataId), [c, u] = WM(i, s.shape, s.dtype, a, o.shape, l, r.shape), h = e.makeTensorInfo([c.length], "int32", c), d = e.makeTensorInfo([u.length], s.dtype, u);
return [h, d];
}
const j4 = {
kernelName: qf,
backendName: "webgl",
kernelFunc: K4
};
/**
* @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.
* =============================================================================
*/
function X4(n) {
const { inputs: t, backend: e, attrs: s } = n, { shape: o, values: r, defaultValue: i, rowPartitionTensors: a } = t, { rowPartitionTypes: l } = s, c = e.readSync(o.dataId), u = e.readSync(r.dataId), h = e.readSync(i.dataId), d = a.map((g) => e.readSync(g.dataId)), p = a.map((g) => g.shape), [f, m] = UM(c, o.shape, u, r.shape, r.dtype, h, i.shape, d, p, l);
return e.makeTensorInfo(f, r.dtype, m);
}
const q4 = {
kernelName: Yf,
backendName: "webgl",
kernelFunc: X4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const d1 = (n) => {
const { backend: t, attrs: e } = n, { start: s, stop: o, step: r, dtype: i } = e, a = GM(s, o, r, i);
return t.makeTensorInfo([a.length], i, a);
}, Y4 = {
kernelName: nh,
backendName: "webgl",
kernelFunc: d1
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const J4 = "return 1.0 / x;", Z4 = vt({ opSnippet: J4 }), Q4 = {
kernelName: si,
backendName: "webgl",
kernelFunc: Z4
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const tU = un + `
return (x < 0.0) ? 0.0 : x;
`, eU = `
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;
`, nU = vt({ opSnippet: tU, packedOpSnippet: eU }), sU = {
kernelName: oi,
backendName: "webgl",
kernelFunc: nU
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const oU = un + `
return (x < 0.0) ? 0.0 : min(6.0, x);
`, rU = `
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;
`, iU = vt({ opSnippet: oU, packedOpSnippet: rU }), aU = {
kernelName: ri,
backendName: "webgl",
kernelFunc: iU
};
/**
* @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.
* =============================================================================
*/
class lU {
constructor(t, e, s, o, r) {
this.variableNames = ["A"], this.outputShape = [];
const [i, a, l, c] = t;
this.outputShape = [i, e, s, c];
const u = [
o && e > 1 ? a - 1 : a,
o && s > 1 ? l - 1 : l
], h = [
o && e > 1 ? e - 1 : e,
o && s > 1 ? s - 1 : s
];
let d;
r ? d = "(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)" : d = "vec2(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0] / h[0]},
${u[1] / h[1]});
const vec2 inputShapeRC = vec2(${a}.0, ${l}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${d};
// 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);
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class cU {
constructor(t, e, s, o, r) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0, this.outputShape = [];
const [i, a, l, c] = t;
this.outputShape = [i, e, s, c];
const u = [
o && e > 1 ? a - 1 : a,
o && s > 1 ? l - 1 : l
], h = [
o && e > 1 ? e - 1 : e,
o && s > 1 ? s - 1 : s
];
let d;
r ? d = "(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)" : d = "vec3(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec3 effectiveInputOverOutputRatioRC = vec3(
${u[0] / h[0]},
${u[1] / h[1]},
${u[1] / h[1]});
const vec3 inputShapeRC = vec3(${a}.0, ${l}.0,
${l}.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 = ${d};
// 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 < ${c - 1};
bool hasNextRow = coords.z < ${s - 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);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function uU(n) {
const { inputs: t, backend: e, attrs: s } = n, { images: o } = t, { alignCorners: r, halfPixelCenters: i, size: a } = s, [l, c] = a, u = P().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new cU(o.shape, l, c, r, i) : new lU(o.shape, l, c, r, i);
return e.runWebGLProgram(u, [o], "float32");
}
const hU = {
kernelName: $l,
backendName: "webgl",
kernelFunc: uU
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class dU {
constructor(t, e, s) {
this.variableNames = ["dy"], this.outputShape = [], this.outputShape = e;
const [, o, r] = e, [, i, a] = t, l = [
s && i > 1 ? o - 1 : o,
s && a > 1 ? r - 1 : r
], c = [
s && i > 1 ? i - 1 : i,
s && a > 1 ? a - 1 : a
], u = l[0] / c[0], h = l[1] / c[1], d = 1 / u, p = 1 / h, f = Math.ceil(d) * 2 + 2, m = Math.ceil(p) * 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(${u});
const float widthScale = float(${h});
const float invHeightScale = float(${d});
const float invWidthScale = float(${p});
const int winHeight = int(${f});
const int winWidth = int(${m});
// 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 >= ${i}) {
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 >= ${a}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${o - 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), ${r - 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);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function pU(n) {
const { inputs: t, backend: e, attrs: s } = n, { images: o, dy: r } = t, { alignCorners: i } = s, a = new dU(r.shape, o.shape, i);
return e.runWebGLProgram(a, [r], r.dtype);
}
const fU = {
kernelName: rh,
backendName: "webgl",
kernelFunc: pU
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class mU {
constructor(t, e, s, o, r) {
this.variableNames = ["A"], this.outputShape = [];
const [i, a, l, c] = t;
this.outputShape = [i, e, s, c];
const u = [
o && e > 1 ? a - 1 : a,
o && s > 1 ? l - 1 : l
], h = [
o && e > 1 ? e - 1 : e,
o && s > 1 ? s - 1 : s
], d = o ? "0.5" : "0.0";
let p;
r ? p = "max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))" : p = "vec2(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0] / h[0]},
${u[1] / h[1]});
const vec2 inputShapeRC = vec2(${a}.0, ${l}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${p};
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class gU {
constructor(t, e, s, o, r) {
this.variableNames = ["A"], this.packedInputs = !0, this.packedOutput = !0, this.outputShape = [];
const [i, a, l, c] = t;
this.outputShape = [i, e, s, c];
const u = [
o && e > 1 ? a - 1 : a,
o && s > 1 ? l - 1 : l
], h = [
o && e > 1 ? e - 1 : e,
o && s > 1 ? s - 1 : s
], d = o ? "0.5" : "0.0";
let p;
r ? p = "max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))" : p = "vec3(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec3 effectiveInputOverOutputRatioRC = vec3(
${u[0] / h[0]},
${u[1] / h[1]},
${u[1] / h[1]});
const vec3 inputShapeRC = vec3(${a}.0, ${l}.0,
${l}.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 = ${p};
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${c - 1};
bool hasNextRow = coords.z < ${s - 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);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function xU(n) {
const { inputs: t, backend: e, attrs: s } = n, { images: o } = t, { alignCorners: r, halfPixelCenters: i, size: a } = s, [l, c] = a, u = P().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new gU(o.shape, l, c, r, i) : new mU(o.shape, l, c, r, i);
return e.runWebGLProgram(u, [o], o.dtype);
}
const bU = {
kernelName: Cl,
backendName: "webgl",
kernelFunc: xU
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class yU {
constructor(t, e, s) {
this.variableNames = ["dy"], this.outputShape = [], this.outputShape = e;
const [, o, r] = e, [, i, a] = t, l = [
s && i > 1 ? o - 1 : o,
s && a > 1 ? r - 1 : r
], c = [
s && i > 1 ? i - 1 : i,
s && a > 1 ? a - 1 : a
], u = l[0] / c[0], h = l[1] / c[1], d = 1 / u, p = 1 / h, f = Math.ceil(d) * 2 + 2, m = Math.ceil(p) * 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(${u});
const float widthScale = float(${h});
const float invHeightScale = float(${d});
const float invWidthScale = float(${p});
const int winHeight = int(${f});
const int winWidth = int(${m});
// 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 >= ${i}) {
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 >= ${a}) {
continue;
}
float sourceFracRow =
float(${l[0]}) *
(float(dyR) / float(${c[0]}));
float sourceFracCol =
float(${l[1]}) *
(float(dyC) / float(${c[1]}));
int sourceNearestRow = int(min(
float(int(${o}) - 1),
${s} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${r}) - 1),
${s} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function wU(n) {
const { inputs: t, backend: e, attrs: s } = n, { images: o, dy: r } = t, { alignCorners: i } = s, a = new yU(r.shape, o.shape, i);
return e.runWebGLProgram(a, [r], r.dtype);
}
const CU = {
kernelName: oh,
backendName: "webgl",
kernelFunc: wU
};
/**
* @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.
* =============================================================================
*/
class $U {
constructor(t, e) {
this.variableNames = ["x"];
const s = t.length;
if (s > 4)
throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);
if (this.outputShape = t, s === 1) {
this.userCode = `
void main() {
int coord = getOutputCoords();
setOutput(getX(${t[0]} - coord - 1));
}
`;
return;
}
const o = (a) => e.indexOf(a) !== -1 && t[a] !== 1 ? `${t[a]} - coords[${a}] - 1` : `coords[${a}]`, r = t.map((a, l) => o(l)).join(","), i = Ot(s);
this.userCode = `
void main() {
${i} coords = getOutputCoords();
setOutput(getX(${r}));
}
`;
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class IU {
constructor(t, e) {
this.variableNames = ["x"], this.packedInputs = !0, this.packedOutput = !0;
const s = t.length;
if (s > 4)
throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);
this.outputShape = t;
const o = Ee("rc", s), r = `${o[s - 1]} + 1 < ${this.outputShape[s - 1]}`, i = `${o[s - 2]} + 1 < ${this.outputShape[s - 2]}`, a = Ot(s);
s === 1 ? this.userCode = `
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${t[0]} - rc - 1),
${t[0]} - rc - 1);
if(${r}){
result.g = getChannel(getX(${t[0]} - (rc + 1) - 1),
${t[0]} - (rc + 1) - 1);
}
setOutput(result);
}
` : this.userCode = `
void main() {
${a} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${l(o.slice())};
if(${r}){
result.g = ${c(o.slice())};
}
if(${i}) {
result.b = ${u(o.slice())};
if(${r}) {
result.a = ${h(o.slice())};
}
}
setOutput(result);
}
`;
function l(f) {
return d(f);
}
function c(f) {
return f[s - 1] = "(" + f[s - 1] + " + 1)", d(f);
}
function u(f) {
return f[s - 2] = "(" + f[s - 2] + " + 1)", d(f);
}
function h(f) {
return f[s - 1] = "(" + f[s - 1] + " + 1)", f[s - 2] = "(" + f[s - 2] + " + 1)", d(f);
}
function d(f) {
const m = t.map((b, w) => p(w, f)), g = m.join(","), x = m.slice(-2).join(",");
return `getChannel(getX(${g}), vec2(${x}))`;
}
function p(f, m) {
return e.indexOf(f) !== -1 && t[f] !== 1 ? `${t[f]} - ${m[f]} - 1` : `${m[f]}`;
}
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function kU(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { dims: r } = s, i = o.shape.length, a = wt(r, o.shape);
if (i === 0)
return He({ inputs: { x: o }, backend: e });
const l = P().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new IU(o.shape, a) : new $U(o.shape, a);
return e.runWebGLProgram(l, [o], o.dtype);
}
const vU = {
kernelName: Il,
backendName: "webgl",
kernelFunc: kU
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class SU {
constructor(t, e) {
this.variableNames = ["Image"], this.outputShape = [], this.customUniforms = [{ name: "params", type: "vec4" }];
const s = t[1], o = t[2];
this.outputShape = t;
let r = "";
typeof e == "number" ? r = `float outputValue = ${e.toFixed(2)};` : r = `
vec3 fill = vec3(${e.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]));
${r}
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${s}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const NU = {
kernelName: dh,
backendName: "webgl",
kernelFunc: ({ inputs: n, attrs: t, backend: e }) => {
const { image: s } = n, { radians: o, fillValue: r, center: i } = t, a = e, l = new SU(s.shape, r), [c, u] = Zh(i, s.shape[1], s.shape[2]), h = [[c, u, Math.sin(o), Math.cos(o)]];
return a.runWebGLProgram(l, [s], s.dtype, h);
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const TU = `
// 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;
}
}
`, EU = vt({ opSnippet: TU }), RU = {
kernelName: ii,
backendName: "webgl",
kernelFunc: EU
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const DU = "return inversesqrt(x);", AU = vt({ opSnippet: DU, cpuKernelImpl: HM }), FU = {
kernelName: ai,
backendName: "webgl",
kernelFunc: AU
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class tp {
constructor(t, e, s, o, r, i, a = !0, l = !1) {
this.variableNames = ["updates", "indices", "defaultValue"], this.outputShape = i;
const c = Ot(r.length), u = Ot(i.length);
let h = "";
s === 1 ? h = "i" : s === 2 && (h = "i, j");
const d = `getIndices(${h})`;
let p = "";
o === 1 ? p = "i" : o === 2 && (p = "i, coords[1]");
const f = `getUpdates(${p})`;
let m = "";
l && (m = "coords[0], coords[1]");
const g = `getDefaultValue(${m})`, x = e > 1 ? "strides[j]" : "strides";
this.userCode = `
${c} strides = ${c}(${r});
void main() {
${u} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${t}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${e}; j++) {
int index = round(${d});
flattenedIndex += index * ${x};
}
if (flattenedIndex == coords[0]) {
sum += ${f};
found = true;
}
}
setOutput(mix(${g}, sum, float(found)));
}
`;
}
}
/**
* @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.
* =============================================================================
*/
class OU {
constructor(t, e, s, o, r, i, a = !0, l = !1) {
this.variableNames = ["updates", "indices", "defaultValue"], this.packedInputs = !0, this.packedOutput = !0, this.outputShape = i;
const c = Ot(r.length), u = Ot(i.length);
let h = "";
s === 1 ? h = "i" : s === 2 && (h = "i, j");
const d = `getIndices(${h})`;
let p = "";
o === 1 ? p = "i" : o === 2 && (p = "i, coords[1]");
const f = `getUpdates(${p})`;
let m = "";
l && (m = "coords[0], coords[1]");
const g = `getDefaultValue(${m})`, x = e > 1 ? "strides[j]" : "strides", b = e > 1 ? "strides[j + 1]" : "strides";
this.userCode = `
${c} strides = ${c}(${r});
void main() {
${u} coords = getOutputCoords();
vec4 sum = vec4(0.);
vec4 found = vec4(0.);
for (int i = 0; i < ${t}; i+=2) {
ivec2 flattenedIndex = ivec2(0);
for (int j = 0; j < ${e}; j+=2) {
ivec4 index = round(${d});
flattenedIndex += index.xz * ${x};
if (j + 1 < ${e}) {
flattenedIndex += index.yw * ${b};
}
}
if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
vec4 updVals = ${f};
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(${g}, sum, found));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _U(n) {
const { inputs: t, backend: e, attrs: s } = n, { indices: o, updates: r } = t, { shape: i } = s, { sliceRank: a, numUpdates: l, sliceSize: c, strides: u, outputSize: h } = io(r, o, i), d = [h / c, c];
if (h === 0)
return e.makeTensorInfo(i, o.dtype);
const p = tt({ inputs: { x: o }, backend: e, attrs: { shape: [l, a] } }), f = tt({ inputs: { x: r }, backend: e, attrs: { shape: [l, c] } }), m = e.makeTensorInfo([], "float32", new Float32Array([0]));
let g;
P().getBool("WEBGL_PACK") ? g = new OU(l, a, p.shape.length, f.shape.length, u, d) : g = new tp(l, a, p.shape.length, f.shape.length, u, d);
const x = e.runWebGLProgram(g, [f, p, m], f.dtype), b = tt({ inputs: { x }, backend: e, attrs: { shape: i } });
return e.disposeIntermediateTensorInfo(p), e.disposeIntermediateTensorInfo(f), e.disposeIntermediateTensorInfo(x), e.disposeIntermediateTensorInfo(m), b;
}
const LU = {
kernelName: Jf,
backendName: "webgl",
kernelFunc: _U
};
/**
* @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.
* =============================================================================
*/
class MU {
constructor(t, e, s, o) {
this.variableNames = ["sortedSequence", "values"], this.customUniforms = [{ name: "numInputs", type: "int" }], this.outputShape = [t, s];
const r = "while (left < right) {", i = `for (int i = 0; i < ${Math.ceil(Math.log2(e + 1))}; ++i) { if (left >= right) break;`, a = P().getNumber("WEBGL_VERSION") === 2 ? r : i, l = o === "left" ? "<" : "<=";
this.userCode = `
int findBound(int batch, float value) {
int left = 0;
int right = numInputs;
int mid;
${a}
mid = (left + right) / 2;
if (getSortedSequence(batch, mid) ${l} 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)));
}
`;
}
}
/**
* @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.
* =============================================================================
*/
function PU(n) {
const { inputs: t, backend: e, attrs: s } = n, { sortedSequence: o, values: r } = t, { side: i } = s, a = new MU(o.shape[0], o.shape[1], r.shape[1], i), l = [[o.shape[1]]];
return e.runWebGLProgram(a, [o, r], "int32", l);
}
const zU = {
kernelName: Qf,
backendName: "webgl",
kernelFunc: PU
};
/**
* @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.
* =============================================================================
*/
class BU {
constructor(t, e, s) {
this.variableNames = ["c", "a", "b"], this.outputShape = e;
let o, r;
if (s > 4)
throw Error(`Where for rank ${s} is not yet supported`);
if (s === 1)
r = "resRC", o = "resRC";
else {
const a = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], l = [], c = [];
for (let u = 0; u < e.length; u++)
c.push(`${a[u]}`), u < t && l.push(`${a[u]}`);
o = l.join(), r = c.join();
}
const i = Ot(s);
this.userCode = `
void main() {
${i} resRC = getOutputCoords();
float cVal = getC(${o});
if (cVal >= 1.0) {
setOutput(getA(${r}));
} else {
setOutput(getB(${r}));
}
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function VU(n) {
const { inputs: t, backend: e } = n, { condition: s, t: o, e: r } = t, i = new BU(s.shape.length, o.shape, o.shape.length);
return e.runWebGLProgram(i, [s, o, r], Ue(o.dtype, r.dtype));
}
const WU = {
kernelName: kl,
backendName: "webgl",
kernelFunc: VU
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const UU = `
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${Gl};
float scale = ${Hl};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`, GU = vt({ opSnippet: UU }), HU = {
kernelName: li,
backendName: "webgl",
kernelFunc: GU
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const KU = Jo + `
return 1.0 / (1.0 + exp(-1.0 * x));
`, jU = `
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;
`, XU = vt({
opSnippet: KU,
packedOpSnippet: jU,
cpuKernelImpl: jM
}), qU = {
kernelName: di,
backendName: "webgl",
kernelFunc: XU
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const YU = `
if (isnan(x)) { return 0.0; }
return sign(x);
`, JU = vt({ opSnippet: YU }), ZU = {
kernelName: hi,
backendName: "webgl",
kernelFunc: JU
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const QU = Jo + `
return sin(x);
`, tG = `
vec4 result = sin(x);
bvec4 isNaN = isnan(x);
${ho}
return result;
`, eG = vt({ opSnippet: QU, packedOpSnippet: tG }), nG = {
kernelName: ci,
backendName: "webgl",
kernelFunc: eG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sG = `
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`, oG = vt({ opSnippet: sG }), rG = {
kernelName: ui,
backendName: "webgl",
kernelFunc: oG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const iG = `
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;
`, aG = vt({ opSnippet: iG }), lG = {
kernelName: pi,
backendName: "webgl",
kernelFunc: aG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const cG = (n) => {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { blockShape: r, paddings: i } = s;
I(o.shape.length <= 4, () => "spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");
const a = r.reduce((x, b) => x * b), l = [[0, 0]];
l.push(...i);
for (let x = 1 + r.length; x < o.shape.length; ++x)
l.push([0, 0]);
const c = [], u = h1({
inputs: { x: o },
backend: e,
attrs: { paddings: l, constantValue: 0 }
}), h = Si(u.shape, r, a, !1), d = Ni(h.length, r.length, !1), p = Ti(u.shape, r, a, !1), f = tt({ inputs: { x: u }, backend: e, attrs: { shape: h } }), m = De({
inputs: { x: f },
backend: e,
attrs: { perm: d }
}), g = tt({ inputs: { x: m }, backend: e, attrs: { shape: p } });
return c.push(u), c.push(f), c.push(m), c.forEach((x) => e.disposeIntermediateTensorInfo(x)), g;
}, uG = {
kernelName: Nl,
backendName: "webgl",
kernelFunc: cG
};
/**
* @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.
* =============================================================================
*/
function hG(n) {
const { inputs: t, backend: e } = n, { indices: s, values: o, denseShape: r, defaultValue: i } = t;
if (r.shape.length !== 1)
throw new Error(`Dense shape must be a vector, saw:
${r.shape}`);
if (s.shape.length !== 2)
throw new Error(`Indices must be a matrix, saw:
${s.shape}`);
if (o.shape.length !== 1)
throw new Error(`Values must be a vector, saw:
${o.shape}`);
if (i.shape.length !== 0)
throw new Error(`Default value must be a scalar, saw:
${i.shape}`);
const a = e.readSync(s.dataId), l = e.readSync(o.dataId), c = e.readSync(r.dataId), u = e.readSync(i.dataId)[0], [h, d, p, f, m] = qM(a, s.shape, s.dtype, l, o.dtype, c, u);
return [
e.makeTensorInfo(d, s.dtype, h),
e.makeTensorInfo([d[0]], o.dtype, p),
e.makeTensorInfo([f.length], "bool", new Uint8Array(f.map((g) => Number(g)))),
e.makeTensorInfo([m.length], s.dtype, new Int32Array(m))
];
}
const dG = {
kernelName: tm,
backendName: "webgl",
kernelFunc: hG
};
/**
* @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.
* =============================================================================
*/
function pG(n) {
const { inputs: t, backend: e } = n, { inputIndices: s, inputShape: o, newShape: r } = t;
if (s.shape.length !== 2)
throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);
if (o.shape.length !== 1)
throw new Error(`Input shape should be a vector but received shape ${o.shape}`);
if (r.shape.length !== 1)
throw new Error(`Target shape should be a vector but received shape ${r.shape}`);
const i = Array.from(e.readSync(o.dataId)), a = e.readSync(s.dataId), l = Array.from(e.readSync(r.dataId)), [c, u, h] = YM(a, s.shape, s.dtype, i, l);
return [
e.makeTensorInfo(u, s.dtype, c),
e.makeTensorInfo([h.length], r.dtype, new Int32Array(h))
];
}
const fG = {
kernelName: em,
backendName: "webgl",
kernelFunc: pG
};
/**
* @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.
* =============================================================================
*/
function mG(n) {
const { inputs: t, backend: e } = n, { data: s, indices: o, segmentIds: r } = t;
if (s.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${o.shape}`);
if (r.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${r.shape}`);
const i = e.readSync(s.dataId), a = e.readSync(o.dataId), l = e.readSync(r.dataId), [c, u] = Ly(i, s.shape, s.dtype, a, l, !0);
return e.makeTensorInfo(u, s.dtype, c);
}
const gG = {
kernelName: nm,
backendName: "webgl",
kernelFunc: mG
};
/**
* @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.
* =============================================================================
*/
function xG(n) {
const { inputs: t, backend: e } = n, { data: s, indices: o, segmentIds: r } = t;
if (s.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${o.shape}`);
if (r.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${r.shape}`);
const i = e.readSync(s.dataId), a = e.readSync(o.dataId), l = e.readSync(r.dataId), [c, u] = Ly(i, s.shape, s.dtype, a, l);
return e.makeTensorInfo(u, s.dtype, c);
}
const bG = {
kernelName: sm,
backendName: "webgl",
kernelFunc: xG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function yG(n) {
const { inputs: t, backend: e, attrs: s } = n, { sparseIndices: o, sparseValues: r, defaultValue: i } = t, { outputShape: a } = s, { sliceRank: l, numUpdates: c, sliceSize: u, strides: h, outputSize: d } = io(r, o, a), p = !1;
if (r.dtype === "string") {
const x = e.bufferSync(o), b = e.bufferSync(r), w = ps(e.readSync(i.dataId)[0]), y = KM(x, b, a, d, u, c, l, h, w, p);
return e.makeTensorInfo(a, y.dtype, y.values);
}
const f = new tp(c, l, o.shape.length, r.shape.length, h, [d, 1], p), m = e.runWebGLProgram(f, [r, o, i], r.dtype), g = tt({ inputs: { x: m }, backend: e, attrs: { shape: a } });
return e.disposeIntermediateTensorInfo(m), g;
}
const wG = {
kernelName: om,
backendName: "webgl",
kernelFunc: yG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function CG(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { numOrSizeSplits: r, axis: i } = s, a = wt(i, o.shape)[0], l = pd(o, r, a), c = o.shape.length, u = new Array(c).fill(0), h = o.shape.slice();
return l.map((d) => {
const p = [...h];
p[a] = d;
const f = Zo({ inputs: { x: o }, backend: e, attrs: { begin: u, size: p } });
return u[a] += d, f;
});
}
const $G = {
kernelName: Tl,
backendName: "webgl",
kernelFunc: CG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Rf = "return sqrt(x);", IG = vt({ opSnippet: Rf, packedOpSnippet: Rf, cpuKernelImpl: JM }), kG = {
kernelName: fi,
backendName: "webgl",
kernelFunc: IG
};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const vG = "return x * x;", SG = vt({ opSnippet: vG }), NG = {
kernelName: ih,
backendName: "webgl",
kernelFunc: SG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const Df = "return (a - b) * (a - b);", TG = ye({ opSnippet: Df, packedOpSnippet: Df }), EG = {
kernelName: mi,
backendName: "webgl",
kernelFunc: TG
};
/**
* @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.
* =============================================================================
*/
function RG(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t;
if (o.dtype !== "string")
throw new Error("Input must be of datatype string");
const r = e.readSync(o.dataId), i = Yn(r), a = ZM(i, "string", s);
return e.makeTensorInfo(o.shape, "string", a);
}
const DG = {
kernelName: ah,
backendName: "webgl",
kernelFunc: RG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function AG({ inputs: n, attrs: t, backend: e }) {
const { x: s } = n, o = un + `
return x > 0.0 ? 1.0 : float(${t.alpha});
`, r = new En(s.shape, o);
return e.runWebGLProgram(r, [s], s.dtype);
}
const FG = {
kernelName: wi,
backendName: "webgl",
kernelFunc: AG
};
/**
* @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.
* =============================================================================
*/
class OG {
constructor(t, e, s) {
this.variableNames = ["x"], this.outputShape = s;
const o = s.length, r = Ot(s.length), i = Ot(s.length);
let a = "";
if (o === 1)
a = "coords * strides + begin";
else {
let l = 0;
a = s.map((c, u) => (l++, s.length === 1 ? `coords * strides[${u}] + begin[${u}]` : `coords[${l - 1}] * strides[${u}] + begin[${u}]`)).join(",");
}
this.userCode = `
${r} begin = ${r}(${t});
${r} strides = ${r}(${e});
void main() {
${i} coords = getOutputCoords();
setOutput(getX(${a}));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function _G(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { begin: r, end: i, strides: a, beginMask: l, endMask: c, ellipsisMask: u, newAxisMask: h, shrinkAxisMask: d } = s, { finalShapeSparse: p, finalShape: f, isIdentity: m, sliceDim0: g, isSimpleSlice: x, begin: b, end: w, strides: y } = qh(o.shape, r, i, a, l, c, u, h, d);
let C;
if (m)
C = tt({ inputs: { x: o }, backend: e, attrs: { shape: f } });
else if (g || x) {
I(o.shape.length >= 1, () => `Input must have rank at least 1, got: ${o.shape.length}`);
const k = Kh(b, w, y), v = Zo({ inputs: { x: o }, backend: e, attrs: { begin: b, size: k } });
C = tt({ inputs: { x: v }, backend: e, attrs: { shape: f } }), e.disposeIntermediateTensorInfo(v);
} else if (e.shouldExecuteOnCPU([o])) {
const v = e.readSync(o.dataId), S = yt(o.shape, o.dtype, v), T = QM(p, S, y, b);
C = e.makeTensorInfo(f, o.dtype, T.values);
} else {
const v = new OG(b, y, p);
C = e.runWebGLProgram(v, [o], o.dtype);
}
const $ = tt({ inputs: { x: C }, backend: e, attrs: { shape: f } });
return e.disposeIntermediateTensorInfo(C), $;
}
const LG = {
kernelName: lh,
backendName: "webgl",
kernelFunc: _G
};
/**
* @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.
* =============================================================================
*/
function MG(n) {
const { inputs: t, backend: e, attrs: s } = n, { separator: o, nGramWidths: r, leftPad: i, rightPad: a, padWidth: l, preserveShortSequences: c } = s, { data: u, dataSplits: h } = t, d = e.readSync(u.dataId), p = e.readSync(h.dataId), [f, m] = tP(d, p, o, r, i, a, l, c);
return [
e.makeTensorInfo([f.length], "string", f),
e.makeTensorInfo(h.shape, "int32", m)
];
}
const PG = {
kernelName: rm,
backendName: "webgl",
kernelFunc: MG
};
/**
* @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.
* =============================================================================
*/
function zG(n) {
const { inputs: t, backend: e, attrs: s } = n, { skipEmpty: o } = s, { input: r, delimiter: i } = t;
if (r.dtype !== "string")
throw new Error("Input must be of datatype string");
if (r.shape.length !== 1)
throw new Error(`Input must be a vector, got shape: ${r.shape}`);
if (i.shape.length !== 0)
throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);
const a = e.readSync(r.dataId), l = e.readSync(i.dataId)[0], [c, u, h] = eP(a, l, o), d = u.length;
return [
e.makeTensorInfo([d, 2], "int32", c),
e.makeTensorInfo([d], "string", u),
e.makeTensorInfo([2], "int32", new Int32Array(h))
];
}
const BG = {
kernelName: im,
backendName: "webgl",
kernelFunc: zG
};
/**
* @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.
* =============================================================================
*/
function VG(n) {
const { inputs: t, backend: e, attrs: s } = n, { numBuckets: o } = s, { input: r } = t;
if (r.dtype !== "string")
throw new Error("Input must be of datatype string");
if (o <= 0)
throw new Error("Number of buckets must be at least 1");
const i = e.readSync(r.dataId), a = nP(i, o);
return e.makeTensorInfo(r.shape, "int32", a);
}
const WG = {
kernelName: am,
backendName: "webgl",
kernelFunc: VG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const UG = "return tan(x);", GG = vt({ opSnippet: UG }), HG = {
kernelName: xi,
backendName: "webgl",
kernelFunc: GG
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const KG = `
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`, jG = vt({ opSnippet: KG }), XG = {
kernelName: bi,
backendName: "webgl",
kernelFunc: jG
};
/**
* @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.
* =============================================================================
*/
function qG(n) {
const { inputs: t, backend: e, attrs: s } = n, { tensor: o, indices: r, updates: i } = t, { sliceRank: a, numUpdates: l, sliceSize: c, strides: u, outputSize: h } = io(i, r, o.shape), d = [h / c, c];
if (h === 0)
return e.makeTensorInfo(o.shape, r.dtype);
const p = tt({ inputs: { x: r }, backend: e, attrs: { shape: [l, a] } }), f = tt({ inputs: { x: i }, backend: e, attrs: { shape: [l, c] } }), m = tt({ inputs: { x: o }, backend: e, attrs: { shape: d } }), g = new tp(l, a, p.shape.length, f.shape.length, u, d, !1, !0), x = e.runWebGLProgram(g, [f, p, m], m.dtype), b = tt({ inputs: { x }, backend: e, attrs: { shape: o.shape } });
return e.disposeIntermediateTensorInfo(p), e.disposeIntermediateTensorInfo(f), e.disposeIntermediateTensorInfo(m), e.disposeIntermediateTensorInfo(x), b;
}
const YG = {
kernelName: Zf,
backendName: "webgl",
kernelFunc: qG
};
/**
* @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.
* =============================================================================
*/
class JG {
constructor(t, e) {
this.variableNames = ["A"];
const s = new Array(t.length);
for (let i = 0; i < s.length; i++)
s[i] = t[i] * e[i];
this.outputShape = s, this.rank = s.length;
const o = Ot(this.rank), r = ZG(t);
this.userCode = `
void main() {
${o} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`;
}
}
function ZG(n) {
const t = n.length;
if (t > 5)
throw Error(`Tile for rank ${t} is not yet supported`);
if (t === 1)
return `imod(resRC, ${n[0]})`;
const e = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u"], s = [];
for (let o = 0; o < n.length; o++)
s.push(`imod(${e[o]}, ${n[o]})`);
return s.join();
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function p1(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { reps: r } = s;
if (o.dtype === "string" || o.shape.length > 5) {
const l = e.readSync(o.dataId), c = o.dtype === "string" ? l.map((d) => ps(d)) : l, u = yt(o.shape, o.dtype, c), h = oP(u, r);
return e.makeTensorInfo(h.shape, h.dtype, h.values);
}
const i = new JG(o.shape, r);
return e.runWebGLProgram(i, [o], o.dtype);
}
const QG = {
kernelName: yi,
backendName: "webgl",
kernelFunc: p1
};
class tH {
/**
* @param shape desired output shape (can be larger than input shape, output
* will be padded with -Infinity)
*/
constructor(t) {
this.variableNames = ["x", "indices"], this.customUniforms = [
{ name: "n", type: "int" },
{ name: "firstPass", type: "int" },
{ name: "negativeInf", type: "float" },
{ name: "dir", type: "int" },
{ name: "inc", type: "int" }
], this.outputShape = t, 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 eH {
/**
* @param shape desired output shape (must be half of the input size)
*/
constructor(t) {
this.variableNames = ["x", "indices"], this.customUniforms = [
{ name: "n", type: "int" },
{ name: "firstPass", type: "int" },
{ name: "k", type: "int" }
], this.outputShape = t, 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));
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function Ds(n, t) {
t !== null && n.disposeIntermediateTensorInfo(t);
}
function Af(n) {
let t = 1;
for (; t < n; )
t *= 2;
return t;
}
function nH(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o } = t, { k: r, sorted: i } = s, a = P().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"), l = P().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"), c = o.shape, u = c[c.length - 1];
if (e.shouldExecuteOnCPU([o]) || u < a || r > l) {
const T = e.readSync(o.dataId), [F, L] = rP(T, c, o.dtype, r, i);
return [
e.makeTensorInfo(F.shape, F.dtype, F.values),
e.makeTensorInfo(L.shape, L.dtype, L.values)
];
}
if (r === 0)
return c[c.length - 1] = 0, [
e.makeTensorInfo(c, o.dtype, []),
e.makeTensorInfo(c, "int32", [])
];
if (u === 1)
return [
o,
Wi({ attrs: { shape: c, dtype: "int32", value: 0 }, backend: e })
];
const h = e.texData.get(o.dataId), d = h !== null && h.isPacked, p = d ? e.unpackTensor(o) : o, m = G(c) / u, g = tt({ inputs: { x: p }, attrs: { shape: [m, u] }, backend: e });
d && Ds(e, p);
const x = Af(r), b = Af(u);
let w = null;
const y = () => w === null ? [g, g] : [g, w], C = (T, F, L) => {
const M = y(), B = new tH(L), V = [[u], [w === null ? 1 : 0], [Number.NEGATIVE_INFINITY], [T], [F]], H = w;
w = e.runWebGLProgram(B, M, "int32", V), Ds(e, H);
};
for (let T = 1; T < x; T *= 2) {
const F = T * 2;
for (let L = T; L >= 1; L /= 2)
C(F, L, [m, b]);
}
for (let T = b; T > x; T /= 2) {
const F = y(), L = new eH([m, T / 2]), B = [[u], [w === null ? 1 : 0], [x]], z = w;
w = e.runWebGLProgram(L, F, "int32", B), Ds(e, z);
const V = x / 2, H = V * 2;
for (let U = V; U >= 1; U /= 2)
C(H, U, w.shape);
}
let $ = w;
w = Zo({ inputs: { x: w }, backend: e, attrs: { begin: 0, size: [m, r] } }), Ds(e, $);
let k = r1({ inputs: { x: g, indices: w }, backend: e, attrs: { axis: 1, batchDims: 1 } });
Ds(e, g);
const v = c.slice(0, -1);
v.push(r), $ = w, w = tt({ inputs: { x: w }, attrs: { shape: v }, backend: e }), Ds(e, $);
const S = k;
return k = tt({ inputs: { x: k }, attrs: { shape: v }, backend: e }), Ds(e, S), [k, w];
}
const sH = {
kernelName: ch,
backendName: "webgl",
kernelFunc: nH
};
/**
* @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.
* =============================================================================
*/
class oH {
constructor(t, e, s, o, r, i) {
this.variableNames = ["Image", "Transforms"], this.outputShape = i;
const a = s === "nearest" ? 1 : 2;
let l;
switch (o) {
case "constant":
l = 1;
break;
case "reflect":
l = 2;
break;
case "wrap":
l = 3;
break;
case "nearest":
l = 4;
break;
default:
l = 1;
break;
}
this.userCode = `
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${l} == 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 (${l} == 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 (${l} == 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 < ${t} && 0 <= coordX && coordX < ${e}) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = float(${r});
}
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(${r});
} else {
float inX = (a1 * xf + a2 * yf + a3) / projection;
float inY = (b1 * xf + b2 * yf + b3) / projection;
float mapX = mapCoord(inX, float(${e}));
float mapY = mapCoord(inY, float(${t}));
if (${a} == 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);
}
`;
}
}
/**
* @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.
* =============================================================================
*/
function rH(n) {
const { inputs: t, backend: e, attrs: s } = n, { image: o, transforms: r } = t, { interpolation: i, fillMode: a, fillValue: l, outputShape: c } = s, [u, h, d, p] = o.shape, [f, m] = c ?? [h, d], g = [
u,
f,
m,
p
], x = new oH(h, d, i, a, l, g);
return e.runWebGLProgram(x, [o, r], "float32");
}
const iH = {
kernelName: uh,
backendName: "webgl",
kernelFunc: rH
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function aH(n) {
const { inputs: t, attrs: e, backend: s } = n, { axis: o } = e, { x: r } = t;
zi(r, "unique"), console.warn("WARNING: ", "UI might be locked temporarily as data is being downloaded");
const i = s.readSync(r.dataId), { outputValues: a, outputShape: l, indices: c } = iP(i, o, r.shape, r.dtype);
return [
s.makeTensorInfo(l, r.dtype, a),
s.makeTensorInfo([c.length], "int32", c)
];
}
const lH = {
kernelName: hh,
backendName: "webgl",
kernelFunc: aH
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function cH(n) {
const { inputs: t, backend: e, attrs: s } = n, { value: o } = t;
let { axis: r } = s;
r < 0 && (r += o.shape.length);
const i = o, a = i.shape.length, l = o.shape[r], c = new Array(a - 1);
let u = 0;
for (let m = 0; m < a; m++)
m !== r && (c[u++] = i.shape[m]);
const h = [], d = new Array(a).fill(0), p = i.shape.slice();
p[r] = 1;
const f = new Array(l);
for (let m = 0; m < f.length; m++) {
d[r] = m;
const g = Zo({ inputs: { x: i }, backend: e, attrs: { begin: d, size: p } }), x = tt({ inputs: { x: g }, backend: e, attrs: { shape: c } });
f[m] = x, h.push(g);
}
return h.forEach((m) => e.disposeIntermediateTensorInfo(m)), f;
}
const uH = {
kernelName: Rl,
backendName: "webgl",
kernelFunc: cH
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class hH {
constructor(t, e) {
this.variableNames = ["x", "segmentIds"];
const s = t.windowSize, o = t.batchSize, r = t.inSize, i = t.numSegments, a = i * Math.ceil(r / s);
this.outputShape = [o, a];
const l = "0.0", c = "sumValue", u = Math.floor(s / 4) * 4, h = s % 4, d = `
sumValue += dot(values, segFilter);
`;
let p = "";
r % s > 0 && (p = `
if (inIdx < 0 || inIdx >= ${r}) {
return initializationValue;
}
`);
let f = "";
r % s > 0 && (f = `
if (inIdx < 0 || inIdx >= ${r}) {
return -1.0;
}
`), this.userCode = `
const float initializationValue = ${l};
float getValue(int batch, int inIdx) {
${p}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${f}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${i})) * float(${s}));
int currentSeg = int(mod(float(outIdx), float(${i})));
float sumValue = 0.0;
for (int i = 0; i < ${u}; 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
);
${d}
}
int inIdx = inOffset + ${u};
if (${h === 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
);
${d}
} else if (${h === 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
);
${d}
} else if (${h === 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
);
${d}
}
setOutput(${c});
}
`;
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function dH(n) {
const { inputs: t, backend: e, attrs: s } = n, { x: o, segmentIds: r } = t, { numSegments: i } = s, a = o.shape.length, l = [];
let c = 0;
const u = jt([c], a);
let h = o;
u != null && (h = De({ inputs: { x: o }, backend: e, attrs: { perm: u } }), l.push(h), c = Zt(1, a)[0]);
const d = Xg(h.shape, c, i), p = G([h.shape[c]]), f = tt({ inputs: { x: h }, backend: e, attrs: { shape: [-1, p] } });
l.push(f);
const m = ph(o.dtype), g = (y, C, $, k, v) => {
const S = y.shape[0], T = y.shape[1], F = jg(T, v), L = { windowSize: F, inSize: T, batchSize: S, numSegments: v }, M = new hH(L, C), B = e.compileAndRun(M, [y, $], k);
if (l.push(B), B.shape[1] === v)
return B;
const z = d1({
backend: e,
attrs: { start: 0, stop: v, step: 1, dtype: "float32" }
}), V = p1({
inputs: { x: z },
backend: e,
attrs: { reps: [T / F] }
});
return l.push(z), l.push(V), g(B, C, V, k, v);
}, x = g(f, "unsortedSegmentSum", r, m, i), b = tt({ inputs: { x }, backend: e, attrs: { shape: d } });
let w = b;
if (u != null) {
l.push(b);
const y = $s(u);
w = De({ inputs: { x: w }, backend: e, attrs: { perm: y } });
}
return l.forEach((y) => e.disposeIntermediateTensorInfo(y)), w;
}
const pH = {
kernelName: Dl,
backendName: "webgl",
kernelFunc: dH
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const fH = [
JP,
QP,
n3,
r3,
a3,
u3,
d3,
f3,
b3,
w3,
I3,
S3,
E3,
F3,
L3,
P3,
B3,
G3,
K3,
X3,
Z3,
rz,
az,
hz,
pz,
yz,
Cz,
vz,
OP,
Tz,
Fz,
Mz,
Uz,
Kz,
Xz,
Yz,
Zz,
nB,
rB,
lB,
uB,
dB,
fB,
xB,
yB,
IB,
vB,
TB,
DB,
FB,
MB,
VB,
HB,
XB,
JB,
ZB,
tV,
nV,
oV,
iV,
lV,
dV,
mV,
bV,
wV,
IV,
SV,
RV,
OV,
FP,
LV,
Dz,
zV,
WV,
HV,
LP,
qV,
QV,
eW,
rW,
lW,
dW,
mW,
yW,
IW,
SW,
TW,
AW,
OW,
LW,
BW,
WW,
GW,
KW,
XW,
ZW,
n4,
i4,
f4,
zP,
b4,
C4,
k4,
N4,
mz,
R4,
A4,
O4,
M4,
V4,
PP,
U4,
H4,
j4,
q4,
Y4,
gz,
u4,
Q4,
sU,
aU,
VP,
hU,
fU,
bU,
CU,
vU,
NU,
RU,
FU,
LU,
zU,
WU,
HU,
qU,
ZU,
nG,
rG,
sz,
d4,
lG,
uG,
dG,
fG,
gG,
bG,
wG,
$G,
kG,
NG,
EG,
DG,
FG,
LG,
PG,
BG,
WG,
h4,
XP,
HG,
XG,
YG,
QG,
sH,
iH,
qP,
lH,
uH,
pH,
D4
];
for (const n of fH)
cm(n);
export {
Fa as Abs,
Sr as Acos,
Nr as Acosh,
hg as AdadeltaOptimizer,
dg as AdagradOptimizer,
pg as AdamOptimizer,
fg as AdamaxOptimizer,
Po as Add,
Su as AddN,
Nu as All,
Tu as Any,
Oa as ArgMax,
_a as ArgMin,
Tr as Asin,
Er as Asinh,
Rr as Atan,
Ar as Atan2,
Dr as Atanh,
La as AvgPool,
Ma as AvgPool3D,
Ru as AvgPool3DGrad,
Eu as AvgPoolGrad,
Pa as BatchMatMul,
za as BatchToSpaceND,
Du as Bincount,
Au as BitwiseAnd,
Wf as BroadcastArgs,
X1 as BroadcastTo,
W2 as CallbackList,
Fr as Cast,
Or as Ceil,
_r as ClipByValue,
Fu as Complex,
Ba as ComplexAbs,
Va as Concat,
Wa as Conv2D,
Ou as Conv2DBackpropFilter,
Ua as Conv2DBackpropInput,
Ga as Conv3D,
_u as Conv3DBackpropFilterV2,
Lu as Conv3DBackpropInputV2,
Lr as Cos,
Mr as Cosh,
Pu as CropAndResize,
Mu as Cumprod,
Ha as Cumsum,
H2 as CustomCallback,
Of as DataStorage,
zu as DenseBincount,
Bu as DepthToSpace,
Ka as DepthwiseConv2dNative,
Vu as DepthwiseConv2dNativeBackpropFilter,
Wu as DepthwiseConv2dNativeBackpropInput,
Uf as Diag,
ja as Dilation2D,
Oc as Dilation2DBackpropFilter,
Fc as Dilation2DBackpropInput,
q1 as Draw,
Bf as ENV,
Uu as Einsum,
zr as Elu,
Gu as EluGrad,
W1 as Environment,
Xa as Equal,
Br as Erf,
Vr as Exp,
qa as ExpandDims,
Wr as Expm1,
Hu as FFT,
Ku as Fill,
ju as FlipLeftRight,
Ur as Floor,
Gr as FloorDiv,
J1 as FromPixels,
Ya as FusedBatchNorm,
aa as FusedConv2D,
lm as FusedDepthwiseConv2D,
Nc as GPGPUContext,
Gf as GatherNd,
Ja as GatherV2,
Za as Greater,
Hr as GreaterEqual,
G2 as History,
Xu as IFFT,
Kr as Identity,
qu as Imag,
re as InputSpec,
jr as IsFinite,
Xr as IsInf,
qr as IsNan,
wu as KernelBackend,
rl as LRN,
Yu as LRNGrad,
S2 as LayerVariable,
Io as LayersModel,
Qa as LeakyRelu,
tl as Less,
el as LessEqual,
Hf as LinSpace,
Yr as Log,
Jr as Log1p,
Y1 as LogSoftmax,
nl as LogicalAnd,
sl as LogicalNot,
ol as LogicalOr,
nc as MathBackendCPU,
rc as MathBackendWebGL,
il as Max,
al as MaxPool,
ll as MaxPool3D,
Zu as MaxPool3DGrad,
Ju as MaxPoolGrad,
Kf as MaxPoolWithArgmax,
Zr as Maximum,
cl as Mean,
ul as Min,
Qr as Minimum,
hl as MirrorPad,
ti as Mod,
mg as MomentumOptimizer,
jf as Multinomial,
ei as Multiply,
dl as Neg,
Qu as NonMaxSuppressionV3,
th as NonMaxSuppressionV4,
eh as NonMaxSuppressionV5,
pl as NotEqual,
ww as OP_SCOPE_SUFFIX,
ml as OneHot,
fl as OnesLike,
vs as Optimizer,
Kv as OptimizerConstructors,
gl as Pack,
xl as PadV2,
ni as Pow,
bl as Prelu,
yl as Prod,
gg as RMSPropOptimizer,
Ss as RNN,
Xf as RaggedGather,
qf as RaggedRange,
Yf as RaggedTensorToTensor,
nh as Range,
lp as Rank,
sh as Real,
Pr as RealDiv,
si as Reciprocal,
oi as Relu,
ri as Relu6,
wl as Reshape,
$l as ResizeBilinear,
rh as ResizeBilinearGrad,
Cl as ResizeNearestNeighbor,
oh as ResizeNearestNeighborGrad,
Il as Reverse,
dh as RotateWithOffset,
ii as Round,
ai as Rsqrt,
Uh as SGDOptimizer,
Jf as ScatterNd,
Qf as SearchSorted,
kl as Select,
li as Selu,
yr as Sequential,
di as Sigmoid,
hi as Sign,
ci as Sin,
ui as Sinh,
vl as Slice,
El as Softmax,
pi as Softplus,
Nl as SpaceToBatchND,
tm as SparseFillEmptyRows,
em as SparseReshape,
nm as SparseSegmentMean,
sm as SparseSegmentSum,
om as SparseToDense,
Tl as SplitV,
fi as Sqrt,
ih as Square,
mi as SquaredDifference,
ah as StaticRegexReplace,
wi as Step,
lh as StridedSlice,
rm as StringNGrams,
im as StringSplit,
am as StringToHashBucketFast,
gi as Sub,
Sl as Sum,
Pn as SymbolicTensor,
xi as Tan,
bi as Tanh,
se as Tensor,
ge as TensorBuffer,
Zf as TensorScatterUpdate,
yi as Tile,
ch as TopK,
uh as Transform,
Co as Transpose,
hh as Unique,
Rl as Unpack,
Dl as UnsortedSegmentSum,
ca as Variable,
Al as ZerosLike,
ia as _FusedMatMul,
Ne as abs,
Qw as acos,
eC as acosh,
Y as add,
Om as all,
Hc as any,
dr as argMax,
iC as argMin,
lC as asin,
uC as asinh,
dC as atan,
fC as atan2,
gC as atanh,
gh as avgPool,
kC as avgPool3d,
Iw as backend,
Jv as backend_util,
Ml as batchNorm,
OC as batchNorm2d,
LC as batchNorm3d,
PC as batchNorm4d,
xh as batchToSpaceND,
BC as bincount,
ur as broadcastTo,
yt as buffer,
st as cast,
UC as ceil,
Ye as clipByValue,
Ps as clone,
No as complex,
Le as concat,
KC as concat1d,
XC as concat2d,
YC as concat3d,
ZC as concat4d,
_m as conv1d,
js as conv2d,
Lm as conv2dTranspose,
o$ as conv3d,
a$ as conv3dTranspose,
yh as cos,
Pm as cosh,
jc as cumprod,
zm as cumsum,
Eo as customGrad,
mp as denseBincount,
f$ as depthToSpace,
wh as depthwiseConv2d,
x$ as dilation2d,
$t as dispose,
ut as div,
$$ as divNoNan,
k$ as dot,
Bk as dropout,
er as einsum,
zl as elu,
kn as engine,
P as env,
_n as equal,
Bm as erf,
L$ as euclideanNorm,
Ln as exp,
Oe as expandDims,
B$ as expm1,
Um as eye,
og as fft,
Pl as fill,
Vl as floor,
Fm as floorDiv,
$h as gather,
op as getGradient,
sp as getKernel,
rp as getKernelsForBackend,
Je as greater,
oo as greaterEqual,
Xc as ifft,
Ih as imag,
Hn as image,
mk as irfft,
q$ as isFinite,
J$ as isInf,
Q$ as isNaN,
Dn as keep,
kh as leakyRelu,
ha as less,
Vo as lessEqual,
Lv as linalg,
oI as localResponseNormalization,
Mn as log,
Gm as log1p,
hI as logSigmoid,
Hm as logSoftmax,
Km as logSumExp,
jn as logicalAnd,
vh as logicalNot,
jm as logicalOr,
yI as logicalXor,
Nt as matMul,
bn as max,
Sh as maxPool,
$I as maxPool3d,
Is as maximum,
ee as mean,
Vc as memory,
ua as min,
mr as minimum,
NI as mirrorPad,
EI as mod,
Nh as moments,
R as mul,
Yt as neg,
vg as nextFrame,
Bl as norm,
da as notEqual,
Xm as oneHot,
ks as ones,
an as onesLike,
O as op,
Th as pad,
zI as pool,
Xs as pow,
Rh as prelu,
Hw as print,
WI as prod,
HI as randomNormal,
Ii as randomUniform,
gr as range,
yH as ready,
pa as real,
qI as reciprocal,
vm as registerBackend,
Q1 as registerGradient,
cm as registerKernel,
ro as relu,
Ym as relu6,
A as reshape,
qs as reverse,
bk as rfft,
Jm as round,
Zm as rsqrt,
Tt as scalar,
Qm as selu,
tg as separableConv2d,
bH as setBackend,
S_ as setWebGLContext,
cR as shared,
Bo as sigmoid,
ok as sign,
eg as sin,
ng as sinh,
zt as slice,
Dh as slice1d,
sg as slice2d,
Ah as slice3d,
fa as slice4d,
Hv as slice_util,
Fh as softmax,
$i as softplus,
Eh as spaceToBatchND,
qe as split,
$e as sqrt,
Vt as square,
wk as squaredDifference,
ki as squeeze,
Xn as stack,
vi as step,
vk as stridedSlice,
pt as sub,
ct as sum,
ph as sumOutType,
Nk as tan,
Ll as tanh,
km as tensor,
We as tensor1d,
mc as tensor2d,
_ as tidy,
gn as tile,
Rk as topk,
fo as train,
It as transpose,
ig as truncatedNormal,
Fk as unique,
ag as unsortedSegmentSum,
Ys as unstack,
Ue as upcastType,
Lk as variable,
aI as variableGrads,
Ex as version_layers,
Re as where,
he as zeros,
kt as zerosLike
};